answer stringlengths 17 10.2M |
|---|
package org.jboss.netty.channel;
/**
* An I/O event or I/O request associated with a {@link Channel}.
* <p>
* A {@link ChannelEvent} is supposed to be handled by the
* {@link ChannelPipeline} which is owned by the {@link Channel} that
* the event belongs to. Once an event is sent to a {@link ChannelPipeline},
* it is handled by a list of {@link ChannelHandler}s.
*
* <h3>Upstream events and downstream events, and their interpretation</h3>
* <p>
* If an event flows from the first handler to the last handler in a
* {@link ChannelPipeline}, we call it a upstream event and say <strong>"an
* event goes upstream."</strong> If an event flows from the last handler to
* the first handler in a {@link ChannelPipeline}, we call it a downstream
* event and say <strong>"an event goes downstream."</strong> (Please refer
* to the diagram in {@link ChannelPipeline} for more explanation.)
* <p>
* A {@link ChannelEvent} is interpreted differently by a {@link ChannelHandler}
* depending on whether the event is a upstream event or a downstream event.
* A upstream event represents the notification of what happened in the past.
* By contrast, a downstream event represents the request of what should happen
* in the future. For example, a {@link MessageEvent} represents the
* notification of a received message when it goes upstream, while it
* represents the request of writing a message when it goes downstream.
* <p>
* Please refer to the documentation of {@link ChannelHandler} and its sub-types
* ({@link ChannelUpstreamHandler} for upstream events and
* {@link ChannelDownstreamHandler} for downstream events) to find out how
* a {@link ChannelEvent} is interpreted depending on the type of the handler
* more in detail.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Trustin Lee (tlee@redhat.com)
*
* @version $Rev$, $Date$
*
* @apiviz.landmark
* @apiviz.composedOf org.jboss.netty.channel.ChannelFuture
*/
public interface ChannelEvent {
/**
* Returns the {@link Channel} which is associated with this event.
*/
Channel getChannel();
/**
* Returns the {@link ChannelFuture} which is associated with this event.
* If this event is a upstream event, this method will always return a
* {@link SucceededChannelFuture} because the event has occurred already.
* If this event is a downstream event (i.e. I/O request), the returned
* future will be notified when the I/O request succeeds or fails.
*/
ChannelFuture getFuture();
} |
package org.jitsi.impl.neomedia.codec;
import org.jitsi.util.*;
import java.nio.*;
/**
* Provides the interface to the native FFmpeg library.
*
* @author Lyubomir Marinov
* @author Sebastien Vincent
*/
public class FFmpeg
{
/**
* No pts value.
*/
public static final long AV_NOPTS_VALUE = 0x8000000000000000L;
public static final int AV_NUM_DATA_POINTERS = 8;
/**
* The AV sample format for signed 16.
*/
public static final int AV_SAMPLE_FMT_S16 = 1;
/**
* The AV sample format for signed 16 planar.
*/
public static final int AV_SAMPLE_FMT_S16P = 6;
/**
* AC pred flag.
*/
public static final int CODEC_FLAG_AC_PRED = 0x02000000;
/**
* H263+ slice struct flag.
*/
public static final int CODEC_FLAG_H263P_SLICE_STRUCT = 0x10000000;
/**
* H263+ UMV flag.
*/
public static final int CODEC_FLAG_H263P_UMV = 0x01000000 ;
/**
* Loop filter flag.
*/
public static final int CODEC_FLAG_LOOP_FILTER = 0x00000800;
/**
* The flag which allows incomplete frames to be passed to a decoder.
*/
public static final int CODEC_FLAG2_CHUNKS = 0x00008000;
/**
* Intra refresh flag2.
*/
public static final int CODEC_FLAG2_INTRA_REFRESH = 0x00200000;
/**
* AMR-NB codec ID.
*/
private static final int CODEC_ID_AMR_NB = 0x12000;
/**
* AMR-WB codec ID
*/
public static final int CODEC_ID_AMR_WB = CODEC_ID_AMR_NB + 1;
/**
* H263 codec ID.
*/
public static final int CODEC_ID_H263 = 5;
/**
* H263+ codec ID.
*/
public static final int CODEC_ID_H263P = 20;
/**
* H264 codec ID.
*/
public static final int CODEC_ID_H264 = 28;
/**
* MJPEG codec ID.
*/
public static final int CODEC_ID_MJPEG = 8;
/**
* MP3 codec ID.
*/
public static final int CODEC_ID_MP3 = 0x15000 + 1;
/**
* VP8 codec ID
*/
public static final int CODEC_ID_VP8 = 142;
/**
* Work around bugs in encoders which sometimes cannot be detected
* automatically.
*/
public static final int FF_BUG_AUTODETECT = 1;
public static final int FF_CMP_CHROMA = 256;
/**
* Padding size for FFmpeg input buffer.
*/
public static final int FF_INPUT_BUFFER_PADDING_SIZE = 8;
public static final int FF_MB_DECISION_SIMPLE = 0;
/**
* The minimum encoding buffer size defined by libavcodec.
*/
public static final int FF_MIN_BUFFER_SIZE = 16384;
/**
* The H264 baseline profile.
*/
public static final int FF_PROFILE_H264_BASELINE = 66;
/**
* The H264 high profile.
*/
public static final int FF_PROFILE_H264_HIGH = 100;
/**
* The H264 main profile.
*/
public static final int FF_PROFILE_H264_MAIN = 77;
/**
* ARGB format.
*/
public static final int PIX_FMT_ARGB = 27;
/**
* BGR24 format as of FFmpeg.
*/
public static final int PIX_FMT_BGR24_1 = 3;
/**
* BGR32 format handled in endian specific manner.
* It is stored as ABGR on big-endian and RGBA on little-endian.
*/
public static final int PIX_FMT_BGR32;
/**
* BGR32_1 format handled in endian specific manner.
* It is stored as BGRA on big-endian and ARGB on little-endian.
*/
public static final int PIX_FMT_BGR32_1;
/**
* "NONE" format.
*/
public static final int PIX_FMT_NONE = -1;
/**
* NV12 format.
*/
public static final int PIX_FMT_NV12 = 25;
/**
* RGB24 format handled in endian specific manner.
* It is stored as RGB on big-endian and BGR on little-endian.
*/
public static final int PIX_FMT_RGB24;
/**
* RGB24 format as of FFmpeg.
*/
public static final int PIX_FMT_RGB24_1 = 2;
/**
* RGB32 format handled in endian specific manner.
* It is stored as ARGB on big-endian and BGRA on little-endian.
*/
public static final int PIX_FMT_RGB32;
/**
* RGB32_1 format handled in endian specific manner.
* It is stored as RGBA on big-endian and ABGR on little-endian.
*/
public static final int PIX_FMT_RGB32_1;
/**
* UYVY422 format.
*/
public static final int PIX_FMT_UYVY422 = 17;
/**
* UYYVYY411 format.
*/
public static final int PIX_FMT_UYYVYY411 = 18;
/** Y41P format */
public static final int PIX_FMT_YUV411P = 7;
/**
* YUV420P format.
*/
public static final int PIX_FMT_YUV420P = 0;
/**
* YUVJ422P format.
*/
public static final int PIX_FMT_YUVJ422P = 13;
/**
* YUYV422 format.
*/
public static final int PIX_FMT_YUYV422 = 1;
/**
* BICUBIC type for libswscale conversion.
*/
public static final int SWS_BICUBIC = 4;
//public static final int X264_RC_ABR = 2;
static
{
try
{
System.loadLibrary("libopenh264");
}
catch (Throwable t){}
boolean jnffmpegLoaded = false;
try
{
JNIUtils.loadLibrary("jnffmpeg", FFmpeg.class.getClassLoader());
jnffmpegLoaded = true;
}
catch (Throwable t)
{
// TODO remove stacktrace print
t.printStackTrace();
}
try
{
if (!jnffmpegLoaded)
JNIUtils.loadLibrary(
"jnffmpeg-no-openh264", FFmpeg.class.getClassLoader());
}
catch (Throwable t)
{
// TODO remove stacktrace print
t.printStackTrace();
throw t;
}
av_register_all();
avcodec_register_all();
avfilter_register_all();
if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN))
{
PIX_FMT_RGB24 = av_get_pix_fmt("rgb24");
PIX_FMT_RGB32 = av_get_pix_fmt("argb");
PIX_FMT_RGB32_1 = av_get_pix_fmt("rgba");
PIX_FMT_BGR32 = av_get_pix_fmt("abgr");
PIX_FMT_BGR32_1 = av_get_pix_fmt("bgra");
}
else
{
PIX_FMT_RGB24 = av_get_pix_fmt("bgr24");
PIX_FMT_RGB32 = av_get_pix_fmt("bgra");
PIX_FMT_RGB32_1 = av_get_pix_fmt("abgr");
PIX_FMT_BGR32 = av_get_pix_fmt("rgba");
PIX_FMT_BGR32_1 = av_get_pix_fmt("argb");
}
}
public static native String av_strerror(int errnum);
public static native int av_get_pix_fmt(String name);
/**
* Free a native pointer allocated by av_malloc.
*
* @param ptr native pointer to free
*/
public static native void av_free(long ptr);
/**
* Allocate memory.
*
* @param size size to allocate
* @return native pointer or 0 if av_malloc failed
*/
public static native long av_malloc(int size);
/**
* Initialize libavformat and register all the muxers, demuxers and
* protocols.
*/
public static native void av_register_all();
/**
* Allocates a new <tt>AVCodecContext</tt>.
*
* @param codec
* @return native pointer to the new <tt>AVCodecContext</tt>
*/
public static native long avcodec_alloc_context3(long codec);
/**
* Allocates an <tt>AVFrame</tt> instance and sets its fields to default
* values. The result must be freed using {@link #avcodec_free_frame(long)}.
*
* @return an <tt>AVFrame *</tt> value which points to an <tt>AVFrame</tt>
* instance filled with default values or <tt>0</tt> on failure
*/
public static native long avcodec_alloc_frame();
public static native long avcodec_alloc_packet(int size);
/**
* Close an AVCodecContext
*
* @param ctx pointer to AVCodecContex
* @return 0 if success, -1 otherwise
*/
public static native int avcodec_close(long ctx);
public static native int avcodec_decode_audio4(long avctx, long frame,
boolean[] got_frame, long avpkt);
/**
* Decode a video frame.
*
* @param ctx codec context
* @param frame frame decoded
* @param got_picture if the decoding has produced a valid picture
* @param buf the input buffer
* @param buf_size input buffer size
* @return number of bytes written to buff if success
*/
public static native int avcodec_decode_video(long ctx, long frame,
boolean[] got_picture, byte[] buf, int buf_size);
/**
* Decode a video frame.
*
* @param ctx codec context
* @param avframe frame decoded
* @param src input buffer
* @param src_length input buffer size
* @return number of bytes written to buff if success
*/
public static native int avcodec_decode_video(long ctx, long avframe,
long src, int src_length);
/**
* Encodes an audio frame from <tt>samples</tt> into <tt>buf</tt>.
*
* @param ctx the codec context
* @param buf the output buffer
* @param buf_offset the output buffer offset
* @param buf_size the output buffer size
* @param samples the input buffer containing the samples. The number of
* samples read from this buffer is <tt>frame_size</tt>*<tt>channels</tt>,
* both of which are defined in <tt>ctx</tt>. For PCM audio the number of
* samples read from samples is equal to
* <tt>buf_size</tt>*<tt>input_sample_size</tt>/<tt>output_sample_size</tt>.
* @param samples_offset the offset in the input buffer containing the
* samples
* @return on error a negative value is returned, on success zero or the
* number of bytes used to encode the data read from the input buffer
*/
public static native int avcodec_encode_audio(
long ctx,
byte[] buf, int buf_offset, int buf_size,
byte[] samples, int samples_offset);
/**
* Encode a video frame.
*
* @param ctx codec context
* @param buff the output buffer
* @param buf_size output buffer size
* @param frame frame to encode
* @return number of bytes written to buff if success
*/
public static native int avcodec_encode_video(long ctx, byte[] buff,
int buf_size, long frame);
/**
* Finds a registered decoder with a matching ID.
*
* @param id <tt>AVCodecID</tt> of the requested encoder
* @return an <tt>AVCodec</tt> decoder if one was found; <tt>0</tt>,
* otherwise
*/
public static native long avcodec_find_decoder(int id);
/**
* Finds a registered encoder with a matching codec ID.
*
* @param id <tt>AVCodecID</tt> of the requested encoder
* @return an <tt>AVCodec</tt> encoder if one was found; <tt>0</tt>,
* otherwise
*/
public static native long avcodec_find_encoder(int id);
/**
* Frees an <tt>AVFrame</tt> instance specified as an <tt>AVFrame *</tt>
* value and any dynamically allocated objects in it (e.g.
* <tt>extended_data</tt>).
* <p>
* <b>Warning</b>: The method/function does NOT free the data buffers
* themselves because it does not know how since they might have been
* allocated with a custom <tt>get_buffer()</tt>.
* </p>
*
* @param frame an <tt>AVFrame *</tt> value which points to the
* <tt>AVFrame</tt> instance to be freed
*/
public static void avcodec_free_frame(long frame)
{
// FIXME Invoke the native function avcodec_free_frame(AVFrame **).
av_free(frame);
}
public static native void avcodec_free_packet(long pkt);
/**
* Initializes the specified <tt>AVCodecContext</tt> to use the specified
* <tt>AVCodec</tt>.
*
* @param ctx the <tt>AVCodecContext</tt> which will be set up to use the
* specified <tt>AVCodec</tt>
* @param codec the <tt>AVCodec</tt> to use within the
* <tt>AVCodecContext</tt>
* @param options
* @return zero on success, a negative value on error
*/
public static native int avcodec_open2(
long ctx,
long codec,
String... options);
public static native void avcodec_register_all();
/**
* Add specific flags to AVCodecContext's flags member.
*
* @param ctx pointer to AVCodecContext
* @param flags flags to add
*/
public static native void avcodeccontext_add_flags(long ctx, int flags);
/**
* Add specific flags to AVCodecContext's flags2 member.
*
* @param ctx pointer to AVCodecContext
* @param flags2 flags to add
*/
public static native void avcodeccontext_add_flags2(long ctx, int flags2);
/**
* Gets the samples per packet of the specified <tt>AVCodecContext</tt>. The
* property is set by libavcodec upon {@link #avcodec_open(long, long)}.
*
* @param ctx the <tt>AVCodecContext</tt> to get the samples per packet of
* @return the samples per packet of the specified <tt>AVCodecContext</tt>
*/
public static native int avcodeccontext_get_frame_size(long ctx);
/**
* Get height of the video.
*
* @param ctx pointer to AVCodecContext
* @return video height
*/
public static native int avcodeccontext_get_height(long ctx);
/**
* Get pixel format.
*
* @param ctx pointer to AVCodecContext
* @return pixel format
*/
public static native int avcodeccontext_get_pix_fmt(long ctx);
/**
* Get width of the video.
*
* @param ctx pointer to AVCodecContext
* @return video width
*/
public static native int avcodeccontext_get_width(long ctx);
/**
* Set the B-Frame strategy.
*
* @param ctx AVCodecContext pointer
* @param b_frame_strategy strategy
*/
public static native void avcodeccontext_set_b_frame_strategy(long ctx,
int b_frame_strategy);
/**
* Sets the average bit rate of the specified <tt>AVCodecContext</tt>. The
* property is to be set by the user when encoding and is unused for
* constant quantizer encoding. It is set by libavcodec when decoding and
* its value is <tt>0</tt> or some bitrate if this info is available in the
* stream.
*
* @param ctx the <tt>AVCodecContext</tt> to set the average bit rate of
* @param bit_rate the average bit rate to be set to the specified
* <tt>AVCodecContext</tt>
*/
public static native void avcodeccontext_set_bit_rate(long ctx,
int bit_rate);
/**
* Set the bit rate tolerance
*
* @param ctx the <tt>AVCodecContext</tt> to set the bit rate of
* @param bit_rate_tolerance bit rate tolerance
*/
public static native void avcodeccontext_set_bit_rate_tolerance(long ctx,
int bit_rate_tolerance);
/**
* Sets the number of channels of the specified <tt>AVCodecContext</tt>. The
* property is audio only.
*
* @param ctx the <tt>AVCodecContext</tt> to set the number of channels of
* @param channels the number of channels to set to the specified
* <tt>AVCodecContext</tt>
*/
public static native void avcodeccontext_set_channels(
long ctx, int channels);
public static native void avcodeccontext_set_channel_layout(
long ctx, int channelLayout);
public static native void avcodeccontext_set_chromaoffset(long ctx,
int chromaoffset);
/**
* Sets the maximum number of pictures in a group of pictures i.e. the
* maximum interval between keyframes.
*
* @param ctx the <tt>AVCodecContext</tt> to set the <tt>gop_size</tt> of
* @param gop_size the maximum number of pictures in a group of pictures
* i.e. the maximum interval between keyframes
*/
public static native void avcodeccontext_set_gop_size(long ctx,
int gop_size);
public static native void avcodeccontext_set_i_quant_factor(long ctx,
float i_quant_factor);
/**
* Sets the minimum GOP size.
*
* @param ctx the <tt>AVCodecContext</tt> to set the minimum GOP size of
* @param keyint_min the minimum GOP size to set on <tt>ctx</tt>
*/
public static native void avcodeccontext_set_keyint_min(long ctx,
int keyint_min);
/**
* Set the maximum B frames.
*
* @param ctx the <tt>AVCodecContext</tt> to set the maximum B frames of
* @param max_b_frames maximum B frames
*/
public static native void avcodeccontext_set_max_b_frames(long ctx,
int max_b_frames);
public static native void avcodeccontext_set_mb_decision(long ctx,
int mb_decision);
public static native void avcodeccontext_set_me_cmp(long ctx, int me_cmp);
public static native void avcodeccontext_set_me_method(long ctx,
int me_method);
public static native void avcodeccontext_set_me_range(long ctx,
int me_range);
public static native void avcodeccontext_set_me_subpel_quality(long ctx,
int me_subpel_quality);
/**
* Set the pixel format.
*
* @param ctx the <tt>AVCodecContext</tt> to set the pixel format of
* @param pix_fmt pixel format
*/
public static native void avcodeccontext_set_pix_fmt(long ctx,
int pix_fmt);
public static native void avcodeccontext_set_profile(long ctx,
int profile);
public static native void avcodeccontext_set_qcompress(long ctx,
float qcompress);
public static native void avcodeccontext_set_quantizer(long ctx,
int qmin, int qmax, int max_qdiff);
public static native void avcodeccontext_set_rc_buffer_size(long ctx,
int rc_buffer_size);
public static native void avcodeccontext_set_rc_eq(long ctx, String rc_eq);
public static native void avcodeccontext_set_rc_max_rate(long ctx,
int rc_max_rate);
public static native void avcodeccontext_set_refs(long ctx,
int refs);
/**
* Set the RTP payload size.
*
* @param ctx the <tt>AVCodecContext</tt> to set the RTP payload size of
* @param rtp_payload_size RTP payload size
*/
public static native void avcodeccontext_set_rtp_payload_size(long ctx,
int rtp_payload_size);
public static native void avcodeccontext_set_sample_aspect_ratio(
long ctx, int num, int den);
public static native void avcodeccontext_set_sample_fmt(
long ctx, int sample_fmt);
/**
* Sets the samples per second of the specified <tt>AVCodecContext</tt>. The
* property is audio only.
*
* @param ctx the <tt>AVCodecContext</tt> to set the samples per second of
* @param sample_rate the samples per second to set to the specified
* <tt>AVCodecContext</tt>
*/
public static native void avcodeccontext_set_sample_rate(
long ctx, int sample_rate);
/**
* Set the scene change threshold (in percent).
*
* @param ctx AVCodecContext pointer
* @param scenechange_threshold value between 0 and 100
*/
public static native void avcodeccontext_set_scenechange_threshold(
long ctx, int scenechange_threshold);
/**
* Set the size of the video.
*
* @param ctx pointer to AVCodecContext
* @param width video width
* @param height video height
*/
public static native void avcodeccontext_set_size(long ctx, int width,
int height);
/**
* Set the number of thread.
*
* @param ctx the <tt>AVCodecContext</tt> to set the number of thread of
* @param thread_count number of thread to set
*/
public static native void avcodeccontext_set_thread_count(long ctx,
int thread_count);
public static native void avcodeccontext_set_ticks_per_frame(long ctx,
int ticks_per_frame);
public static native void avcodeccontext_set_time_base(long ctx, int num,
int den);
public static native void avcodeccontext_set_trellis(long ctx,
int trellis);
public static native void avcodeccontext_set_workaround_bugs(long ctx,
int workaround_bugs);
/**
* Allocates a new <tt>AVFilterGraph</tt> instance.
*
* @return a pointer to the newly-allocated <tt>AVFilterGraph</tt> instance
*/
public static native long avfilter_graph_alloc();
/**
* Checks the validity and configures all the links and formats in a
* specific <tt>AVFilterGraph</tt> instance.
*
* @param graph a pointer to the <tt>AVFilterGraph</tt> instance to check
* the validity of and configure
* @param log_ctx the <tt>AVClass</tt> context to be used for logging
* @return <tt>0</tt> on success; a negative <tt>AVERROR</tt> on error
*/
public static native int avfilter_graph_config(long graph, long log_ctx);
/**
* Frees a specific <tt>AVFilterGraph</tt> instance and destroys its links.
*
* @param graph a pointer to the <tt>AVFilterGraph</tt> instance to free
*/
public static native void avfilter_graph_free(long graph);
/**
* Gets a pointer to an <tt>AVFilterContext</tt> instance with a specific
* name in a specific <tt>AVFilterGraph</tt> instance.
*
* @param graph a pointer to the <tt>AVFilterGraph</tt> instance where the
* <tt>AVFilterContext</tt> instance with the specified name is to be found
* @param name the name of the <tt>AVFilterContext</tt> instance which is to
* be found in the specified <tt>graph</tt>
* @return the filter graph pointer
*/
public static native long avfilter_graph_get_filter(
long graph,
String name);
/**
* Adds a filter graph described by a <tt>String</tt> to a specific
* <tt>AVFilterGraph</tt> instance.
*
* @param graph a pointer to the <tt>AVFilterGraph</tt> instance where to
* link the parsed graph context
* @param filters the <tt>String</tt> to be parsed
* @param inputs a pointer to a linked list to the inputs of the graph if
* any; otherwise, <tt>0</tt>
* @param outputs a pointer to a linked list to the outputs of the graph if
* any; otherwise, <tt>0</tt>
* @param log_ctx the <tt>AVClass</tt> context to be used for logging
* @return <tt>0</tt> on success; a negative <tt>AVERROR</tt> on error
*/
public static native int avfilter_graph_parse(
long graph,
String filters, long inputs, long outputs, long log_ctx);
/**
* Initializes the <tt>libavfilter</tt> system and registers all built-in
* filters.
*/
public static native void avfilter_register_all();
public static native long avframe_get_data0(long frame);
public static native int avframe_get_linesize0(long frame);
public static native long avframe_get_pts(long frame);
public static native void avframe_set_data(
long frame,
long data0, long offset1, long offset2);
public static native void avframe_set_key_frame(
long frame,
boolean key_frame);
public static native void avframe_set_linesize(
long frame,
int linesize0, int linesize1, int linesize2);
public static native void avpacket_set_data(
long pkt,
byte[] data, int offset, int length);
public static native int avpicture_fill(long picture, long ptr,
int pix_fmt, int width, int height);
public static native long get_filtered_video_frame(
long input, int width, int height, int pixFmt,
long buffer,
long ffsink,
long output);
public static native void memcpy(byte[] dst, int dst_offset, int dst_length,
long src);
public static native void memcpy(int[] dst, int dst_offset, int dst_length,
long src);
public static native void memcpy(long dst, byte[] src, int src_offset,
int src_length);
/**
* Get BGR32 pixel format.
*
* @return BGR32 pixel format
*/
private static native int PIX_FMT_BGR32();
/**
* Get BGR32_1 pixel format.
*
* @return BGR32_1 pixel format
*/
private static native int PIX_FMT_BGR32_1();
/**
* Get RGB24 pixel format.
*
* @return RGB24 pixel format
*/
private static native int PIX_FMT_RGB24();
/**
* Get RGB32 pixel format.
*
* @return RGB32 pixel format
*/
private static native int PIX_FMT_RGB32();
/**
* Get RGB32_1 pixel format.
*
* @return RGB32_1 pixel format
*/
private static native int PIX_FMT_RGB32_1();
/**
* Free an SwsContext.
*
* @param ctx SwsContext native pointer
*/
public static native void sws_freeContext(long ctx);
/**
* Get a SwsContext pointer.
*
* @param ctx SwsContext
* @param srcW width of source image
* @param srcH height of source image
* @param srcFormat image format
* @param dstW width of destination image
* @param dstH height destination image
* @param dstFormat destination format
* @param flags flags
* @return cached SwsContext pointer
*/
public static native long sws_getCachedContext(
long ctx,
int srcW, int srcH, int srcFormat,
int dstW, int dstH, int dstFormat,
int flags);
/**
* Scale an image.
*
* @param ctx SwsContext native pointer
* @param src source image (native pointer)
* @param srcSliceY slice Y of source image
* @param srcSliceH slice H of source image
* @param dst destination image (java type)
* @param dstFormat destination format
* @param dstW width of destination image
* @param dstH height destination image
* @return 0 if success, -1 otherwise
*/
public static native int sws_scale(
long ctx,
long src, int srcSliceY, int srcSliceH,
Object dst, int dstFormat, int dstW, int dstH);
/**
* Scale image an image.
*
* @param ctx SwsContext native pointer
* @param src source image (java type)
* @param srcFormat image format
* @param srcW width of source image
* @param srcH height of source image
* @param srcSliceY slice Y of source image
* @param srcSliceH slice H of source image
* @param dst destination image (java type)
* @param dstFormat destination format
* @param dstW width of destination image
* @param dstH height destination image
* @return 0 if success, -1 otherwise
*/
public static native int sws_scale(
long ctx,
Object src, int srcFormat, int srcW, int srcH,
int srcSliceY, int srcSliceH,
Object dst, int dstFormat, int dstW, int dstH);
} |
package org.lantern.geoip;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import org.lantern.GeoData;
import org.littleshoot.util.BitUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Singleton;
/**
*
* @author leah
*
*/
@Singleton
public class GeoIpLookupService {
private static final Logger LOG = LoggerFactory
.getLogger(GeoIpLookupService.class);
private TreeMap<Long, GeoData> table;
private volatile boolean dataLoaded = false;
public GeoIpLookupService() {
this(true);
}
public GeoIpLookupService(boolean loadImmediately) {
if (loadImmediately) {
threadLoadData();
}
}
public void threadLoadData() {
Runnable runnable = new Runnable() {
@Override
public void run() {
loadData();
}
};
Thread thread = new Thread(runnable);
thread.setDaemon(true);
thread.start();
}
private GeoData getGeoData(byte[] bytes) {
loadData();
synchronized (this) {
while (!dataLoaded) {
try {
wait();
} catch (InterruptedException e) {
//fall through
}
}
}
long address = BitUtils.byteArrayToInteger(bytes);
if (address < 0) {
address = (1L << 32) + address;
}
return table.floorEntry(address).getValue();
}
public GeoData getGeoData(InetAddress ip) {
return getGeoData(ip.getAddress());
}
public GeoData getGeoData(String ip) {
byte[] bytes = new byte[4];
String[] parts = ip.split("\\.");
for (int i = 0; i < 4; i++) {
bytes[i] = (byte) Integer.parseInt(parts[i]);
}
return getGeoData(bytes);
}
private synchronized void loadData() {
if (table != null)
return;
table = new TreeMap<Long, GeoData>();
GeoIpCompressor compressor = new GeoIpCompressor();
InputStream inStream = GeoIpLookupService.class
.getResourceAsStream("geoip.db");
if (inStream == null) {
LOG.error("Failed to load geoip.db. All geo ip lookups will fail.");
dataLoaded = true;
return;
}
try {
compressor.readCompressedData(inStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
// convert to searchable form
List<GeoData> geoDataList = new ArrayList<GeoData>();
for (int i = 0; i < compressor.pixelIdToCountry.size(); ++i) {
GeoData GeoData = new GeoData();
int countryId = compressor.pixelIdToCountry.get(i);
String countryCode = compressor.countryIdToCountry
.get(countryId);
GeoData.setCountrycode(countryCode);
int quantized = compressor.pixelIdToQuantizedLatLon
.get(i);
GeoData.setLatitude(compressor.getLatFromQuantized(quantized));
GeoData.setLongitude(compressor.getLonFromQuantized(quantized));
geoDataList.add(GeoData);
}
long startIp = 0;
for (int i = 0; i < compressor.ipRangeList.size(); ++i) {
int range = compressor.ipRangeList.get(i);
int pixelId = compressor.pixelIdList.get(i);
GeoData GeoData = geoDataList.get(pixelId);
table.put(startIp, GeoData);
startIp += range;
}
dataLoaded = true;
synchronized(this) {
this.notifyAll();
}
}
} |
package org.libgit2.jagged.core;
import java.io.File;
import org.libgit2.jagged.core.Platform.OperatingSystem;
/**
* A wrapper around the system library loader to provide improved semantics for
* installations containing libraries for multiple platforms.
*/
public class NativeLoader
{
private static String nativeLibraryPath;
public static void setNativeLibraryPath(String libraryPath)
{
NativeLoader.nativeLibraryPath = libraryPath;
}
/**
* Loads the given shared library, looking in the platform-specific library
* directory relative to the current working directory.
*
* @param libraryName
* the name of the library to load (must not be {@code null})
*/
public static void load(final String libraryName)
{
if (nativeLibraryPath == null)
{
nativeLibraryPath = System.getProperty("org.libgit2.jagged.nativeLibraryPath");
}
/* Provide a mediocre default when the system property is unset. */
if (nativeLibraryPath == null)
{
nativeLibraryPath = "native";
}
final File operatingSystemPath =
new File(nativeLibraryPath, Platform.getCurrentPlatform().getOperatingSystem().getOsgiName());
final File architecturePath =
new File(operatingSystemPath, Platform.getCurrentPlatform().getArchitecture().getName());
/*
* There's indecision as to whether the file extension of a JNI library
* on Mac OS should be ".jnilib" (Java 6 and prior) or ".dylib" (Java
* 7). So we need to hardcode this for compatibility.
*/
final String mappedLibraryName;
if (Platform.getCurrentPlatform().getOperatingSystem() == OperatingSystem.MAC_OS_X)
{
mappedLibraryName = "lib" + libraryName + ".dylib";
}
else
{
mappedLibraryName = System.mapLibraryName(libraryName);
}
/*
* Try the operating system path first - some platforms (eg, Mac OS) can
* support "fat" binaries that are archives of the libraries for the
* multiple architectures.
*/
File libraryPath = new File(operatingSystemPath, mappedLibraryName);
if (!libraryPath.exists())
{
libraryPath = new File(architecturePath, mappedLibraryName);
}
System.load(libraryPath.getAbsolutePath());
}
} |
package org.lightmare.remote.rpc;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorker;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.channel.socket.nio.WorkerPool;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
import org.lightmare.config.Config;
import org.lightmare.config.Configuration;
import org.lightmare.remote.rcp.decoders.RcpEncoder;
import org.lightmare.remote.rpc.decoders.RpcDecoder;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
/**
* Registers and starts RPC server @see <a href="netty.io"/>netty.io</a>
*
* @author levan
*
*/
public class RpcListener {
/**
* Boss pool for Netty network
*/
private static ExecutorService boss;
/**
* Worker pool for Netty server
*/
private static ExecutorService worker;
/**
* {@link NioWorkerPool} for Netty server
*/
private static WorkerPool<NioWorker> workerPool;
/**
* {@link ChannelGroup} "info-channels" for only info requests
*/
public static ChannelGroup channelGroup = new DefaultChannelGroup(
"info-channels");
private static Channel channel;
private static ServerSocketChannelFactory factory;
private static final Runtime RUNTIME = Runtime.getRuntime();
private static final Logger LOG = Logger.getLogger(RpcListener.class);
/**
* Set boss and worker thread pools size from configuration
*/
private static void setNettyPools(Configuration config) {
Integer bossCount;
Integer workerCount;
boss = new OrderedMemoryAwareThreadPoolExecutor(
(bossCount = config.getIntValue("boss_pool_size")) != null ? bossCount
: 1, 400000000, 2000000000, 60, TimeUnit.SECONDS,
new ThreadFactoryUtil("netty-boss-thread", Thread.MAX_PRIORITY));
worker = new OrderedMemoryAwareThreadPoolExecutor(
(workerCount = config.getIntValue("worker_pool_size")) != null ? workerCount
: RUNTIME.availableProcessors() * 3, 400000000,
2000000000, 60, TimeUnit.SECONDS, new ThreadFactoryUtil(
"netty-worker-thread", (Thread.MAX_PRIORITY - 1)));
workerPool = new NioWorkerPool(worker, workerCount);
}
/**
* Starts server
*
*/
public static void startServer(Configuration config) {
setNettyPools(config);
factory = new NioServerSocketChannelFactory(boss, workerPool);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new RcpEncoder(), new RpcDecoder(),
new RpcHandler());
}
});
bootstrap.setOption("tcpNoDelay", Boolean.TRUE);
bootstrap.setOption("child.keepAlive", Boolean.TRUE);
bootstrap.setOption("backlog", 500);
bootstrap.setOption("connectTimeoutMillis",
config.getIntValue(Config.CONNECTION_TIMEOUT.key));
try {
channel = bootstrap.bind(new InetSocketAddress(Inet4Address
.getByName(config.getStringValue("listening_ip")), config
.getIntValue("listening_port")));
channelGroup.add(channel);
LOG.info(channel.getLocalAddress());
} catch (UnknownHostException ex) {
LOG.error(ex.getMessage(), ex);
}
}
} |
package org.neo4j.remote;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.event.KernelEventHandler;
import org.neo4j.graphdb.event.TransactionEventHandler;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.RelationshipIndex;
/**
* A remote connection to a running {@link GraphDatabaseService Graph Database}
* instance, providing access to the Neo4j Graph Database API.
* @author Tobias Ivarsson
*/
public final class RemoteGraphDatabase implements GraphDatabaseService
{
private static final ProtocolService protocol = new ProtocolService();
private final RemoteGraphDbEngine engine;
/**
* Creates a new remote graph database connection.
* @param site
* The connection layer to be used.
*/
public RemoteGraphDatabase( ConnectionTarget site )
{
this( null, site );
}
/**
* Creates a new remote graph database connection.
* @param config
* the {@link ConfigurationModule} containing the configurations
* of the subsystems of the graph database.
* @param site
* The connection layer to be used.
*/
public RemoteGraphDatabase( ConfigurationModule config, ConnectionTarget site )
{
this( site.connect(), config );
}
/**
* Creates a new remote graph database connection.
* @param site
* The connection layer to be used.
* @param username
* the name of the user to log in as on the remote site. (
* <code>null</code> means anonymous)
* @param password
* the password for the user to log in as on the remote site.
*/
public RemoteGraphDatabase( ConnectionTarget site, String username, String password )
{
this( null, site, username, password );
}
/**
* Creates a new remote graph database connection.
* @param config
* the {@link ConfigurationModule} containing the configurations
* of the subsystems of the graph database.
* @param site
* The connection layer to be used.
* @param username
* the name of the user to log in as on the remote site. (
* <code>null</code> means anonymous)
* @param password
* the password for the user to log in as on the remote site.
*/
public RemoteGraphDatabase( ConfigurationModule config, ConnectionTarget site,
String username, String password )
{
this( site.connect( username, password ), config );
}
/**
* Create a remote graph database connection. Select implementation depending on the
* supplied URI.
* @param resourceUri
* the URI where the connection resource is located.
* @throws URISyntaxException
* if the resource URI is malformed.
*/
public RemoteGraphDatabase( String resourceUri ) throws URISyntaxException
{
this( null, resourceUri );
}
/**
* Create a remote graph database connection. Select implementation depending on the
* supplied URI.
* @param config
* the {@link ConfigurationModule} containing the configurations
* of the subsystems of the graph database.
* @param resourceUri
* the URI where the connection resource is located.
* @throws URISyntaxException
* if the resource URI is malformed.
*/
public RemoteGraphDatabase( ConfigurationModule config, String resourceUri )
throws URISyntaxException
{
this( config, protocol.get( new URI( resourceUri ) ) );
}
/**
* Create a remote graph database connection. Select implementation depending on the
* supplied URI.
* @param resourceUri
* the URI where the connection resource is located.
* @param username
* the name of the user to log in as on the remote site. (
* <code>null</code> means anonymous)
* @param password
* the password for the user to log in as on the remote site.
* @throws URISyntaxException
* if the resource URI is malformed.
*/
public RemoteGraphDatabase( String resourceUri, String username, String password )
throws URISyntaxException
{
this( null, resourceUri, username, password );
}
/**
* Create a remote graph database connection. Select implementation depending on the
* supplied URI.
* @param config
* the {@link ConfigurationModule} containing the configurations
* of the subsystems of the graph database.
* @param resourceUri
* the URI where the connection resource is located.
* @param username
* the name of the user to log in as on the remote site. (
* <code>null</code> means anonymous)
* @param password
* the password for the user to log in as on the remote site.
* @throws URISyntaxException
* if the resource URI is malformed.
*/
public RemoteGraphDatabase( ConfigurationModule config, String resourceUri,
String username, String password ) throws URISyntaxException
{
this( config, protocol.get( new URI( resourceUri ) ), username,
password );
}
private RemoteGraphDatabase( RemoteConnection connection, ConfigurationModule config )
{
this.engine = new RemoteGraphDbEngine( this, connection, config );
}
/**
* Register a {@link ConnectionTarget} implementation with a specified protocol.
* @param factory
* a factory to create the site once it's required.
*/
public static void registerProtocol( Transport factory )
{
protocol.register( factory );
}
// GraphDatabaseService implementation
public Transaction beginTx()
{
return engine.beginTx();
}
public Node createNode()
{
return engine.current().createNode();
}
public Node getNodeById( long id )
{
// TODO: implement non-transactional path
return engine.current().getNodeById( id );
}
public Relationship getRelationshipById( long id )
{
// TODO: implement non-transactional path
return engine.current().getRelationshipById( id );
}
public Node getReferenceNode()
{
return engine.current( true ).getReferenceNode();
}
public Iterable<RelationshipType> getRelationshipTypes()
{
return engine.current( true ).getRelationshipTypes();
}
public Iterable<Node> getAllNodes()
{
return engine.current( true ).getAllNodes();
}
public void shutdown()
{
engine.shutdown();
}
public KernelEventHandler registerKernelEventHandler(
KernelEventHandler handler )
{
throw new UnsupportedOperationException(
"Event handlers not suppoerted by RemoteGraphDatabase." );
}
public KernelEventHandler unregisterKernelEventHandler(
KernelEventHandler handler )
{
throw new UnsupportedOperationException(
"Event handlers not suppoerted by RemoteGraphDatabase." );
}
public <T> TransactionEventHandler<T> registerTransactionEventHandler(
TransactionEventHandler<T> handler )
{
throw new UnsupportedOperationException(
"Event handlers not suppoerted by RemoteGraphDatabase." );
}
public <T> TransactionEventHandler<T> unregisterTransactionEventHandler(
TransactionEventHandler<T> handler )
{
throw new UnsupportedOperationException(
"Event handlers not suppoerted by RemoteGraphDatabase." );
}
RemoteGraphDbEngine getEngine()
{
return engine;
}
// These are scheduled to be removed from the GraphDatabaseService interface.
public boolean enableRemoteShell()
{
// NOTE This might not be something that we wish to support in RemoteGraphDatabase
return false;
}
public boolean enableRemoteShell( Map<String, Serializable> initialProperties )
{
// NOTE This might not be something that we wish to support in RemoteGraphDatabase
return false;
}
public Index<Node> nodeIndex( String indexName, Map<String, String> configForCreation )
{
throw new UnsupportedOperationException( "Not implemented RemoteGraphDatabase.nodeIndex()" );
}
public RelationshipIndex relationshipIndex( String indexName,
Map<String, String> configForCreation )
{
throw new UnsupportedOperationException( "Not implemented RemoteGraphDatabase.relationshipIndex()" );
}
} |
package org.neo4j.server.web;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.resource.Resource;
import org.mortbay.thread.QueuedThreadPool;
import com.sun.jersey.spi.container.servlet.ServletContainer;
public class Jetty6WebServer implements WebServer {
private static final String DEFAULT_CONTENT_RESOURCE_PATH = "html";
private static final String DEFAULT_CONTENT_CONTEXT_BASE = "webadmin";
private Server jetty;
private int jettyPort = 80;
private ServletHolder jerseyServletHolder = new ServletHolder(ServletContainer.class);
private String contentResourcePath = DEFAULT_CONTENT_RESOURCE_PATH;
private String contentContextPath = DEFAULT_CONTENT_CONTEXT_BASE;
public void start() {
jetty = new Server(jettyPort);
jetty.setStopAtShutdown(true);
try {
final WebAppContext webadmin = new WebAppContext();
webadmin.setServer(jetty);
webadmin.setContextPath("/" + contentContextPath);
URL url = getClass().getClassLoader().getResource(contentResourcePath).toURI().toURL();
final Resource resource = Resource.newResource(url);
webadmin.setBaseResource(resource);
jetty.addHandler(webadmin);
} catch (Exception e) {
throw new RuntimeException(e);
}
Context jerseyContext = new Context(jetty, "/"); |
package org.opentripplanner.analyst;
import com.bedatadriven.geojson.GeometryDeserializer;
import com.bedatadriven.geojson.GeometrySerializer;
import com.csvreader.CsvReader;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MappingJsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.PrecisionModel;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Query;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.referencing.CRS;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.PropertyType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opentripplanner.analyst.batch.Individual;
import org.opentripplanner.analyst.pointset.PropertyMetadata;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.services.GraphService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
/**
* PointSets serve as destinations in web analyst one-to-many indicators. They
* can also serve as origins in many-to-many indicators.
*
* PointSets are one of the three main web analyst resources: Pointsets
* Indicators TimeSurfaces
*/
public class PointSet implements Serializable{
private static final long serialVersionUID = -8962916330731463238L;
private static final Logger LOG = LoggerFactory.getLogger(PointSet.class);
public String id;
public String label;
public String description;
public Map<String, PropertyMetadata> propMetadata = new HashMap<String, PropertyMetadata>();
public Map<String, int[]> properties = new ConcurrentHashMap<String, int[]>();
public int capacity = 0; // The total number of features this PointSet can
// hold.
/*
* Connects this population to vertices in a given Graph (map of graph ids
* to sample sets). Keeping as a graphId->sampleSet map to prevent
* duplication of pointset when used across multiple graphs
*/
private Map<String, SampleSet> samples = new ConcurrentHashMap<String, SampleSet>();
/*
* Used to generate SampleSets on an as needed basis.
*/
protected GraphService graphService;
/*
* In a detailed Indicator, the time to reach each target, for each origin.
* Null in non-indicator pointsets.
*/
public int[][] times;
/**
* The geometries of the features. Each Attribute must contain an array of
* magnitudes with the same length as this list.
*/
protected String[] ids;
protected double[] lats;
protected double[] lons;
protected Polygon[] polygons;
/**
* Rather than trying to load anything any everything, we stick to a strict
* format and rely on other tools to get the data into the correct format.
* This includes column headers in the category:subcategory:attribute format
* and coordinates in WGS84. Comments begin with a #.
*/
public static PointSet fromCsv(File filename) throws IOException {
/* First, scan through the file to count lines and check for errors. */
CsvReader reader = new CsvReader(filename.getAbsolutePath(), ',', Charset.forName("UTF8"));
reader.readHeaders();
int nCols = reader.getHeaderCount();
while (reader.readRecord()) {
if (reader.getColumnCount() != nCols) {
LOG.error("CSV record {} has the wrong number of fields.", reader.getCurrentRecord());
return null;
}
}
// getCurrentRecord is zero-based and does not include headers or blank
// lines.
int nRecs = (int) reader.getCurrentRecord() + 1;
reader.close();
/* If we reached here, the file is entirely readable. Start over. */
reader = new CsvReader(filename.getAbsolutePath(), ',', Charset.forName("UTF8"));
PointSet ret = new PointSet(nRecs);
reader.readHeaders();
if (reader.getHeaderCount() != nCols) {
LOG.error("Number of headers changed.");
return null;
}
int latCol = -1;
int lonCol = -1;
int[][] properties = new int[nCols][ret.capacity];
for (int c = 0; c < nCols; c++) {
String header = reader.getHeader(c);
if (header.equalsIgnoreCase("lat") || header.equalsIgnoreCase("latitude")) {
latCol = c;
} else if (header.equalsIgnoreCase("lon") || header.equalsIgnoreCase("longitude")) {
lonCol = c;
} else {
ret.getOrCreatePropertyForId(header);
properties[c] = ret.properties.get(header);
}
}
if (latCol < 0 || lonCol < 0) {
LOG.error("CSV file did not contain a latitude or longitude column.");
throw new IOException();
}
ret.lats = new double[nRecs];
ret.lons = new double[nRecs];
while (reader.readRecord()) {
int rec = (int) reader.getCurrentRecord();
for (int c = 0; c < nCols; c++) {
if(c==latCol || c==lonCol){
continue;
}
int[] prop = properties[c];
int mag = Integer.parseInt(reader.get(c));
prop[rec] = mag;
}
ret.lats[rec] = Double.parseDouble(reader.get(latCol));
ret.lons[rec] = Double.parseDouble(reader.get(lonCol));
}
ret.capacity = nRecs;
return ret;
}
public static PointSet fromShapefile( File file ) throws IOException, NoSuchAuthorityCodeException, FactoryException, EmptyPolygonException, UnsupportedGeometryException {
if ( ! file.exists())
throw new RuntimeException("Shapefile does not exist.");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(WGS84);
SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
SimpleFeatureIterator it = featureCollection.features();
PointSet ret = new PointSet(featureCollection.size());
int i=0;
while (it.hasNext()) {
SimpleFeature feature = it.next();
Geometry geom = (Geometry) feature.getDefaultGeometry();
PointFeature ft = new PointFeature();
ft.setGeom(geom);
for(Property prop : feature.getProperties() ){
Object binding = prop.getType().getBinding();
//attempt to coerce the prop's value into an integer
int val;
if(binding.equals(Integer.class)){
val = (Integer)prop.getValue();
} else if(binding.equals(Long.class)){
val = ((Long)prop.getValue()).intValue();
} else if(binding.equals(String.class)){
try{
val = Integer.parseInt((String)prop.getValue());
} catch (NumberFormatException ex ){
continue;
}
} else {
continue;
}
ft.addAttribute(prop.getName().toString(), val);
}
ret.addFeature(ft, i);
i++;
}
return ret;
}
public static PointSet fromGeoJson(File filename) {
try {
FileInputStream fis = new FileInputStream(filename);
int n = validateGeoJson(fis);
if (n < 0)
return null;
fis.getChannel().position(0); // rewind file
return fromValidatedGeoJson(fis, n);
} catch (FileNotFoundException ex) {
LOG.error("GeoJSON file not found: {}", filename);
return null;
} catch (IOException ex) {
LOG.error("I/O exception while reading GeoJSON file: {}", filename);
return null;
}
}
/**
* Examines a JSON stream to see if it matches the expected OTPA format.
*
* @return the number of features in the collection if it's valid, or -1 if
* it doesn't fit the OTPA format.
*/
public static int validateGeoJson(InputStream is) {
int n = 0;
JsonFactory f = new JsonFactory();
try {
JsonParser jp = f.createParser(is);
JsonToken current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
LOG.error("Root of OTPA GeoJSON should be a JSON object.");
return -1;
}
// Iterate over the key:value pairs in the top-level JSON object
while (jp.nextToken() != JsonToken.END_OBJECT) {
String key = jp.getCurrentName();
current = jp.nextToken();
if (key.equals("features")) {
if (current != JsonToken.START_ARRAY) {
LOG.error("Error: GeoJSON features are not in an array.");
return -1;
}
// Iterate over the features in the array
while (jp.nextToken() != JsonToken.END_ARRAY) {
n += 1;
jp.skipChildren();
}
} else {
jp.skipChildren(); // ignore all other keys except features
}
}
if (n == 0)
return -1; // JSON has no features
return n;
} catch (Exception ex) {
LOG.error("Exception while validating GeoJSON: {}", ex);
return -1;
}
}
/**
* Reads with a combination of streaming and tree-model to allow very large
* GeoJSON files. The JSON should be already validated, and you must pass in
* the maximum number of features from that validation step.
*/
private static PointSet fromValidatedGeoJson(InputStream is, int n) {
JsonFactory f = new MappingJsonFactory();
PointSet ret = new PointSet(n);
int index = 0;
try {
JsonParser jp = f.createParser(is);
JsonToken current = jp.nextToken();
// Iterate over the key:value pairs in the top-level JSON object
while (jp.nextToken() != JsonToken.END_OBJECT) {
String key = jp.getCurrentName();
current = jp.nextToken();
if (key.equals("properties")) {
JsonNode properties = jp.readValueAsTree();
if(properties.get("id") != null)
ret.id = properties.get("id").asText();
if(properties.get("label") != null)
ret.label = properties.get("label").asText();
if(properties.get("description") != null)
ret.label = properties.get("description").asText();
if(properties.get("schema") != null) {
Iterator<Entry<String, JsonNode>> catIter = properties.get("schema").fields();
while (catIter.hasNext()) {
Entry<String, JsonNode> catEntry = catIter.next();
String catName = catEntry.getKey();
JsonNode catNode = catEntry.getValue();
PropertyMetadata cat = new PropertyMetadata(catName);
if(catNode.get("label") != null)
cat.label = catNode.get("label").asText();
if(catNode.get("style") != null) {
Iterator<Entry<String, JsonNode>> styleIter = catNode.get("style").fields();
while (styleIter.hasNext()) {
Entry<String, JsonNode> styleEntry = styleIter.next();
String styleName = styleEntry.getKey();
JsonNode styleValue = styleEntry.getValue();
cat.addStyle(styleName, styleValue.asText());
}
}
ret.propMetadata.put(catName, cat);
}
}
}
if (key.equals("features")) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
// Read the feature into a tree model, which moves
// parser to its end.
JsonNode feature = jp.readValueAsTree();
ret.addFeature(feature, index++);
}
} else {
jp.skipChildren(); // ignore all other keys except features
}
}
} catch (Exception ex) {
LOG.error("GeoJSON parsing failure: {}", ex.toString());
return null;
}
return ret;
}
/**
* Add one GeoJSON feature to this PointSet from a Jackson node tree.
* com.bedatadriven.geojson only exposed its streaming Geometry parser as a
* public method. I made its tree parser public as well. Geotools also has a
* GeoJSON parser called GeometryJson (which OTP wraps in
* GeoJsonDeserializer) but it consumes straight text, not a Jackson model
* or streaming parser.
*/
private void addFeature(JsonNode feature, int index) {
PointFeature feat = null;
try {
feat = PointFeature.fromJsonNode(feature);
} catch (EmptyPolygonException e) {
LOG.warn("Empty MultiPolygon, skipping.");
return;
} catch (UnsupportedGeometryException e) {
LOG.warn(e.message);
return;
}
if (feat == null) {
return;
}
addFeature(feat, index);
}
/**
* Create a PointSet manually by defining capacity and calling
* addFeature(geom, data) repeatedly.
*
* @param capacity
* expected number of features to be added to this PointSet.
*/
public PointSet(int capacity) {
this.capacity = capacity;
ids = new String[capacity];
lats = new double[capacity];
lons = new double[capacity];
polygons = new Polygon[capacity];
}
/**
* Adds a graph service to allow for auto creation of SampleSets for a given
* graph
*
* @param reference
* to the application graph service
*/
public void setGraphService(GraphService graphService) {
this.graphService = graphService;
}
/**
* gets a sample set for a given graph id -- requires graphservice to be set
*
* @param a valid graph id
* @return sampleset for graph
*/
public SampleSet getSampleSet(String routerId) {
if(this.graphService == null)
return null;
if (this.samples.containsKey(routerId))
return this.samples.get(routerId);
Graph g = this.graphService.getGraph(routerId);
return getSampleSet(g);
}
/**
* gets a sample set for a graph object -- does not require graph service to be set
* @param g a graph objects
* @return sampleset for graph
*/
public SampleSet getSampleSet(Graph g) {
if (g == null)
return null;
SampleSet sampleSet = new SampleSet(this, g.getSampleFactory());
this.samples.put(g.routerId, sampleSet);
return sampleSet;
}
/**
* Add a single feature with a variable number of free-form properties.
* Attribute data contains id value pairs, ids are in form "cat_id:prop_id".
* If the properties and categories do not exist, they will be created.
* TODO: read explicit schema or infer it and validate property presence as
* they're read
*
* @param geom
* must be a Point, a Polygon, or a single-element MultiPolygon
*/
public int featureCount() {
return ids.length;
}
public void addFeature(PointFeature feat, int index) {
if (index >= capacity) {
throw new AssertionError("Number of features seems to have grown since validation.");
}
polygons[index] = feat.getPolygon();
lats[index] = feat.getLat();
lons[index] = feat.getLon();
ids[index] = feat.getId();
for (Entry<String,Integer> ad : feat.getProperties().entrySet()) {
String propId = ad.getKey();
Integer propVal = ad.getValue();
this.getOrCreatePropertyForId(propId);
this.properties.get(propId)[index] = propVal;
}
}
public PointFeature getFeature(int index) {
PointFeature ret = new PointFeature(ids[index]);
if (polygons[index] != null) {
try {
ret.setGeom(polygons[index]);
} catch (Exception e) {
// The polygon is clean; this should never happen. We
// could pass the exception up but that'd just make the calling
// function deal with an exception that will never pop. So
// we'll make the compiler happy by catching it here silently.
}
}
// ret.setGeom, if it was called, will already set the lat and lon
// properties. But since every item in this pointset is guaranteed
// to have a lat/lon coordinate, we defer to it as more authoritative.
ret.setLat(lats[index]);
ret.setLon(lons[index]);
for (Entry<String, int[]> property : this.properties.entrySet()) {
ret.addAttribute( property.getKey(), property.getValue()[index]);
}
return ret;
}
public void setLabel(String catId, String label) {
PropertyMetadata meta = this.propMetadata.get(catId);
if(meta!=null){
meta.setLabel( label );
}
}
public void setStyle(String catId, String styleAttribute, String styleValue) {
PropertyMetadata meta = propMetadata.get(catId);
if(meta!=null){
meta.addStyle( styleAttribute, styleValue );
}
}
/**
* Gets the Category object for the given ID, creating it if it doesn't
* exist.
*
* @param id
* the id for the category alone, not the fully-specified
* category:property.
* @return a Category with the given ID.
*/
public PropertyMetadata getOrCreatePropertyForId(String id) {
PropertyMetadata property = propMetadata.get(id);
if (property == null) {
property = new PropertyMetadata(id);
propMetadata.put(id, property);
}
if(!properties.containsKey(id))
properties.put(id, new int[capacity]);
return property;
}
public void writeJson(OutputStream out) {
writeJson(out, false);
}
/**
* Use the Jackson streaming API to output this as GeoJSON without creating
* another object. The Indicator is a column store, and is transposed WRT
* the JSON representation.
*/
public void writeJson(OutputStream out, Boolean forcePoints) {
try {
JsonFactory jsonFactory = new JsonFactory(); // ObjectMapper.getJsonFactory()
// is better
JsonGenerator jgen = jsonFactory.createGenerator(out);
jgen.setCodec(new ObjectMapper());
jgen.writeStartObject();
{
jgen.writeStringField("type", "FeatureCollection");
writeJsonProperties(jgen);
jgen.writeArrayFieldStart("features");
{
for (int f = 0; f < capacity; f++) {
writeFeature(f, jgen, forcePoints);
}
}
jgen.writeEndArray();
}
jgen.writeEndObject();
jgen.close();
} catch (IOException ioex) {
LOG.info("IOException, connection may have been closed while streaming JSON.");
}
}
public void writeJsonProperties(JsonGenerator jgen) throws JsonGenerationException, IOException {
jgen.writeObjectFieldStart("properties");
{
if (id != null)
jgen.writeStringField("id", id);
if (label != null)
jgen.writeStringField("label", label);
if (description != null)
jgen.writeStringField("description", description);
// writes schema as a flat namespace with cat_id and
// cat_id:prop_id interleaved
jgen.writeObjectFieldStart("schema");
{
for (PropertyMetadata cat : this.propMetadata.values()) {
jgen.writeObjectFieldStart(cat.id);
{
if (cat.label != null)
jgen.writeStringField("label", cat.label);
jgen.writeStringField("type", "Category");
if (cat.style != null && cat.style.attributes != null) {
jgen.writeObjectFieldStart("style");
{
for (String styleKey : cat.style.attributes.keySet()) {
jgen.writeStringField(styleKey, cat.style.attributes.get(styleKey));
}
}
jgen.writeEndObject();
}
}
jgen.writeEndObject();
// two-level hierarchy for now... could be extended
// to recursively map
// categories,sub-categories,attributes
}
}
jgen.writeEndObject();
}
jgen.writeEndObject();
}
/**
* Pairs an array of times with the array of features in this pointset,
* writing out the resulting (ID,time) pairs to a JSON object.
*/
protected void writeTimes(JsonGenerator jgen, int[] times) throws IOException {
jgen.writeObjectFieldStart("times");
for (int i = 0; i < times.length; i++) { // capacity is now 1 if this is
// a one-to-many indicator
int t = times[i];
if (t != Integer.MAX_VALUE)
jgen.writeNumberField(ids[i], t);
}
jgen.writeEndObject();
}
/**
* This writes either a polygon or lat/lon point defining the feature. In
* the case of polygons, we convert these back to centroids on import, as
* OTPA depends on the actual point. The polygons are kept for derivative
* uses (e.g. visualization)
*
* @param i
* the feature index
* @param jgen
* the Jackson streaming JSON generator to which the geometry
* will be written
* @throws IOException
*/
private void writeFeature(int i, JsonGenerator jgen, Boolean forcePoints) throws IOException {
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel());
GeometrySerializer geomSerializer = new GeometrySerializer();
jgen.writeStartObject();
{
jgen.writeStringField("id", ids[i]);
jgen.writeStringField("type", "Feature");
jgen.writeFieldName("geometry");
{
if (!forcePoints && polygons != null && polygons.length >= i && polygons[i] != null) {
geomSerializer.writeGeometry(jgen, polygons[i]);
} else {
Point p = geometryFactory.createPoint(new Coordinate(lons[i], lats[i]));
geomSerializer.writeGeometry(jgen, p);
}
}
jgen.writeObjectFieldStart("properties");
{
writeStructured(i, jgen);
}
jgen.writeEndObject();
}
jgen.writeEndObject();
}
/**
* This will be called once per point in an origin/destination pointset, and
* once per origin in a one- or many-to-many indicator.
*/
protected void writeStructured(int i, JsonGenerator jgen) throws IOException {
jgen.writeObjectFieldStart("structured");
for (Entry<String,int[]> entry : properties.entrySet()) {
jgen.writeNumberField( entry.getKey(), entry.getValue()[i] );
}
jgen.writeEndObject();
}
/**
* Get a subset of this point set containing only the specified point IDs.
*/
public PointSet slice(List<String> ids) {
PointSet ret = new PointSet(ids.size());
HashSet<String> idsHashSet = new HashSet<String>(ids);
ret.id = id;
ret.label = label;
ret.description = description;
int n = 0;
for (int i = 0; i < this.ids.length; i++) {
if(idsHashSet.contains(this.ids[i])) {
ret.lats[n] = this.lats[i];
ret.lons[n] = this.lons[i];
ret.ids[n] = this.ids[i];
ret.polygons[n] = this.polygons[i];
n++;
}
}
return ret;
}
public PointSet slice(int start, int end) {
PointSet ret = new PointSet(end - start);
ret.id = id;
ret.label = label;
ret.description = description;
int n = 0;
for (int i = start; i < end; i++) {
ret.lats[n] = this.lats[i];
ret.lons[n] = this.lons[i];
ret.ids[n] = this.ids[i];
ret.polygons[n] = this.polygons[i];
n++;
}
for(Entry<String, int[]> property : this.properties.entrySet()) {
int[] data = property.getValue();
int[] magSlice = new int[end-start];
n=0;
for(int i=start; i<end; i++){
magSlice[n] = data[i];
n++;
}
ret.properties.put( property.getKey(), magSlice );
}
return ret;
}
} |
package org.purl.linkedepcis.eem;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.log4j.Logger;
import org.openrdf.model.BNode;
import org.openrdf.model.Graph;
import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.Rio;
import org.openrdf.rio.UnsupportedRDFormatException;
import org.openrdf.rio.WriterConfig;
import org.openrdf.rio.helpers.BasicWriterSettings;
import org.openrdf.rio.helpers.ContextStatementCollector;
import org.openrdf.rio.turtle.TurtleWriter;
import org.purl.linkedepcis.cbv.Address;
import org.purl.linkedepcis.cbv.Site;
import org.purl.linkedepcis.cbv.SubSite;
import org.purl.linkedepcis.cbv.SubSiteAttribute;
public class EPCISCommon {
// counter for the event. This increments with every call to getEventIRI();
private int eventCounter = 0;
Logger logger = Logger.getLogger(EPCISCommon.class);
public void addEPCTOEvent() {
}
/**
* @param ns
* @param mySubject
* @param myGraph
* @param epcArray
*/
public Graph addEPCsToGraph(Namespaces ns, Graph myGraph, URI mySubject,
ArrayList<String> epcArray) {
if (epcArray.size() > 0) {
ValueFactory myFactory = ValueFactoryImpl.getInstance();
BNode bnodeEPC = myFactory.createBNode();
// link the EPCS to the event
myGraph.add(mySubject, myFactory.createURI(
ns.getIRIForPrefix("eem"), "associatedWithEPCList"),
bnodeEPC);
myGraph.add(bnodeEPC, RDF.TYPE,
myFactory.createURI(ns.getIRIForPrefix("eem"), "SetOfEPCs"));
for (String e : epcArray) {
myGraph.add(bnodeEPC,
myFactory.createURI("http://purl.org/co#element"),
myFactory.createURI(e.trim()));
// System.out.println(e);
}
}
return myGraph;
}
// write the graph to a file with namespace mappings
public void persistGraphToFile(Graph myGraph, String f, Namespaces namespaces) {
// printGraph(myGraph);
try {
FileOutputStream fout = new FileOutputStream(f, true);
// logger.info("file to be written ..." + f);
// TurtleWriter turtleWriter = new TurtleWriter(fout);
// addToStream(namespaces);
ValueFactory myFactory = ValueFactoryImpl.getInstance();
Model result = new LinkedHashModel();
ContextStatementCollector csc = new ContextStatementCollector(result, myFactory, myFactory.createURI(namespaces.getContextURI()));
WriterConfig config = new WriterConfig();
config.set(BasicWriterSettings.PRETTY_PRINT, true);
// // turtleWriter.setWriterConfig(config);
// // turtleWriter.startRDF();
// csc.startRDF();
// for (Statement statement : myGraph) {
// // System.out.println(statement);
// csc.handleStatement(statement);
// // turtleWriter.handleStatement(statement);
Map<String, String> ns = namespaces.getNameSpacesPrefixes();
for (Map.Entry<String, String> entry : ns.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
//use key and value
// logger.info(key + " " + value);
// turtleWriter.handleNamespace(key, value);
csc.handleNamespace(key, value);
}
Rio.write(myGraph, csc);
//handle namespaces
if(f.contains("trig"))
Rio.write(result, fout, RDFFormat.TRIG);
else
persistGraphToFile(myGraph, f);
// csc.endRDF();
// turtleWriter.endRDF();
fout.close();
addToStream(namespaces);
// System.out.println(f.getAbsolutePath() + " "+f.exists());
} catch (UnsupportedRDFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RDFHandlerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// prettyPrintTurtleFormat(f);
}
// write the graph to a file
public void persistGraphToFile(Graph myGraph, String f) {
// printGraph(myGraph);
try {
FileOutputStream fout = new FileOutputStream(f, true);
TurtleWriter turtleWriter = new TurtleWriter(fout);
WriterConfig config = new WriterConfig();
config.set(BasicWriterSettings.PRETTY_PRINT, true);
turtleWriter.setWriterConfig(config);
turtleWriter.startRDF();
for (Statement statement : myGraph) {
// System.out.println(statement);
turtleWriter.handleStatement(statement);
}
turtleWriter.endRDF();
fout.close();
// System.out.println(f.getAbsolutePath() + " "+f.exists());
} catch (UnsupportedRDFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RDFHandlerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// prettyPrintTurtleFormat(f);
}
// print graph
public void printGraph(Graph myGraph) {
try {
RDFWriter turtleWriter = Rio.createWriter(RDFFormat.TURTLE,
System.out);
WriterConfig config = new WriterConfig();
config.set(BasicWriterSettings.PRETTY_PRINT, true);
turtleWriter.setWriterConfig(config);
turtleWriter.startRDF();
for (Statement statement : myGraph) {
turtleWriter.handleStatement(statement);
}
turtleWriter.endRDF();
} catch (UnsupportedRDFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RDFHandlerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// add action to the graph
public Graph setAction(Namespaces ns, Graph myGraph, URI subject,
String action) {
myGraph.add(
subject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "action"),
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), action.toUpperCase()));
return myGraph;
}
// add action to the graph
public Graph setAction(Namespaces ns, Graph myGraph, URI subject,
URI actionURI) {
myGraph.add(
subject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "action"), actionURI);
return myGraph;
}
// add business step type to the graph
public Graph setBusinessStepType(Namespaces ns, Graph myGraph, URI subject,
String businessStep) {
myGraph.add(
subject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "hasBusinessStepType"),
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("cbv"),
businessStep.toLowerCase()));
return myGraph;
}
// add business step type to the graph
public Graph setBusinessStepType(Namespaces ns, Graph myGraph, URI subject,
URI businessStepURI) {
myGraph.add(
subject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "hasBusinessStepType"),
businessStepURI);
return myGraph;
}
// add temporal properties to the graph
public Graph setTemporalProperties(Namespaces ns, Graph myGraph,
URI mySubject) {
// set up the temporal properties
URI myPredicate;
Literal myLiteral;
GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.setTimeInMillis(System.currentTimeMillis());
DatatypeFactory df;
try {
df = DatatypeFactory.newInstance();
XMLGregorianCalendar xc = df.newXMLGregorianCalendar(gc);
String ts = xc.toXMLFormat();
myLiteral = ValueFactoryImpl.getInstance().createLiteral(
xc);
myPredicate = ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "eventOccurredAt");
myGraph.add(mySubject, myPredicate, myLiteral);
myLiteral = ValueFactoryImpl.getInstance().createLiteral(
TimeUnit.MILLISECONDS.toDays(gc.getTimeZone().getOffset(
gc.getTimeInMillis())));
// set up the offset
myPredicate = ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "eventTimeZoneOffset");
myGraph.add(mySubject, myPredicate, myLiteral);
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return myGraph;
}
/**
* @param ns
* @param myGraph
* @param mySubject
* @param transactions
*/
public Graph setBusinessTransaction(Namespaces ns, Graph myGraph,
URI mySubject, ArrayList<Transaction> transactions) {
if (transactions.size() > 0) {
ValueFactory myFactory = ValueFactoryImpl.getInstance();
BNode bnode = myFactory.createBNode();
// link the EPCS to the event
myGraph.add(mySubject,
myFactory.createURI(ns.getIRIForPrefix("eem"),
"associatedWithTransactionList"), bnode);
myGraph.add(bnode, RDF.TYPE, myFactory.createURI(
ns.getIRIForPrefix("eem"), "SetOfTransactions"));
for (Transaction e : transactions) {
URI transactionID = myFactory.createURI(e.getTransactionID());
myGraph.add(transactionID, RDF.TYPE, myFactory.createURI(
ns.getIRIForPrefix("eem"), "Transaction"));
myGraph.add(transactionID, myFactory.createURI(
ns.getIRIForPrefix("eem"), "hasTransactionType"),
myFactory.createURI(ns.getIRIForPrefix("cbv"), "btt/"
+ e.getTransactionType()));
myGraph.add(bnode,
myFactory.createURI("http://purl.org/co#element"),
transactionID);
// System.out.println(e);
}
}
return myGraph;
}
/**
* @param ns
* @param myGraph
* @param mySubject
* @param disposition
* @return
*/
// set disposition with default URI
public Graph setDisposition(Namespaces ns, Graph myGraph, URI mySubject,
String disposition) {
myGraph.add(
mySubject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "hasDisposition"),
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("cbv"),
disposition.toLowerCase()));
return myGraph;
}
// set disposition with custom URI
public Graph setDisposition(Namespaces ns, Graph myGraph, URI mySubject,
URI disposition) {
myGraph.add(
mySubject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "hasDisposition"),
disposition);
return myGraph;
}
public Graph setLocation(Namespaces ns, URI mySubject, Graph myGraph,
Site location, String identifier) {
URI myPredicate = null;
ValueFactory myFactory = ValueFactoryImpl.getInstance();
BNode bnode = myFactory.createBNode();
URI locationIDURI = location.getLocationIDURI();
Address address = location.getAddress();
SubSite subsite = location.getSubSite();
if (identifier.equals("readPoint")) {
myPredicate = myFactory.createURI(ns.getIRIForPrefix("eem"),
"hasReadPointLocation");
myGraph.add(locationIDURI, RDF.TYPE, myFactory.createURI(
ns.getIRIForPrefix("eem"), "ReadPointLocation"));
} else {
myPredicate = myFactory.createURI(ns.getIRIForPrefix("eem"),
"hasBusinessLocation");
myGraph.add(locationIDURI, RDF.TYPE, myFactory.createURI(
ns.getIRIForPrefix("eem"), "BusinessLocation"));
}
myGraph.add(mySubject, myPredicate, locationIDURI);
if (address != null) {
// add address properties
if (address.getStreetName() != null) {
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("vcard"),
"street-address"), myFactory.createLiteral(address
.getStreetName()));
}
if (address.getPostCode() != null) {
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("vcard"),
"postal-code"), myFactory.createLiteral(address
.getPostCode()));
}
if (address.getCountry() != null) {
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("vcard"),
"country-name"), myFactory.createLiteral(address
.getCountry()));
}
if (address.getLocality() != null) {
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("vcard"),
"locality"), myFactory.createLiteral(address.getLocality()));
}
if (address.getPost_office_box() != null) {
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("vcard"),
"post-ffice-box"), myFactory.createLiteral(address
.getPost_office_box()));
}
if (address.getRegion() != null) {
myGraph.add(bnode,
myFactory.createURI(ns.getIRIForPrefix("vcard"), "region"),
myFactory.createLiteral(address.getRegion()));
}
myGraph.add(location.getLocationIDURI(),
myFactory.createURI(ns.getIRIForPrefix("vcard"), "adr"), bnode);
myGraph.add(
location.getLocationIDURI(),
myFactory.createURI(ns.getIRIForPrefix("eem"), "hasLocationID"),
location.getLocationIDURI());
myGraph.add(location.getLocationIDURI(),
myFactory.createURI(ns.getIRIForPrefix("wgs84"), "latitude"),
myFactory.createLiteral(address.getLatitude()));
myGraph.add(location.getLocationIDURI(),
myFactory.createURI(ns.getIRIForPrefix("wgs84"), "longitude"),
myFactory.createLiteral(address.getLongitude()));
}
if (subsite != null) {
bnode = myFactory.createBNode();
//add the subSiteType statements
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("cbv"), "hasSubSiteType"),
myFactory.createLiteral(subsite.getSubSiteType().toString()));
if (subsite.getSubsSiteAttribute() != null) {
ArrayList<SubSiteAttribute> ssAttributes = subsite.getSubsSiteAttribute();
for (SubSiteAttribute ssat : ssAttributes) {
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("cbv"), "hasSubSiteAttribute"),
myFactory.createLiteral(ssat.toString()));
}
}
if (subsite.getSubSiteDetail() != null) {
myGraph.add(bnode, myFactory.createURI(ns.getIRIForPrefix("cbv"), "hasSubSiteDetail"),
myFactory.createLiteral(subsite.getSubSiteDetail()));
}
myGraph.add(location.getLocationIDURI(),
myFactory.createURI(ns.getIRIForPrefix("cbv"), "hasSubSite"),
bnode);
}
return myGraph;
}
public Graph setLocation(Namespaces ns, String prefix, Graph myGraph,
URI mySubject, Site location, String identifier) {
URI myPredicate = null;
ValueFactory myFactory = ValueFactoryImpl.getInstance();
;
// check the strings
String locationID = location.getLocationID();
URI locationIDURI = location.getLocationIDURI();
if (locationIDURI == null) {
locationIDURI = myFactory.createURI(ns.getIRIForPrefix(prefix),
locationID);
location.setLocationIDURI(locationIDURI);
}
myGraph = setLocation(ns, mySubject, myGraph, location, identifier);
return myGraph;
}
private void prettyPrintTurtleFormat(String fileName) {
//Model model = Rio.parse(new FileInputStream(fileName), RDFFormat.TURTLE);
//Rio.p
// System.out.println("
// System.out.println() ;
// RDFDataMgr.write(System.out, model, Lang.TURTLE) ;
// System.out.println() ;
// System.out.println("
// System.out.println() ;
// model.write(System.out, "TTL") ;
}
/**
* @param myGraph
* @param mySubject2
* @param reader
* @return
*/
public Graph setReaderForEvent(Namespaces ns, String prefix, Graph myGraph,
URI mySubject, Reader reader) {
URI readerURI = ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix(prefix), reader.getPhysicalReaderID());
myGraph.add(readerURI, RDF.TYPE, ValueFactoryImpl.getInstance()
.createURI(ns.getIRIForPrefix("eem"), "Reader"));
myGraph.add(
readerURI,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "logicalID"),
ValueFactoryImpl.getInstance().createLiteral(
reader.getPhysicalReaderID()));
myGraph.add(
mySubject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "recordedByReader"),
readerURI);
return myGraph;
}
/**
* @param recordTime
* @return
*/
public Graph setEventRecordedTime(Namespaces ns, Graph myGraph,
URI subject, Literal recordTime) {
// System.out.println(subject);
myGraph.add(
subject,
ValueFactoryImpl.getInstance().createURI(
ns.getIRIForPrefix("eem"), "eventRecordedAt"),
recordTime);
return myGraph;
}
public Literal getCurrentTimeAndDateInXMLGregorianCalendar() {
GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.setTimeInMillis(System.currentTimeMillis());
DatatypeFactory df = null;
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException ex) {
java.util.logging.Logger.getLogger(EPCISCommon.class.getName()).log(Level.SEVERE, null, ex);
}
XMLGregorianCalendar xc = df.newXMLGregorianCalendar(gc);
Literal myLiteral = ValueFactoryImpl.getInstance().createLiteral(
xc);
return myLiteral;
}
Graph streamGraph = new LinkedHashModel();
private void addToStream(Namespaces ns) {
setEventRecordedTime(ns, streamGraph, ValueFactoryImpl.getInstance().createURI(ns.getContextURI()), getCurrentTimeAndDateInXMLGregorianCalendar());
persistStreamGraph(streamGraph, ns);
}
void persistStreamGraph(Graph streamGraph, Namespaces ns) {
File fstream = new File("streams");
try {
if (!fstream.exists()) {
fstream.mkdir();
fstream.createNewFile();
} else {
logger.info("file exists");
}
FileOutputStream fout = new FileOutputStream("streams//streamGraph.trig", true);
// TurtleWriter turtleWriter = new TurtleWriter(fout);
// WriterConfig config = new WriterConfig();
// config.set(BasicWriterSettings.PRETTY_PRINT, true);
// turtleWriter.setWriterConfig(config);
// turtleWriter.startRDF();
// for (Statement statement : streamGraph) {
// // System.out.println(statement);
// turtleWriter.handleStatement(statement);
// turtleWriter.endRDF();
// fout.close();
ValueFactory myFactory = ValueFactoryImpl.getInstance();
Model result = new LinkedHashModel();
ContextStatementCollector csc = new ContextStatementCollector(result, myFactory, myFactory.createURI(ns.getBaseIRI().concat("eventStream")));
// Map<String, String> namespaces = ns.getNameSpacesPrefixes();
// for (Map.Entry<String, String> entry : namespaces.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// //use key and value
// logger.info(key + " " + value);
// // turtleWriter.handleNamespace(key, value);
// csc.handleNamespace(key, value);
Rio.write(streamGraph, csc);
//handle namespaces
Rio.write(result, fout, RDFFormat.TURTLE);
fout.close();
} catch (IOException ex) {
java.util.logging.Logger.getLogger(EPCISCommon.class.getName()).log(Level.SEVERE, null, ex);
} catch (RDFHandlerException ex) {
java.util.logging.Logger.getLogger(EPCISCommon.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
package org.simpleframework.xml.load;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.beans.Introspector;
/**
* The <code>Scanner</code> object performs the reflective inspection
* of a class and builds a map of attributes and elements for each
* annotated field. This acts as a cachable container for reflection
* actions performed on a specific type. When scanning the provided
* class this inserts the scanned field as a <code>Label</code> in to
* a map so that it can be retrieved by name. Annotations classified
* as attributes have the <code>Attribute</code> annotation, all other
* annotated fields are stored as elements.
*
* @author Niall Gallagher
*
* @see org.simpleframework.xml.load.Schema
*/
class Scanner {
/**
* This is used to store all labels that are XML attributes.
*/
private LabelMap attributes;
/**
* This is used to store all labels that are XML elements.
*/
private LabelMap elements;
/**
* This method acts as a pointer to the types commit process.
*/
private Method commit;
/**
* This method acts as a pointer to the types validate process.
*/
private Method validate;
/**
* This method acts as a pointer to the types persist process.
*/
private Method persist;
/**
* This method acts as a pointer to the types complete process.
*/
private Method complete;
/**
* This method is used as a pointer to the replacement method.
*/
private Method replace;
/**
* This method is used as a pointer to the resolution method.
*/
private Method resolve;
/**
* This is used to store all labels that are XML text values.
*/
private Label text;
/**
* This is the optional order annotation for the scanned class.
*/
private Order order;
/**
* This is the optional root annotation for the scanned class.
*/
private Root root;
/**
* This is the name of the class as taken from the root class.
*/
private String name;
/**
* This is used to specify whether the type is a primitive class.
*/
private boolean primitive;
/**
* Constructor for the <code>Schema</code> object. This is used
* to scan the provided class for annotations that are used to
* build a schema for an XML file to follow.
*
* @param type this is the type that is scanned for a schema
*/
public Scanner(Class type) throws Exception {
this.attributes = new LabelMap(this);
this.elements = new LabelMap(this);
this.scan(type);
}
/**
* Returns a <code>LabelMap</code> that contains the details for
* all fields marked as XML attributes. This returns a new map
* each time the method is called, the goal is to ensure that any
* object using the label map can manipulate it without changing
* the core details of the schema, allowing it to be cached.
*
* @return map with the details extracted from the schema class
*/
public LabelMap getAttributes() {
return attributes.clone();
}
/**
* Returns a <code>LabelMap</code> that contains the details for
* all fields marked as XML elements. The annotations that are
* considered elements are the <code>ElementList</code> and the
* <code>Element</code> annotations. This returns a copy of the
* details extracted from the schema class so this can be cached.
*
* @return a map containing the details for XML elements
*/
public LabelMap getElements() {
return elements.clone();
}
/**
* This returns the <code>Label</code> that represents the text
* annotation for the scanned class. Only a single text annotation
* can be used per class, so this returns only a single label
* rather than a <code>LabelMap</code> object. Also if this is
* not null then the elements label map must be empty.
*
* @return this returns the text label for the scanned class
*/
public Label getText() {
return text;
}
/**
* This returns the name of the class processed by this scanner.
* The name is either the name as specified in the last found
* <code>Root</code> annotation, or if a name was not specified
* within the discovered root then the Java Bean class name of
* the last class annotated with a root annotation.
*
* @return this returns the name of the object being scanned
*/
public String getName() {
return name;
}
/**
* This method is used to retrieve the schema class commit method
* during the deserialization process. The commit method must be
* marked with the <code>Commit</code> annotation so that when the
* object is deserialized the persister has a chance to invoke the
* method so that the object can build further data structures.
*
* @return this returns the commit method for the schema class
*/
public Method getCommit() {
return commit;
}
/**
* This method is used to return the <code>Conduit</code> for this
* class. The conduit is a means to deliver invocations to the
* object for the persister callback methods. It aggregates all of
* the persister callback methods in to a single object.
*
* @return this returns a conduit used for delivering callbacks
*/
public Conduit getConduit() {
return new Conduit(this);
}
/**
* This method is used to retrieve the schema class validation
* method during the deserialization process. The validation method
* must be marked with the <code>Validate</code> annotation so that
* when the object is deserialized the persister has a chance to
* invoke that method so that object can validate its field values.
*
* @return this returns the validate method for the schema class
*/
public Method getValidate() {
return validate;
}
/**
* This method is used to retrieve the schema class persistence
* method. This is invoked during the serialization process to
* get the object a chance to perform an nessecary preparation
* before the serialization of the object proceeds. The persist
* method must be marked with the <code>Persist</code> annotation.
*
* @return this returns the persist method for the schema class
*/
public Method getPersist() {
return persist;
}
/**
* This method is used to retrieve the schema class completion
* method. This is invoked after the serialization process has
* completed and gives the object a chance to restore its state
* if the persist method required some alteration or locking.
* This is marked with the <code>Complete</code> annotation.
*
* @return returns the complete method for the schema class
*/
public Method getComplete() {
return complete;
}
/**
* This method is used to retrieve the schema class replacement
* method. The replacement method is used to substitute an object
* that has been deserialized with another object. This allows
* a seamless delegation mechanism to be implemented. This is
* marked with the <code>Replace</code> annotation.
*
* @return returns the replace method for the schema class
*/
public Method getReplace() {
return replace;
}
/**
* This method is used to retrieve the schema class replacement
* method. The replacement method is used to substitute an object
* that has been deserialized with another object. This allows
* a seamless delegation mechanism to be implemented. This is
* marked with the <code>Replace</code> annotation.
*
* @return returns the replace method for the schema class
*/
public Method getResolve() {
return resolve;
}
/**
* This is used to determine whether the scanned class represents
* a primitive type. A primitive type is a type that contains no
* XML annotations and so cannot be serialized with an XML form.
* Instead primitives a serialized using transformations.
*
* @return this returns true if no XML annotations were found
*/
public boolean isPrimitive() {
return primitive;
}
/**
* This is used to determine whether the scanned class represents
* a primitive type. A primitive type is a type that contains no
* XML annotations and so cannot be serialized with an XML form.
* Instead primitives a serialized using transformations.
*
* @return this returns true if no XML annotations were found
*/
private boolean isEmpty() {
if(!elements.isEmpty()) {
return false;
}
if(!attributes.isEmpty()) {
return false;
}
if(text != null) {
return false;
}
return root == null;
}
/**
* This method is used to determine whether strict mappings are
* required. Strict mapping means that all labels in the class
* schema must match the XML elements and attributes in the
* source XML document. When strict mapping is disabled, then
* XML elements and attributes that do not exist in the schema
* class will be ignored without breaking the parser.
*
* @return true if strict parsing is enabled, false otherwise
*/
public boolean isStrict() {
if(root != null) {
return root.strict();
}
return true;
}
/**
* Scan the fields and methods such that the given class is scanned
* first then all super classes up to the root <code>Object</code>.
* All fields and methods from the most specialized classes override
* fields and methods from higher up the inheritance heirarchy. This
* means that annotated details can be overridden and so may not
* have a value assigned to them during deserialization.
*
* @param type the class to extract fields and methods from
*/
private void scan(Class type) throws Exception {
Class real = type;
while(type != null) {
if(root == null) {
root(type);
}
if(order == null) {
order(type);
}
scan(real, type);
type = type.getSuperclass();
}
process(real);
}
/**
* This is used to scan the specified class for methods so that
* the persister callback annotations can be collected. These
* annotations help object implementations to validate the data
* that is injected into the instance during deserialization.
*
* @param real this is the actual type of the scanned class
* @param type this is a type from within the class heirarchy
*
* @throws Exception thrown if the class schema is invalid
*/
private void scan(Class real, Class type) throws Exception {
Method[] method = type.getDeclaredMethods();
for(int i = 0; i < method.length; i++) {
Method next = method[i];
if(!next.isAccessible()) {
next.setAccessible(true);
}
scan(next);
}
}
/**
* This is used to validate the configuration of the scanned class.
* If a <code>Text</code> annotation has been used with elements
* then validation will fail and an exception will be thrown.
*
* @param type this is the object type that is being scanned
*
* @throws Exception if text and element annotations are present
*/
private void validate(Class type) throws Exception {
if(text != null) {
if(!elements.isEmpty()) {
throw new TextException("Elements used with %s in %s", text, type);
}
} else {
primitive = isEmpty();
}
if(order != null) {
validateElements(type);
validateAttributes(type);
}
}
/**
* This is used to validate the configuration of the scanned class.
* If an ordered element is specified but does not refer to an
* existing element then this will throw an exception.
*
* @param type this is the object type that is being scanned
*
* @throws Exception if an ordered element does not exist
*/
private void validateElements(Class type) throws Exception {
for(String name : order.elements()) {
Label label = elements.get(name);
if(label == null) {
throw new ElementException("Ordered element '%s' missing for %s", name, type);
}
}
}
/**
* This is used to validate the configuration of the scanned class.
* If an ordered attribute is specified but does not refer to an
* existing attribute then this will throw an exception.
*
* @param type this is the object type that is being scanned
*
* @throws Exception if an ordered attribute does not exist
*/
private void validateAttributes(Class type) throws Exception {
for(String name : order.attributes()) {
Label label = attributes.get(name);
if(label == null) {
throw new AttributeException("Ordered attribute '%s' missing for %s", name, type);
}
}
}
/**
* This is used to acquire the optional <code>Root</code> from the
* specified class. The root annotation provides information as
* to how the object is to be parsed as well as other information
* such as the name of the object if it is to be serialized.
*
* @param type this is the type of the class to be inspected
*/
private void root(Class<?> type) {
String real = type.getSimpleName();
String text = real;
if(type.isAnnotationPresent(Root.class)) {
root = type.getAnnotation(Root.class);
text = root.name();
if(isEmpty(text)) {
text = Introspector.decapitalize(real);
}
name = text.intern();
}
}
/**
* This is used to acquire the optional order annotation to provide
* order to the elements and attributes for the generated XML. This
* acts as an override to the order provided by the declaration of
* the types within the object.
*
* @param type this is the type to be scanned for the order
*/
private void order(Class<?> type) {
if(type.isAnnotationPresent(Order.class)) {
order = type.getAnnotation(Order.class);
for(String name : order.elements()) {
elements.put(name, null);
}
for(String name : order.attributes()) {
attributes.put(name, null);
}
}
}
/**
* This method is used to determine if a root annotation value is
* an empty value. Rather than determining if a string is empty
* be comparing it to an empty string this method allows for the
* value an empty string represents to be changed in future.
*
* @param value this is the value to determine if it is empty
*
* @return true if the string value specified is an empty value
*/
private boolean isEmpty(String value) {
return value.length() == 0;
}
/**
* This is used to scan the specified object to extract the fields
* and methods that are to be used in the serialization process.
* This will acquire all fields and getter setter pairs that have
* been annotated with the XML annotations.
*
* @param type this is the object type that is to be scanned
*/
private void process(Class type) throws Exception {
field(type);
method(type);
validate(type);
}
/**
* This is used to acquire the contacts for the annotated fields
* within the specified class. The field contacts are added to
* either the attributes or elements map depending on annotation.
*
* @param type this is the object type that is to be scanned
*/
public void field(Class type) throws Exception {
ContactList list = new FieldScanner(type);
for(Contact contact : list) {
scan(contact, contact.getAnnotation());
}
}
/**
* This is used to acquire the contacts for the annotated fields
* within the specified class. The field contacts are added to
* either the attributes or elements map depending on annotation.
*
* @param type this is the object type that is to be scanned
*/
public void method(Class type) throws Exception {
ContactList list = new MethodScanner(type);
for(Contact contact : list) {
scan(contact, contact.getAnnotation());
}
}
/**
* This reflectively checks the annotation to determine the type
* of annotation it represents. If it represents an XML schema
* annotation it is used to create a <code>Label</code> which can
* be used to represent the field within the source object.
*
* @param field the field that the annotation comes from
* @param label the annotation used to model the XML schema
*
* @throws Exception if there is more than one text annotation
*/
private void scan(Contact field, Annotation label) throws Exception {
if(label instanceof Attribute) {
process(field, label, attributes);
}
if(label instanceof ElementList) {
process(field, label, elements);
}
if(label instanceof ElementArray) {
process(field, label, elements);
}
if(label instanceof ElementMap) {
process(field, label, elements);
}
if(label instanceof Element) {
process(field, label, elements);
}
if(label instanceof Text) {
process(field, label);
}
}
/**
* This is used to process the <code>Text</code> annotations that
* are present in the scanned class. This will set the text label
* for the class and an ensure that if there is more than one
* text label within the class an exception is thrown.
*
* @param field the field the annotation was extracted from
* @param type the annotation extracted from the field
*
* @throws Exception if there is more than one text annotation
*/
private void process(Contact field, Annotation type) throws Exception {
Label label = LabelFactory.getInstance(field, type);
if(text != null) {
throw new TextException("Multiple text annotations in %s", type);
}
text = label;
}
/**
* This is used when all details from a field have been gathered
* and a <code>Label</code> implementation needs to be created.
* This will build a label instance based on the field annotation.
* If a label with the same name was already inserted then it is
* ignored and the value for that field will not be serialized.
*
* @param field the field the annotation was extracted from
* @param type the annotation extracted from the field
* @param map this is used to collect the label instance created
*
* @throws Exception thrown if the label can not be created
*/
private void process(Contact field, Annotation type, LabelMap map) throws Exception {
Label label = LabelFactory.getInstance(field, type);
String name = label.getName();
if(map.get(name) != null) {
throw new PersistenceException("Annotation of name '%s' declared twice", name);
}
map.put(name, label);
}
/**
* Scans the provided method for a persister callback method. If
* the method contains an method annotated as a callback that
* method is stored so that it can be invoked by the persister
* during the serialization and deserialization process.
*
* @param method this is the method to scan for callback methods
*/
private void scan(Method method) {
if(commit == null) {
commit(method);
}
if(validate == null) {
validate(method);
}
if(persist == null) {
persist(method);
}
if(complete == null) {
complete(method);
}
if(replace == null) {
replace(method);
}
if(resolve == null) {
resolve(method);
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Replace</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void replace(Method method) {
Annotation mark = method.getAnnotation(Replace.class);
if(mark != null) {
replace = method;
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Resolve</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void resolve(Method method) {
Annotation mark = method.getAnnotation(Resolve.class);
if(mark != null) {
resolve = method;
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Commit</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void commit(Method method) {
Annotation mark = method.getAnnotation(Commit.class);
if(mark != null) {
commit = method;
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Validate</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void validate(Method method) {
Annotation mark = method.getAnnotation(Validate.class);
if(mark != null) {
validate = method;
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Persist</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void persist(Method method) {
Annotation mark = method.getAnnotation(Persist.class);
if(mark != null) {
persist = method;
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Complete</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void complete(Method method) {
Annotation mark = method.getAnnotation(Complete.class);
if(mark != null) {
complete = method;
}
}
} |
package org.tapestry.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.sql.DataSource;
import org.tapestry.objects.SurveyResult;
/**
* An implementation of the SurveyResultDAO interface.
*
* lxie
*/
@Repository
public class SurveyResultDAOImpl extends JdbcDaoSupport implements SurveyResultDAO {
@Autowired
public SurveyResultDAOImpl(DataSource dataSource) {
setDataSource(dataSource);
}
@Override
public List<SurveyResult> getSurveysByPatientID(int patientId) {
String sql = "SELECT survey_results.*, surveys.title, surveys.description, patients.firstname, patients.lastname FROM survey_results"
+ " INNER JOIN surveys ON survey_results.survey_ID = surveys.survey_ID INNER JOIN patients"
+ " ON survey_results.patient_ID=patients.patient_ID WHERE survey_results.patient_ID=?"
+ " ORDER BY survey_results.startDate ";
List<SurveyResult> results = getJdbcTemplate().query(sql, new Object[]{patientId}, new SurveyResultMapper());
return results;
}
@Override
public List<SurveyResult> getCompletedSurveysByPatientID(int patientId) {
String sql = "SELECT survey_results.*, surveys.title, surveys.description, patients.firstname, patients.lastname "
+ "FROM survey_results INNER JOIN surveys ON survey_results.survey_ID = surveys.survey_ID INNER JOIN patients"
+ " ON survey_results.patient_ID=patients.patient_ID WHERE survey_results.patient_ID=? AND"
+ " survey_results.completed = 1 ORDER BY survey_results.startDate ";
List<SurveyResult> results = getJdbcTemplate().query(sql, new Object[]{patientId}, new SurveyResultMapper());
return results;
}
@Override
public List<SurveyResult> getIncompleteSurveysByPatientID(int patientId) {
String sql = "SELECT survey_results.*, surveys.title, surveys.description, patients.firstname, patients.lastname "
+ "FROM survey_results INNER JOIN surveys ON survey_results.survey_ID = surveys.survey_ID INNER JOIN patients"
+ " ON survey_results.patient_ID=patients.patient_ID WHERE survey_results.patient_ID=? AND"
+ " survey_results.completed = 0 ORDER BY survey_results.startDate ";
List<SurveyResult> results = getJdbcTemplate().query(sql, new Object[]{patientId}, new SurveyResultMapper());
return results;
}
@Override
public SurveyResult getSurveyResultByID(int resultId) {
String sql = "SELECT survey_results.*, surveys.title, surveys.description, patients.firstname, patients.lastname "
+ "FROM survey_results INNER JOIN surveys ON survey_results.survey_ID = surveys.survey_ID INNER JOIN patients"
+ " ON survey_results.patient_ID=patients.patient_ID WHERE survey_results.result_ID=? "
+ " ORDER BY survey_results.startDate ";
return getJdbcTemplate().queryForObject(sql, new Object[]{resultId}, new SurveyResultMapper());
}
@Override
public List<SurveyResult> getAllSurveyResults() {
String sql = "SELECT survey_results.*, surveys.title, surveys.description, patients.firstname, patients.lastname FROM survey_results"
+ " INNER JOIN surveys ON survey_results.survey_ID = surveys.survey_ID INNER JOIN patients"
+ " ON survey_results.patient_ID=patients.patient_ID ORDER BY survey_results.startDate ";
List<SurveyResult> results = getJdbcTemplate().query(sql, new SurveyResultMapper());
return results;
}
@Override
public List<SurveyResult> getAllSurveyResultsBySurveyId(int surveyId) {
String sql = "SELECT survey_results.*, surveys.title, surveys.description, patients.firstname, patients.lastname FROM survey_results"
+ " INNER JOIN surveys ON survey_results.survey_ID = surveys.survey_ID INNER JOIN patients"
+ " ON survey_results.patient_ID=patients.patient_ID WHERE survey_results.survey_ID=?"
+ " ORDER BY survey_results.startDate ";
List<SurveyResult> results = getJdbcTemplate().query(sql, new Object[]{surveyId}, new SurveyResultMapper());
return results;
}
@Override
public List<SurveyResult> getSurveyResultByPatientAndSurveyId(int patientId, int surveyId) {
String sql = "SELECT survey_results.*, surveys.title, surveys.description, patients.firstname, patients.lastname FROM survey_results"
+ " INNER JOIN surveys ON survey_results.survey_ID = surveys.survey_ID INNER JOIN patients"
+ " ON survey_results.patient_ID=patients.patient_ID WHERE survey_results.patient_ID=? AND survey_results.survey_ID=?"
+ " ORDER BY survey_results.startDate ";
List<SurveyResult> results = getJdbcTemplate().query(sql, new Object[]{patientId,surveyId}, new SurveyResultMapper());
return results;
}
@Override
public String assignSurvey(final SurveyResult sr) {
final String sql = "INSERT INTO survey_results (patient_ID, survey_ID, data, startDate) values (?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement pst =
con.prepareStatement(sql, new String[] {"id"});
pst.setInt(1, sr.getPatientID());
pst.setInt(2, sr.getSurveyID());
pst.setBytes(3, sr.getResults());
pst.setString(4, sr.getStartDate());
return pst;
}
},
keyHolder);
return String.valueOf((Long)keyHolder.getKey());
}
@Override
public void deleteSurvey(int id) {
String sql = "DELETE FROM survey_results WHERE result_ID=?";
getJdbcTemplate().update(sql, id);
}
@Override
public void markAsComplete(int id) {
String sql = "UPDATE survey_results SET completed=1 WHERE result_ID=?";
getJdbcTemplate().update(sql, id);
}
@Override
public void updateSurveyResults(int id, byte[] data) {
String sql = "UPDATE survey_results SET data=?, editDate=now() WHERE result_ID=?";
getJdbcTemplate().update(sql, data,id);
}
@Override
public void updateStartDate(int id) {
String sql = "UPDATE survey_results SET startDate=now() WHERE result_ID=?";
getJdbcTemplate().update(sql, id);
}
@Override
public int countCompletedSurveys(int patientId) {
String sql = "SELECT COUNT(*) as c FROM survey_results WHERE (patient_ID=?) AND (completed=1)";
return getJdbcTemplate().queryForInt(sql, new Object[]{patientId});
}
@Override
public int countSurveysBySurveyTemplateId(int surveyTemplateId) {
String sql = "SELECT COUNT(*) as c FROM survey_results WHERE (survey_ID=?)";
return getJdbcTemplate().queryForInt(sql, new Object[]{surveyTemplateId});
}
class SurveyResultMapper implements RowMapper<SurveyResult> {
public SurveyResult mapRow(ResultSet rs, int rowNum) throws SQLException{
SurveyResult sr = new SurveyResult();
sr.setResultID(rs.getInt("result_ID"));
sr.setSurveyID(rs.getInt("survey_ID"));
sr.setSurveyTitle(rs.getString("title"));
sr.setDescription(rs.getString("description"));
sr.setPatientID(rs.getInt("patient_ID"));
sr.setPatientName(rs.getString("firstname") + " " + rs.getString("lastname"));
boolean completed = rs.getBoolean("completed");
sr.setCompleted(completed);
if (completed)
sr.setStrCompleted("COMPLETED");
else
sr.setStrCompleted("INCOMPLETED");
sr.setStartDate(rs.getString("startDate"));
sr.setEditDate(rs.getString("editDate"));
sr.setResults(rs.getBytes("data"));
return sr;
}
}
public void archiveSurveyResult(SurveyResult sr, String patient, String deletedBy){
String sql = "INSERT INTO survey_results_archive (patient, survey_ID, data, startDate, deleted_result_ID, "
+ "deleted_by) values (?,?,?,?,?,?)";
getJdbcTemplate().update(sql, patient, sr.getSurveyID(), sr.getResults(), sr.getStartDate(), sr.getResultID()
, deletedBy);
}
} |
package org.treetank.service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
public class TreeTankService {
/**
* @param args
*/
public static void main(String[] args) {
try {
final Map map = new ConcurrentHashMap();
final Server server = new Server();
final Connector connector = new SocketConnector();
// final Connector connector = new SslSocketConnector();
final Handler handler = new TreeTankHandler(map);
connector.setPort(8182);
// ((SslSocketConnector) connector).setKeystore("keystore");
// ((SslSocketConnector) connector).setPassword("keystore");
// ((SslSocketConnector) connector).setKeyPassword("keystore");
server.setConnectors(new Connector[] { connector });
server.setHandler(handler);
server.start();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
} |
package org.yukung.tutorial.junit;
public class Calculator {
public int multiply(int x, int y) {
return x * y;
}
public float divide(int x, int y) {
if (y == 0)
throw new IllegalArgumentException();
return (float) x / (float) y;
}
} |
package refinedstorage.tile;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraftforge.fluids.FluidStack;
import refinedstorage.RS;
import refinedstorage.RSBlocks;
import refinedstorage.RSUtils;
import refinedstorage.api.network.INetworkMaster;
import refinedstorage.api.storage.fluid.IFluidStorage;
import refinedstorage.api.storage.fluid.IFluidStorageProvider;
import refinedstorage.api.util.IComparer;
import refinedstorage.apiimpl.storage.fluid.FluidStorageNBT;
import refinedstorage.block.BlockFluidStorage;
import refinedstorage.block.EnumFluidStorageType;
import refinedstorage.inventory.ItemHandlerFluid;
import refinedstorage.tile.config.IComparable;
import refinedstorage.tile.config.IExcessVoidable;
import refinedstorage.tile.config.IFilterable;
import refinedstorage.tile.config.IPrioritizable;
import refinedstorage.tile.data.ITileDataProducer;
import refinedstorage.tile.data.TileDataParameter;
import java.util.List;
public class TileFluidStorage extends TileNode implements IFluidStorageProvider, IStorageGui, IComparable, IFilterable, IPrioritizable, IExcessVoidable {
public static final TileDataParameter<Integer> PRIORITY = IPrioritizable.createParameter();
public static final TileDataParameter<Integer> COMPARE = IComparable.createParameter();
public static final TileDataParameter<Boolean> VOID_EXCESS = IExcessVoidable.createParameter();
public static final TileDataParameter<Integer> MODE = IFilterable.createParameter();
public static final TileDataParameter<Integer> STORED = new TileDataParameter<>(DataSerializers.VARINT, 0, new ITileDataProducer<Integer, TileFluidStorage>() {
@Override
public Integer getValue(TileFluidStorage tile) {
return FluidStorageNBT.getStoredFromNBT(tile.storageTag);
}
});
class FluidStorage extends FluidStorageNBT {
public FluidStorage() {
super(TileFluidStorage.this.getStorageTag(), TileFluidStorage.this.getCapacity(), TileFluidStorage.this);
}
@Override
public int getPriority() {
return priority;
}
@Override
public FluidStack insertFluid(FluidStack stack, int size, boolean simulate) {
if (!IFilterable.canTakeFluids(filters, mode, compare, stack)) {
return RSUtils.copyStackWithSize(stack, size);
}
FluidStack result = super.insertFluid(stack, size, simulate);
if (voidExcess && result != null) {
// Simulate should not matter as the fluids are voided anyway
result.amount = -result.amount;
}
return result;
}
}
public static final String NBT_STORAGE = "Storage";
private static final String NBT_PRIORITY = "Priority";
private static final String NBT_COMPARE = "Compare";
private static final String NBT_MODE = "Mode";
private static final String NBT_VOID_EXCESS = "VoidExcess";
private ItemHandlerFluid filters = new ItemHandlerFluid(9, this);
private NBTTagCompound storageTag = FluidStorageNBT.createNBT();
private FluidStorage storage;
private EnumFluidStorageType type;
private int priority = 0;
private int compare = IComparer.COMPARE_NBT;
private int mode = IFilterable.WHITELIST;
private boolean voidExcess = false;
public TileFluidStorage() {
dataManager.addWatchedParameter(PRIORITY);
dataManager.addWatchedParameter(COMPARE);
dataManager.addWatchedParameter(MODE);
dataManager.addWatchedParameter(STORED);
dataManager.addWatchedParameter(VOID_EXCESS);
}
@Override
public int getEnergyUsage() {
return RS.INSTANCE.config.fluidStorageUsage;
}
@Override
public void updateNode() {
}
@Override
public void update() {
super.update();
if (storage == null && storageTag != null) {
storage = new FluidStorage();
if (network != null) {
network.getFluidStorage().rebuild();
}
}
}
public void onBreak() {
if (storage != null) {
storage.writeToNBT();
}
}
@Override
public void onConnectionChange(INetworkMaster network, boolean state) {
super.onConnectionChange(network, state);
network.getFluidStorage().rebuild();
}
@Override
public void addFluidStorages(List<IFluidStorage> storages) {
if (storage != null) {
storages.add(storage);
}
}
@Override
public void read(NBTTagCompound tag) {
super.read(tag);
RSUtils.readItems(filters, 0, tag);
if (tag.hasKey(NBT_PRIORITY)) {
priority = tag.getInteger(NBT_PRIORITY);
}
if (tag.hasKey(NBT_STORAGE)) {
storageTag = tag.getCompoundTag(NBT_STORAGE);
}
if (tag.hasKey(NBT_COMPARE)) {
compare = tag.getInteger(NBT_COMPARE);
}
if (tag.hasKey(NBT_MODE)) {
mode = tag.getInteger(NBT_MODE);
}
if (tag.hasKey(NBT_VOID_EXCESS)) {
voidExcess = tag.getBoolean(NBT_VOID_EXCESS);
}
}
@Override
public NBTTagCompound write(NBTTagCompound tag) {
super.write(tag);
RSUtils.writeItems(filters, 0, tag);
tag.setInteger(NBT_PRIORITY, priority);
if (storage != null) {
storage.writeToNBT();
}
tag.setTag(NBT_STORAGE, storageTag);
tag.setInteger(NBT_COMPARE, compare);
tag.setInteger(NBT_MODE, mode);
tag.setBoolean(NBT_VOID_EXCESS, voidExcess);
return tag;
}
public EnumFluidStorageType getType() {
if (type == null && worldObj.getBlockState(pos).getBlock() == RSBlocks.FLUID_STORAGE) {
this.type = ((EnumFluidStorageType) worldObj.getBlockState(pos).getValue(BlockFluidStorage.TYPE));
}
return type == null ? EnumFluidStorageType.TYPE_64K : type;
}
@Override
public int getCompare() {
return compare;
}
@Override
public void setCompare(int compare) {
this.compare = compare;
markDirty();
}
@Override
public int getMode() {
return mode;
}
@Override
public void setMode(int mode) {
this.mode = mode;
markDirty();
}
@Override
public String getGuiTitle() {
return "block.refinedstorage:fluid_storage." + getType().getId() + ".name";
}
@Override
public TileDataParameter<Integer> getTypeParameter() {
return null;
}
@Override
public TileDataParameter<Integer> getRedstoneModeParameter() {
return REDSTONE_MODE;
}
@Override
public TileDataParameter<Integer> getCompareParameter() {
return COMPARE;
}
@Override
public TileDataParameter<Integer> getFilterParameter() {
return MODE;
}
@Override
public TileDataParameter<Integer> getPriorityParameter() {
return PRIORITY;
}
@Override
public TileDataParameter<Boolean> getVoidExcessParameter() {
return VOID_EXCESS;
}
@Override
public String getVoidExcessType() {
return "fluids";
}
public NBTTagCompound getStorageTag() {
return storageTag;
}
public void setStorageTag(NBTTagCompound storageTag) {
this.storageTag = storageTag;
}
public FluidStorageNBT getStorage() {
return storage;
}
public ItemHandlerFluid getFilters() {
return filters;
}
@Override
public int getPriority() {
return priority;
}
@Override
public void setPriority(int priority) {
this.priority = priority;
markDirty();
}
@Override
public int getStored() {
return STORED.getValue();
}
@Override
public int getCapacity() {
return getType().getCapacity();
}
@Override
public boolean getVoidExcess() {
return voidExcess;
}
@Override
public void setVoidExcess(boolean value) {
this.voidExcess = value;
markDirty();
}
} |
package ru.doublebyte.telegramWeatherBot;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.doublebyte.telegramWeatherBot.enums.ChatAction;
import ru.doublebyte.telegramWeatherBot.enums.ParseMode;
import ru.doublebyte.telegramWeatherBot.enums.RequestType;
import ru.doublebyte.telegramWeatherBot.types.*;
import ru.doublebyte.telegramWeatherBot.utils.JsonUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Bot {
private static final Logger logger = LoggerFactory.getLogger(Bot.class);
private String apiUrl = "https://api.telegram.org/bot{token}/{request}";
private String token = "";
/**
* Maximum update id. Used for getUpdates
*/
private int maxUpdateId = 0;
/**
* Maximum number of messages loaded with getUpdates
*/
private int updateLimit = 100;
/**
* Timeout for long polling in getUpdates (seconds)
*/
private int updateTimeout = 0;
public Bot(String token) {
this.token = token;
}
/**
* Get bot user info
* @return Bot user info
*/
protected User getMe() throws Exception {
JSONObject me = makeRequest(RequestType.getMe);
User user = JsonUtil.toObject(me, User.class);
if(user == null) {
throw new Exception("Cannot parse bot user info");
}
return user;
}
/**
* Get all available updates
* @return Array of updates
*/
protected List<Message> getUpdates() {
return getUpdates(maxUpdateId + 1, updateLimit, updateTimeout);
}
/**
* Send message to user or group
* @param chatId Identifier of user or group
* @param text Message text
* @return Message object sent to server
* @throws Exception
*/
protected Message sendMessage(int chatId, String text) throws Exception{
Map<String, Object> query = new HashMap<>();
query.put("chat_id", chatId);
query.put("text", text);
return sendMessage(query);
}
/**
* Send message to user or group as reply to other message
* @param chatId Identifier of user or group
* @param text Message text
* @param replyToMessageId Identifier of message to reply
* @return Message object sent to server
* @throws Exception
*/
protected Message sendMessage(int chatId, String text, int replyToMessageId) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("chat_id", chatId);
query.put("text", text);
query.put("reply_to_message_id", replyToMessageId);
return sendMessage(query);
}
/**
* Send message to user or group
* @param chatId Identifier of user or group
* @param text Message text
* @param parseMode Parse mode for markdown
* @param disableWebPagePreview Disables link previews for links in this message
* @param replyToMessageId Identifier of message to reply
* @return Message object sent to server
* @throws Exception
*/
protected Message sendMessage(int chatId, String text, ParseMode parseMode,
boolean disableWebPagePreview, int replyToMessageId) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("chat_id", chatId);
query.put("text", text);
query.put("parse_mode", parseMode.toString());
query.put("disable_web_page_preview", disableWebPagePreview);
query.put("reply_to_message_id", replyToMessageId);
return sendMessage(query);
}
/**
* Forward any message
* @param chatId Message recipient
* @param fromChatId Chat where the original message was sent
* @param messageId Message identifier
* @return Message object sent
* @throws Exception
*/
protected Message forwardMessage(int chatId, int fromChatId, int messageId) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("chat_id", chatId);
query.put("from_chat_id", fromChatId);
query.put("message_id", messageId);
JSONObject messageObject = makeRequest(RequestType.forwardMessage, query);
Message message = JsonUtil.toObject(messageObject, Message.class);
if(message == null) {
throw new Exception("Cannot parse sent message");
}
return message;
}
//TODO sendPhoto
//TODO sendAudio
//TODO sendDocument
//TODO sendSticker
//TODO sendVideo
//TODO sendVoice
/**
* Send location
* @param chatId Chat
* @param latitude Latitude
* @param longitude Longitude
* @return Message sent to server
*/
protected Message sendLocation(int chatId, double latitude, double longitude) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("chat_id", chatId);
query.put("latitude", latitude);
query.put("longitude", longitude);
return sendLocation(query);
}
/**
* Send location as reply to a message
* @param chatId Chat
* @param latitude Latitude
* @param longitude Longitude
* @param replyToMessageId Message id to reply
* @return Message sent to server
* @throws Exception
*/
protected Message sendLocation(int chatId, double latitude, double longitude, int replyToMessageId) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("chat_it", chatId);
query.put("latitude", latitude);
query.put("longitude", longitude);
query.put("reply_to_message_id", replyToMessageId);
return sendLocation(query);
}
/**
* Send chat action
* @param chatId Recipient
* @param action Action name
* @throws Exception
*/
protected void sendChatAction(int chatId, ChatAction action) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("chat_id", chatId);
query.put("action", action.toString());
makeRequest(RequestType.sendChatAction, query);
}
/**
* Get user profile photos
* @param userId User
* @return User profile photos description
* @throws Exception
*/
protected UserProfilePhotos getUserProfilePhotos(int userId) throws Exception {
Map<String, Object> query =new HashMap<>();
query.put("user_id", userId);
return getUserProfilePhotos(query);
}
/**
* Get user profile photos
* @param userId User
* @param offset Sequential number of the first photo to be returned
* @param limit Limits the number of photos to be retrieved
* @return User profile photos description
* @throws Exception
*/
protected UserProfilePhotos getUserProfilePhotos(int userId, int offset, int limit) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("user_id", userId);
query.put("offset", offset);
query.put("limit", limit);
return getUserProfilePhotos(query);
}
/**
* Get file download info
* @param fileId File id
* @return File download info
*/
protected File getFile(int fileId) throws Exception {
Map<String, Object> query = new HashMap<>();
query.put("file_id", fileId);
JSONObject fileObject = makeRequest(RequestType.getFile, query);
File file = JsonUtil.toObject(fileObject, File.class);
if(file == null) {
throw new Exception("Cannot parse file");
}
return file;
}
/**
* Make request to telegram bot api
* @param requestType Type of request
* @return Request result
*/
private JSONObject makeRequest(RequestType requestType, Map<String, Object> parameters) throws Exception {
try {
HttpResponse<JsonNode> response = Unirest.get(apiUrl)
.routeParam("token", token)
.routeParam("request", requestType.toString())
.queryString(parameters)
.asJson();
JSONObject result = response.getBody().getObject();
boolean ok = result.getBoolean("ok");
if(!ok) {
String description = result.getString("description");
throw new Exception("Telegram API error: " + description);
}
return result.optJSONObject("result");
} catch(Exception e) {
logger.error("Failed to make request: " + requestType);
throw e;
}
}
/**
* Make api request without parameters
* @param requestType Type of request
* @return Request result
*/
private JSONObject makeRequest(RequestType requestType) throws Exception {
return makeRequest(requestType, new HashMap<>());
}
/**
* Get updates from Telegram
* @return Array of updates
*/
private List<Message> getUpdates(int offset, int limit, int timeout) {
try {
HttpResponse<JsonNode> response = Unirest.get(apiUrl)
.routeParam("token", token)
.routeParam("request", RequestType.getUpdates.toString())
.queryString("offset", offset)
.queryString("limit", limit)
.queryString("timeout", timeout)
.asJson();
JSONObject result = response.getBody().getObject();
boolean ok = result.getBoolean("ok");
if(!ok) {
String description = result.getString("description");
throw new Exception("Telegram API error: " + description);
}
JSONArray array = result.getJSONArray("result");
List<Message> updates = new ArrayList<>();
for(int idx = 0; idx < array.length(); idx++) {
Update update = JsonUtil.toObject(array.getJSONObject(idx), Update.class);
if(update == null) {
logger.warn("Cannot parse an update");
continue;
}
if(update.getMessage() == null) {
continue;
}
maxUpdateId = Math.max(maxUpdateId, update.getUpdateId());
updates.add(update.getMessage());
}
return updates;
} catch(Exception e) {
logger.error("Failed to get updates", e);
return new ArrayList<>();
}
}
/**
* Send message to user or group described by given parameters
* @param query Message parameters
* @return Message sent to server
* @throws Exception
*/
private Message sendMessage(Map<String, Object> query) throws Exception {
JSONObject messageObject = makeRequest(RequestType.sendMessage, query);
Message message = JsonUtil.toObject(messageObject, Message.class);
if(message == null) {
throw new Exception("Cannot parse sent message");
}
return message;
}
/**
* Send location with given parameters
* @param query Query parameters
* @return Message sent to server
* @throws Exception
*/
private Message sendLocation(Map<String, Object> query) throws Exception {
JSONObject messageObject = makeRequest(RequestType.sendLocation, query);
Message message = JsonUtil.toObject(messageObject, Message.class);
if(message == null) {
throw new Exception("Cannot parse sent message");
}
return message;
}
/**
* Get user profile photos with given parameters
* @param query Query parameters
* @return User profile photos description
* @throws Exception
*/
private UserProfilePhotos getUserProfilePhotos(Map<String, Object> query) throws Exception {
JSONObject photosObject = makeRequest(RequestType.getUserProfilePhotos, query);
UserProfilePhotos photos = JsonUtil.toObject(photosObject, UserProfilePhotos.class);
if(photos == null) {
throw new Exception("Cannot parse user profile photos");
}
return photos;
}
public String getApiUrl() {
return apiUrl;
}
public String getToken() {
return token;
}
public int getUpdateLimit() {
return updateLimit;
}
public int getUpdateTimeout() {
return updateTimeout;
}
public void setUpdateLimit(int updateLimit) {
if(updateLimit < 1 || updateLimit > 100) {
throw new IllegalArgumentException("Update limit must be in bounds [1, 100]");
}
this.updateLimit = updateLimit;
}
public void setUpdateTimeout(int updateTimeout) {
if(updateTimeout < 0) {
throw new IllegalArgumentException("Update timeout cannot be negative");
}
this.updateTimeout = updateTimeout;
}
} |
package sagex.phoenix.menu;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import sagex.phoenix.util.var.DynamicVariable;
public class XmlMenuSerializer {
public XmlMenuSerializer() {
}
public void serialize(Menu menu, OutputStream os) throws IOException {
Document doc = createDocument();
serializeMenu(menu, doc.getRootElement());
writeDocument(doc, os);
}
private Document createDocument() {
Document doc = DocumentHelper.createDocument();
doc.setDocType(DocumentFactory.getInstance().createDocType("menus", null, "menus.dtd"));
doc.addElement("menus");
return doc;
}
private void writeDocument(Document doc, OutputStream os) throws IOException {
XMLWriter writer = new XMLWriter(os, OutputFormat.createPrettyPrint());
writer.write(doc);
os.flush();
}
public void serializeFragment(IMenuItem item, String parentMenu, String insertBefore, String insertAfter, OutputStream os)
throws IOException {
Document doc = createDocument();
Element menus = doc.getRootElement();
Element fragment = menus.addElement("fragment");
fragment.addAttribute("parentMenu", parentMenu);
if (!StringUtils.isEmpty(insertBefore)) {
fragment.addAttribute("insertBefore", insertBefore);
}
if (!StringUtils.isEmpty(insertAfter)) {
fragment.addAttribute("insertAfter", insertAfter);
}
if (item instanceof Menu) {
serializeMenu((Menu) item, fragment);
} else {
serializeMenuItem(item, fragment);
}
writeDocument(doc, os);
}
private void serializeMenu(Menu menu, Element parent) {
Element el = parent.addElement("menu").addAttribute("name", menu.getName());
if (menu.type().getValue() != null) {
el.addAttribute("type", menu.type().getValue());
}
serializeCommon(menu, el);
List<IMenuItem> items = menu.getItems();
if (items.size() > 0) {
for (IMenuItem mi : items) {
if (mi instanceof ViewMenu) {
serializeViewMenu((ViewMenu) mi, el);
} else if (mi instanceof Menu) {
serializeMenu((Menu) mi, el);
} else {
serializeMenuItem(mi, el);
}
}
}
}
private void serializeViewMenu(ViewMenu menu, Element parent) {
Element el = parent.addElement("view").addAttribute("name", menu.getName());
if (menu.type().getValue() != null) {
el.addAttribute("type", menu.type().getValue());
}
el.addAttribute("preload", String.valueOf(menu.isPreloaded()));
el.addAttribute("contextVar", menu.getContextVar());
serializeCommon(menu, el);
if (menu.getActions().size() > 0) {
for (Action a : menu.getActions()) {
serializeAction(menu, a, el);
}
}
}
private void serializeMenuItem(IMenuItem mi, Element parent) {
Element el = parent.addElement("menuItem");
if (mi.getName() != null) {
el.addAttribute("name", mi.getName());
}
serializeCommon(mi, el);
if (mi.getActions().size() > 0) {
for (Action a : mi.getActions()) {
serializeAction(mi, a, el);
}
}
}
public void serializeAction(IMenuItem mi, Action a, Element parent) {
if (a instanceof SageScreenAction) {
serializeAction(mi, (SageScreenAction) a, parent);
} else if (a instanceof SageCommandAction) {
serializeAction(mi, (SageCommandAction) a, parent);
} else if (a instanceof SageEvalAction) {
serializeAction(mi, (SageEvalAction) a, parent);
} else if (a instanceof ExecuteCommandAction) {
serializeAction(mi, (ExecuteCommandAction) a, parent);
} else if (a instanceof ScriptAction) {
serializeAction(mi, (ScriptAction) a, parent);
} else {
throw new UnsupportedOperationException("Action not supported: " + a);
}
}
public void serializeAction(IMenuItem mi, ScriptAction a, Element parent) {
Element el = parent.addElement("script");
if (a.getScript() != null) {
if (!StringUtils.isEmpty(a.getScript().getLanguage())) {
el.addAttribute("language", a.getScript().getLanguage());
}
if (!StringUtils.isEmpty(a.getScript().getScript())) {
el.addCDATA(a.getScript().getScript());
}
}
}
public void serializeAction(IMenuItem mi, SageCommandAction a, Element parent) {
parent.addElement("sageCommand").addAttribute("name", a.action().getValue());
}
public void serializeAction(IMenuItem mi, SageEvalAction a, Element parent) {
Element el = parent.addElement("eval");
if (a.outputVariable != null) {
el.addAttribute("outputVariable", a.outputVariable);
}
el.addCDATA(a.action().getValue());
}
public void serializeAction(IMenuItem mi, SageScreenAction a, Element parent) {
parent.addElement("screen").addAttribute("name", a.action().getValue());
}
public void serializeAction(IMenuItem mi, ExecuteCommandAction a, Element parent) {
Element el = parent.addElement("exec");
if (a.getOS() != null) {
el.addAttribute("os", a.getOS());
}
if (a.getOutputVariable() != null) {
el.addAttribute("outputVariable", a.getOutputVariable());
}
if (a.getArgs() != null) {
el.addAttribute("args", a.getArgs());
}
if (a.workingDir().getValue() != null) {
el.addAttribute("workingDir", a.workingDir().getValue());
}
el.addAttribute("cmd", a.action().getValue());
}
public void serializeCommon(IMenuItem item, Element el) {
if (item.background().getValue() != null) {
el.addAttribute("background", item.background().getValue());
}
if (item.icon().getValue() != null) {
el.addAttribute("icon", item.icon().getValue());
}
if (item.label().getValue() != null) {
el.addAttribute("label", item.label().getValue());
}
if (item.linkedMenuId().getValue() != null) {
el.addAttribute("linkedMenu", item.linkedMenuId().getValue());
}
if (item.secondaryIcon().getValue() != null) {
el.addAttribute("secondaryIcon", item.secondaryIcon().getValue());
}
if (item.visible().getValue() != null) {
el.addAttribute("visible", item.visible().getValue());
}
if (item.isDefault().getValue() != null) {
el.addAttribute("isDefault", item.isDefault().getValue());
}
if (item.description().getValue() != null) {
Element desc = el.addElement("description");
desc.addCDATA(item.description().getValue());
}
if (((MenuItem) item).getFields().size() > 0) {
serializeFields(((MenuItem) item).getFields(), el);
}
}
private void serializeFields(Map<String, DynamicVariable<String>> fields, Element parent) {
Element field = parent.addElement("field");
for (Map.Entry<String, DynamicVariable<String>> me : fields.entrySet()) {
field.addAttribute("name", me.getKey());
field.addText(me.getValue().getValue());
}
}
} |
package seedu.address.storage;
import seedu.address.commons.util.XmlUtil;
import seedu.address.commons.exceptions.DataConversionException;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Stores taskmanager data in an XML file
*/
public class XmlFileStorage {
/**
* Saves the given taskmanager data to the specified file.
*/
public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager)
throws FileNotFoundException {
try {
XmlUtil.saveDataToFile(file, taskManager);
} catch (JAXBException e) {
assert false : "Unexpected exception " + e.getMessage();
}
}
/**
* Returns address book in the file or an empty address book
*/
public static XmlSerializableTaskManager loadDataFromSaveFile(File file) throws DataConversionException,
FileNotFoundException {
try {
return XmlUtil.getDataFromFile(file, XmlSerializableTaskManager.class);
} catch (JAXBException e) {
throw new DataConversionException(e);
}
}
} |
package us.myles.ViaVersion;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import lombok.NonNull;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import us.myles.ViaVersion.api.Pair;
import us.myles.ViaVersion.api.ViaVersion;
import us.myles.ViaVersion.api.ViaVersionAPI;
import us.myles.ViaVersion.api.ViaVersionConfig;
import us.myles.ViaVersion.api.boss.BossBar;
import us.myles.ViaVersion.api.boss.BossColor;
import us.myles.ViaVersion.api.boss.BossStyle;
import us.myles.ViaVersion.api.command.ViaVersionCommand;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.protocol.ProtocolRegistry;
import us.myles.ViaVersion.boss.ViaBossBar;
import us.myles.ViaVersion.commands.ViaCommandHandler;
import us.myles.ViaVersion.handlers.ViaVersionInitializer;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.update.UpdateListener;
import us.myles.ViaVersion.update.UpdateUtil;
import us.myles.ViaVersion.util.Configuration;
import us.myles.ViaVersion.util.ListWrapper;
import us.myles.ViaVersion.util.ReflectionUtil;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI, ViaVersionConfig {
private final Map<UUID, UserConnection> portedPlayers = new ConcurrentHashMap<>();
private List<ChannelFuture> injectedFutures = new ArrayList<>();
private List<Pair<Field, Object>> injectedLists = new ArrayList<>();
private ViaCommandHandler commandHandler;
private boolean debug = false;
@Override
public void onLoad() {
ViaVersion.setInstance(this);
generateConfig();
if (System.getProperty("ViaVersion") != null) {
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") != null) {
getLogger().severe("ViaVersion is already loaded, we're going to kick all the players... because otherwise we'll crash because of ProtocolLib.");
for (Player player : Bukkit.getOnlinePlayers()) {
player.kickPlayer("Server reload, please rejoin!");
}
} else {
getLogger().severe("ViaVersion is already loaded, this should work fine... Otherwise reboot the server!!!");
}
}
getLogger().info("ViaVersion " + getDescription().getVersion() + " is now loaded, injecting.");
injectPacketHandler();
}
@Override
public void onEnable() {
if (isCheckForUpdates())
UpdateUtil.sendUpdateMessage(this);
// Gather version :)
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
gatherProtocolVersion();
// Check if there are any pipes to this version
if (ProtocolRegistry.SERVER_PROTOCOL != -1) {
getLogger().info("ViaVersion detected protocol version: " + ProtocolRegistry.SERVER_PROTOCOL);
if (!ProtocolRegistry.isWorkingPipe()) {
getLogger().warning("ViaVersion will not function on the current protocol.");
}
}
}
});
Bukkit.getPluginManager().registerEvents(new UpdateListener(this), this);
getCommand("viaversion").setExecutor(commandHandler = new ViaCommandHandler());
getCommand("viaversion").setTabCompleter(commandHandler);
// Register Protocol Listeners
ProtocolRegistry.registerListeners();
}
@Override
public void onDisable() {
getLogger().info("ViaVersion is disabling, if this is a reload it may not work.");
uninject();
}
public void gatherProtocolVersion() {
try {
Class<?> serverClazz = ReflectionUtil.nms("MinecraftServer");
Object server = ReflectionUtil.invokeStatic(serverClazz, "getServer");
Class<?> pingClazz = ReflectionUtil.nms("ServerPing");
Object ping = null;
// Search for ping method
for (Field f : serverClazz.getDeclaredFields()) {
if (f.getType() != null) {
if (f.getType().getSimpleName().equals("ServerPing")) {
f.setAccessible(true);
ping = f.get(server);
}
}
}
if (ping != null) {
Object serverData = null;
for (Field f : pingClazz.getDeclaredFields()) {
if (f.getType() != null) {
if (f.getType().getSimpleName().endsWith("ServerData")) {
f.setAccessible(true);
serverData = f.get(ping);
}
}
}
if (serverData != null) {
int protocolVersion = -1;
for (Field f : serverData.getClass().getDeclaredFields()) {
if (f.getType() != null) {
if (f.getType() == int.class) {
f.setAccessible(true);
protocolVersion = (int) f.get(serverData);
}
}
}
if (protocolVersion != -1) {
ProtocolRegistry.SERVER_PROTOCOL = protocolVersion;
return;
}
}
}
} catch (Exception e) {
e.printStackTrace();
// We couldn't work it out... We'll just use ping and hope for the best...
}
}
public void generateConfig() {
File file = new File(getDataFolder(), "config.yml");
if (file.exists()) {
// Update config options
Configuration oldConfig = new Configuration(file);
oldConfig.reload(false); // Load current options from config
file.delete(); // Delete old config
saveDefaultConfig(); // Generate new config
Configuration newConfig = new Configuration(file);
newConfig.reload(true); // Load default options
for (String key : oldConfig.getKeys(false)) {
// Set option in new config if exists
if (newConfig.contains(key)) {
newConfig.set(key, oldConfig.get(key));
}
}
newConfig.save();
} else {
saveDefaultConfig();
}
}
public void injectPacketHandler() {
try {
Class<?> serverClazz = ReflectionUtil.nms("MinecraftServer");
Object server = ReflectionUtil.invokeStatic(serverClazz, "getServer");
Object connection = null;
for (Method m : serverClazz.getDeclaredMethods()) {
if (m.getReturnType() != null) {
if (m.getReturnType().getSimpleName().equals("ServerConnection")) {
if (m.getParameterTypes().length == 0) {
connection = m.invoke(server);
}
}
}
}
if (connection == null) {
getLogger().warning("We failed to find the ServerConnection? :( What server are you running?");
return;
}
for (Field field : connection.getClass().getDeclaredFields()) {
field.setAccessible(true);
final Object value = field.get(connection);
if (value instanceof List) {
// Inject the list
List wrapper = new ListWrapper((List) value) {
@Override
public synchronized void handleAdd(Object o) {
synchronized (this) {
if (o instanceof ChannelFuture) {
inject((ChannelFuture) o);
}
}
}
};
injectedLists.add(new Pair<>(field, connection));
field.set(connection, wrapper);
// Iterate through current list
synchronized (wrapper) {
for (Object o : (List) value) {
if (o instanceof ChannelFuture) {
inject((ChannelFuture) o);
} else {
break; // not the right list.
}
}
}
}
}
System.setProperty("ViaVersion", getDescription().getVersion());
} catch (Exception e) {
getLogger().severe("Unable to inject handlers, are you on 1.8? ");
e.printStackTrace();
}
}
private void inject(ChannelFuture future) {
try {
ChannelHandler bootstrapAcceptor = future.channel().pipeline().first();
try {
ChannelInitializer<SocketChannel> oldInit = ReflectionUtil.get(bootstrapAcceptor, "childHandler", ChannelInitializer.class);
ChannelInitializer newInit = new ViaVersionInitializer(oldInit);
ReflectionUtil.set(bootstrapAcceptor, "childHandler", newInit);
injectedFutures.add(future);
} catch (NoSuchFieldException e) {
// field not found
throw new Exception("Unable to find childHandler, blame " + bootstrapAcceptor.getClass().getName());
}
} catch (Exception e) {
getLogger().severe("Have you got late-bind enabled with something else? (ProtocolLib?)");
e.printStackTrace();
}
}
private void uninject() {
// TODO: Uninject from players currently online to prevent protocol lib issues.
for (ChannelFuture future : injectedFutures) {
ChannelHandler bootstrapAcceptor = future.channel().pipeline().first();
try {
ChannelInitializer<SocketChannel> oldInit = ReflectionUtil.get(bootstrapAcceptor, "childHandler", ChannelInitializer.class);
if (oldInit instanceof ViaVersionInitializer) {
ReflectionUtil.set(bootstrapAcceptor, "childHandler", ((ViaVersionInitializer) oldInit).getOriginal());
}
} catch (Exception e) {
System.out.println("Failed to remove injection... reload won't work with connections sorry");
}
}
injectedFutures.clear();
for (Pair<Field, Object> pair : injectedLists) {
try {
Object o = pair.getKey().get(pair.getValue());
if (o instanceof ListWrapper) {
pair.getKey().set(pair.getValue(), ((ListWrapper) o).getOriginalList());
}
} catch (IllegalAccessException e) {
System.out.println("Failed to remove injection... reload might not work with connections sorry");
}
}
injectedLists.clear();
}
@Override
public boolean isPorted(Player player) {
return isPorted(player.getUniqueId());
}
@Override
public int getPlayerVersion(@NonNull Player player) {
if (!isPorted(player))
return ProtocolRegistry.SERVER_PROTOCOL;
return portedPlayers.get(player.getUniqueId()).get(ProtocolInfo.class).getProtocolVersion();
}
@Override
public int getPlayerVersion(@NonNull UUID uuid) {
if (!isPorted(uuid))
return ProtocolRegistry.SERVER_PROTOCOL;
return portedPlayers.get(uuid).get(ProtocolInfo.class).getProtocolVersion();
}
@Override
public boolean isPorted(UUID playerUUID) {
return portedPlayers.containsKey(playerUUID);
}
@Override
public String getVersion() {
return getDescription().getVersion();
}
public UserConnection getConnection(UUID playerUUID) {
return portedPlayers.get(playerUUID);
}
public UserConnection getConnection(Player player) {
return portedPlayers.get(player.getUniqueId());
}
public void sendRawPacket(Player player, ByteBuf packet) throws IllegalArgumentException {
sendRawPacket(player.getUniqueId(), packet);
}
@Override
public void sendRawPacket(UUID uuid, ByteBuf packet) throws IllegalArgumentException {
if (!isPorted(uuid)) throw new IllegalArgumentException("This player is not controlled by ViaVersion!");
UserConnection ci = portedPlayers.get(uuid);
ci.sendRawPacket(packet);
}
@Override
public BossBar createBossBar(String title, BossColor color, BossStyle style) {
return new ViaBossBar(title, 1F, color, style);
}
@Override
public BossBar createBossBar(String title, float health, BossColor color, BossStyle style) {
return new ViaBossBar(title, health, color, style);
}
@Override
public boolean isDebug() {
return this.debug;
}
public void setDebug(boolean value) {
this.debug = value;
}
@Override
public ViaVersionCommand getCommandHandler() {
return commandHandler;
}
public boolean isCheckForUpdates() {
return getConfig().getBoolean("checkforupdates", true);
}
public boolean isPreventCollision() {
return getConfig().getBoolean("prevent-collision", true);
}
public boolean isNewEffectIndicator() {
return getConfig().getBoolean("use-new-effect-indicator", true);
}
@Override
public boolean isShowNewDeathMessages() {
return getConfig().getBoolean("use-new-deathmessages", false);
}
public boolean isSuppressMetadataErrors() {
return getConfig().getBoolean("suppress-metadata-errors", false);
}
public boolean isShieldBlocking() {
return getConfig().getBoolean("shield-blocking", true);
}
public boolean isHologramPatch() {
return getConfig().getBoolean("hologram-patch", false);
}
public boolean isBossbarPatch() {
return getConfig().getBoolean("bossbar-patch", true);
}
public boolean isBossbarAntiflicker() {
return getConfig().getBoolean("bossbar-anti-flicker", false);
}
public boolean isUnknownEntitiesSuppressed() {
return getConfig().getBoolean("suppress-entityid-errors", false);
}
public double getHologramYOffset() {
return getConfig().getDouble("hologram-y", -1D);
}
public boolean isBlockBreakPatch() {
return getConfig().getBoolean("block-break-patch", true);
}
@Override
public int getMaxPPS() {
return getConfig().getInt("max-pps", 140);
}
@Override
public String getMaxPPSKickMessage() {
return getConfig().getString("max-pps-kick-msg", "Sending packets too fast? lag?");
}
@Override
public int getTrackingPeriod() {
return getConfig().getInt("tracking-period", 6);
}
@Override
public int getWarningPPS() {
return getConfig().getInt("tracking-warning-pps", 120);
}
@Override
public int getMaxWarnings() {
return getConfig().getInt("tracking-max-warnings", 3);
}
@Override
public String getMaxWarningsKickMessage() {
return getConfig().getString("tracking-max-kick-msg", "You are sending too many packets, :(");
}
public boolean isAutoTeam() {
// Collision has to be enabled first
return isPreventCollision() && getConfig().getBoolean("auto-team", true);
}
public void addPortedClient(UserConnection info) {
portedPlayers.put(info.get(ProtocolInfo.class).getUuid(), info);
}
public void removePortedClient(UUID clientID) {
portedPlayers.remove(clientID);
}
public void run(final Runnable runnable, boolean wait) {
try {
Future f = Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
runnable.run();
return true;
}
});
if (wait) {
f.get(10, TimeUnit.SECONDS);
}
} catch (Exception e) {
System.out.println("Failed to run task: " + e.getClass().getName());
if (ViaVersion.getInstance().isDebug())
e.printStackTrace();
}
}
public Map<UUID, UserConnection> getPortedPlayers() {
return portedPlayers;
}
public boolean handlePPS(UserConnection info) {
// Max PPS Checker
if (getMaxPPS() > 0) {
if (info.getPacketsPerSecond() >= getMaxPPS()) {
info.disconnect(getMaxPPSKickMessage());
return true; // don't send current packet
}
}
// Tracking PPS Checker
if (getMaxWarnings() > 0 && getTrackingPeriod() > 0) {
if (info.getSecondsObserved() > getTrackingPeriod()) {
// Reset
info.setWarnings(0);
info.setSecondsObserved(1);
} else {
info.setSecondsObserved(info.getSecondsObserved() + 1);
if (info.getPacketsPerSecond() >= getWarningPPS()) {
info.setWarnings(info.getWarnings() + 1);
}
if (info.getWarnings() >= getMaxWarnings()) {
info.disconnect(getMaxWarningsKickMessage());
return true; // don't send current packet
}
}
}
return false;
}
} |
/**
* Abstract Syntax Tree for JUnit.
*
* <pre>
* CompilationUnit ::= ClassDecl
*
* ClassDecl ::= TestMethod*
*
* TestMethod ::= Binding* ActionStatement* TestStateMent* ActionStatement*
*
* Binding ::= Expr
*
* Expr ::= QuotedExpr | StubExpr
*
* StubExpr ::= QuotedExpr StubBehavior
* StubBehavior ::= MethodPattern Expr
* MethodPattern ::= Type*
* Type ::= NonArrayType
* NonArrayType ::= PrimitiveType | ClassType
* PrimitiveType ::= Kind
*
* ActionStatement ::= QuotedExpr
*
* TestStatement ::= IsStatement
* | IsNotStatement
* | ThrowsStatement
*
* IsStatement ::= QuotedExpr QuotedExpr
* IsNotStatement ::= QuotedExpr QuotedExpr
* ThrowsStatement ::= QuotedExpr QuotedExpr
*
* </pre>
*
*/
package yokohama.unit.ast_junit; |
package views;
import java.util.ArrayList;
import java.util.Stack;
import controllers.GroupController;
import utlils.Console;
import models.Group;
import models.User;
public class GroupView implements View{
private boolean done;
private Group group;
private final static int WIDTH = 60;
public GroupView(int groupId){
done = false;
System.out.println("hey hey");
group = GroupController.getGroup(groupId);
System.out.println("laget");
}
@Override
public boolean isDone() {
return done;
}
@Override
public void setUnDone() {
this.done = false;
}
@Override
public String getTitle() {
return group.getName();
}
@Override
public ArrayList<String> getContent() {
ArrayList<String> content = new ArrayList<String>();
content.add(Console.tableHead(group.getName(), WIDTH));
if (group.getMasterGruppe() != null) {
content.add(Console.tableRow("Mastergruppe: " + group.getMasterGruppe().getName(), WIDTH));
content.add("+" + Console.charLine('-', WIDTH - 2) + "+");
}
content.add("| " + Console.matchLength("NAVN", 38) + " " + Console.matchLength("ROLLE", 18) + "|");
content.add("+" + Console.charLine('-', WIDTH - 2) + "+");
for (User user : group.getMembers()) {
content.add("| " + Console.matchLength(user.getName(), 38) + " " + Console.matchLength(user.getRole(), 18) + "|");
}
content.add("+" + Console.charLine('-', WIDTH - 2) + "+");
return content;
}
@Override
public String getQuery() {
return "Trykk enter for å gå tilbake. Skriv 'tools' for å komme til verktøymeny";
}
@Override
public void giveInput(String input, Stack<View> viewStack) {
if(input.length() ==0){
this.done = true;
return;
}
if(input.equals("tools")){
viewStack.add(new GroupToolMenuView(this.group));
return;
}
}
} |
package bisq.core.app;
import bisq.core.account.sign.SignedWitness;
import bisq.core.account.sign.SignedWitnessService;
import bisq.core.account.witness.AccountAgeWitnessService;
import bisq.core.alert.Alert;
import bisq.core.alert.AlertManager;
import bisq.core.alert.PrivateNotificationManager;
import bisq.core.alert.PrivateNotificationPayload;
import bisq.core.btc.Balances;
import bisq.core.btc.model.AddressEntry;
import bisq.core.btc.setup.WalletsSetup;
import bisq.core.btc.wallet.BtcWalletService;
import bisq.core.btc.wallet.WalletsManager;
import bisq.core.dao.DaoSetup;
import bisq.core.dao.governance.asset.AssetService;
import bisq.core.dao.governance.voteresult.VoteResultException;
import bisq.core.dao.governance.voteresult.VoteResultService;
import bisq.core.filter.FilterManager;
import bisq.core.locale.Res;
import bisq.core.notifications.MobileNotificationService;
import bisq.core.notifications.alerts.DisputeMsgEvents;
import bisq.core.notifications.alerts.MyOfferTakenEvents;
import bisq.core.notifications.alerts.TradeEvents;
import bisq.core.notifications.alerts.market.MarketAlerts;
import bisq.core.notifications.alerts.price.PriceAlert;
import bisq.core.offer.OpenOfferManager;
import bisq.core.payment.PaymentAccount;
import bisq.core.payment.TradeLimits;
import bisq.core.payment.payload.PaymentMethod;
import bisq.core.provider.fee.FeeService;
import bisq.core.provider.price.PriceFeedService;
import bisq.core.support.dispute.arbitration.ArbitrationManager;
import bisq.core.support.dispute.arbitration.arbitrator.ArbitratorManager;
import bisq.core.support.dispute.mediation.MediationManager;
import bisq.core.support.dispute.mediation.mediator.MediatorManager;
import bisq.core.support.dispute.refund.RefundManager;
import bisq.core.support.dispute.refund.refundagent.RefundAgentManager;
import bisq.core.support.traderchat.TraderChatManager;
import bisq.core.trade.TradeManager;
import bisq.core.trade.TradeTxException;
import bisq.core.trade.statistics.AssetTradeActivityCheck;
import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.core.user.Preferences;
import bisq.core.user.User;
import bisq.core.util.FormattingUtils;
import bisq.core.util.coin.CoinFormatter;
import bisq.network.crypto.DecryptedDataTuple;
import bisq.network.crypto.EncryptionService;
import bisq.network.p2p.P2PService;
import bisq.network.p2p.peers.keepalive.messages.Ping;
import bisq.network.p2p.storage.payload.PersistableNetworkPayload;
import bisq.common.ClockWatcher;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.app.DevEnv;
import bisq.common.app.Log;
import bisq.common.crypto.CryptoException;
import bisq.common.crypto.KeyRing;
import bisq.common.crypto.SealedAndSigned;
import bisq.common.proto.ProtobufferException;
import bisq.common.util.Utilities;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.RejectMessage;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import com.google.common.net.InetAddresses;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.monadic.MonadicBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.ListChangeListener;
import javafx.collections.SetChangeListener;
import org.spongycastle.crypto.params.KeyParameter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import ch.qos.logback.classic.Level;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
@Slf4j
@Singleton
public class BisqSetup {
public interface BisqSetupListener {
default void onInitP2pNetwork() {
log.info("onInitP2pNetwork");
}
default void onInitWallet() {
log.info("onInitWallet");
}
default void onRequestWalletPassword() {
log.info("onRequestWalletPassword");
}
void onSetupComplete();
}
private static final long STARTUP_TIMEOUT_MINUTES = 4;
private final P2PNetworkSetup p2PNetworkSetup;
private final WalletAppSetup walletAppSetup;
private final WalletsManager walletsManager;
private final WalletsSetup walletsSetup;
private final BtcWalletService btcWalletService;
private final Balances balances;
private final PriceFeedService priceFeedService;
private final ArbitratorManager arbitratorManager;
private final MediatorManager mediatorManager;
private final RefundAgentManager refundAgentManager;
private final P2PService p2PService;
private final TradeManager tradeManager;
private final OpenOfferManager openOfferManager;
private final ArbitrationManager arbitrationManager;
private final MediationManager mediationManager;
private final RefundManager refundManager;
private final TraderChatManager traderChatManager;
private final Preferences preferences;
private final User user;
private final AlertManager alertManager;
private final PrivateNotificationManager privateNotificationManager;
private final FilterManager filterManager;
private final TradeStatisticsManager tradeStatisticsManager;
private final ClockWatcher clockWatcher;
private final FeeService feeService;
private final DaoSetup daoSetup;
private final EncryptionService encryptionService;
private final KeyRing keyRing;
private final BisqEnvironment bisqEnvironment;
private final AccountAgeWitnessService accountAgeWitnessService;
private final SignedWitnessService signedWitnessService;
private final MobileNotificationService mobileNotificationService;
private final MyOfferTakenEvents myOfferTakenEvents;
private final TradeEvents tradeEvents;
private final DisputeMsgEvents disputeMsgEvents;
private final PriceAlert priceAlert;
private final MarketAlerts marketAlerts;
private final VoteResultService voteResultService;
private final AssetTradeActivityCheck tradeActivityCheck;
private final AssetService assetService;
private final TorSetup torSetup;
private final TradeLimits tradeLimits;
private final CoinFormatter formatter;
@Setter
@Nullable
private Consumer<Runnable> displayTacHandler;
@Setter
@Nullable
private Consumer<String> cryptoSetupFailedHandler, chainFileLockedExceptionHandler,
spvFileCorruptedHandler, lockedUpFundsHandler, daoErrorMessageHandler, daoWarnMessageHandler,
filterWarningHandler, displaySecurityRecommendationHandler, displayLocalhostHandler,
wrongOSArchitectureHandler, displaySignedByArbitratorHandler,
displaySignedByPeerHandler, displayPeerLimitLiftedHandler, displayPeerSignerHandler,
rejectedTxErrorMessageHandler;
@Setter
@Nullable
private Consumer<Boolean> displayTorNetworkSettingsHandler;
@Setter
@Nullable
private Runnable showFirstPopupIfResyncSPVRequestedHandler;
@Setter
@Nullable
private Consumer<Consumer<KeyParameter>> requestWalletPasswordHandler;
@Setter
@Nullable
private Consumer<Alert> displayAlertHandler;
@Setter
@Nullable
private BiConsumer<Alert, String> displayUpdateHandler;
@Setter
@Nullable
private Consumer<VoteResultException> voteResultExceptionHandler;
@Setter
@Nullable
private Consumer<PrivateNotificationPayload> displayPrivateNotificationHandler;
@Getter
final BooleanProperty newVersionAvailableProperty = new SimpleBooleanProperty(false);
private BooleanProperty p2pNetworkReady;
private final BooleanProperty walletInitialized = new SimpleBooleanProperty();
private boolean allBasicServicesInitialized;
@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<Boolean> p2pNetworkAndWalletInitialized;
private List<BisqSetupListener> bisqSetupListeners = new ArrayList<>();
@Inject
public BisqSetup(P2PNetworkSetup p2PNetworkSetup,
WalletAppSetup walletAppSetup,
WalletsManager walletsManager,
WalletsSetup walletsSetup,
BtcWalletService btcWalletService,
Balances balances,
PriceFeedService priceFeedService,
ArbitratorManager arbitratorManager,
MediatorManager mediatorManager,
RefundAgentManager refundAgentManager,
P2PService p2PService,
TradeManager tradeManager,
OpenOfferManager openOfferManager,
ArbitrationManager arbitrationManager,
MediationManager mediationManager,
RefundManager refundManager,
TraderChatManager traderChatManager,
Preferences preferences,
User user,
AlertManager alertManager,
PrivateNotificationManager privateNotificationManager,
FilterManager filterManager,
TradeStatisticsManager tradeStatisticsManager,
ClockWatcher clockWatcher,
FeeService feeService,
DaoSetup daoSetup,
EncryptionService encryptionService,
KeyRing keyRing,
BisqEnvironment bisqEnvironment,
AccountAgeWitnessService accountAgeWitnessService,
SignedWitnessService signedWitnessService,
MobileNotificationService mobileNotificationService,
MyOfferTakenEvents myOfferTakenEvents,
TradeEvents tradeEvents,
DisputeMsgEvents disputeMsgEvents,
PriceAlert priceAlert,
MarketAlerts marketAlerts,
VoteResultService voteResultService,
AssetTradeActivityCheck tradeActivityCheck,
AssetService assetService,
TorSetup torSetup,
TradeLimits tradeLimits,
@Named(FormattingUtils.BTC_FORMATTER_KEY) CoinFormatter formatter) {
this.p2PNetworkSetup = p2PNetworkSetup;
this.walletAppSetup = walletAppSetup;
this.walletsManager = walletsManager;
this.walletsSetup = walletsSetup;
this.btcWalletService = btcWalletService;
this.balances = balances;
this.priceFeedService = priceFeedService;
this.arbitratorManager = arbitratorManager;
this.mediatorManager = mediatorManager;
this.refundAgentManager = refundAgentManager;
this.p2PService = p2PService;
this.tradeManager = tradeManager;
this.openOfferManager = openOfferManager;
this.arbitrationManager = arbitrationManager;
this.mediationManager = mediationManager;
this.refundManager = refundManager;
this.traderChatManager = traderChatManager;
this.preferences = preferences;
this.user = user;
this.alertManager = alertManager;
this.privateNotificationManager = privateNotificationManager;
this.filterManager = filterManager;
this.tradeStatisticsManager = tradeStatisticsManager;
this.clockWatcher = clockWatcher;
this.feeService = feeService;
this.daoSetup = daoSetup;
this.encryptionService = encryptionService;
this.keyRing = keyRing;
this.bisqEnvironment = bisqEnvironment;
this.accountAgeWitnessService = accountAgeWitnessService;
this.signedWitnessService = signedWitnessService;
this.mobileNotificationService = mobileNotificationService;
this.myOfferTakenEvents = myOfferTakenEvents;
this.tradeEvents = tradeEvents;
this.disputeMsgEvents = disputeMsgEvents;
this.priceAlert = priceAlert;
this.marketAlerts = marketAlerts;
this.voteResultService = voteResultService;
this.tradeActivityCheck = tradeActivityCheck;
this.assetService = assetService;
this.torSetup = torSetup;
this.tradeLimits = tradeLimits;
this.formatter = formatter;
}
// Setup
public void addBisqSetupListener(BisqSetupListener listener) {
bisqSetupListeners.add(listener);
}
public void start() {
UserThread.runPeriodically(() -> {
}, 1);
maybeReSyncSPVChain();
maybeShowTac();
}
private void step2() {
checkIfLocalHostNodeIsRunning();
}
private void step3() {
torSetup.cleanupTorFiles();
readMapsFromResources();
checkCryptoSetup();
checkForCorrectOSArchitecture();
}
private void step4() {
startP2pNetworkAndWallet();
}
private void step5() {
initDomainServices();
bisqSetupListeners.forEach(BisqSetupListener::onSetupComplete);
// We set that after calling the setupCompleteHandler to not trigger a popup from the dev dummy accounts
// in MainViewModel
maybeShowSecurityRecommendation();
maybeShowLocalhostRunningInfo();
maybeShowAccountSigningStateInfo();
}
// API
public void displayAlertIfPresent(Alert alert, boolean openNewVersionPopup) {
if (alert != null) {
if (alert.isUpdateInfo()) {
user.setDisplayedAlert(alert);
final boolean isNewVersion = alert.isNewVersion();
newVersionAvailableProperty.set(isNewVersion);
String key = "Update_" + alert.getVersion();
if (isNewVersion && (preferences.showAgain(key) || openNewVersionPopup) && displayUpdateHandler != null) {
displayUpdateHandler.accept(alert, key);
}
} else {
final Alert displayedAlert = user.getDisplayedAlert();
if ((displayedAlert == null || !displayedAlert.equals(alert)) && displayAlertHandler != null)
displayAlertHandler.accept(alert);
}
}
}
// Getters
// Wallet
public StringProperty getBtcInfo() {
return walletAppSetup.getBtcInfo();
}
public DoubleProperty getBtcSyncProgress() {
return walletAppSetup.getBtcSyncProgress();
}
public StringProperty getWalletServiceErrorMsg() {
return walletAppSetup.getWalletServiceErrorMsg();
}
public StringProperty getBtcSplashSyncIconId() {
return walletAppSetup.getBtcSplashSyncIconId();
}
public BooleanProperty getUseTorForBTC() {
return walletAppSetup.getUseTorForBTC();
}
// P2P
public StringProperty getP2PNetworkInfo() {
return p2PNetworkSetup.getP2PNetworkInfo();
}
public BooleanProperty getSplashP2PNetworkAnimationVisible() {
return p2PNetworkSetup.getSplashP2PNetworkAnimationVisible();
}
public StringProperty getP2pNetworkWarnMsg() {
return p2PNetworkSetup.getP2pNetworkWarnMsg();
}
public StringProperty getP2PNetworkIconId() {
return p2PNetworkSetup.getP2PNetworkIconId();
}
public BooleanProperty getUpdatedDataReceived() {
return p2PNetworkSetup.getUpdatedDataReceived();
}
public StringProperty getP2pNetworkLabelId() {
return p2PNetworkSetup.getP2pNetworkLabelId();
}
// Private
private void maybeReSyncSPVChain() {
// We do the delete of the spv file at startup before BitcoinJ is initialized to avoid issues with locked files under Windows.
if (preferences.isResyncSpvRequested()) {
try {
walletsSetup.reSyncSPVChain();
} catch (IOException e) {
log.error(e.toString());
e.printStackTrace();
}
}
}
private void maybeShowTac() {
if (!preferences.isTacAcceptedV120() && !DevEnv.isDevMode()) {
if (displayTacHandler != null)
displayTacHandler.accept(() -> {
preferences.setTacAcceptedV120(true);
step2();
});
} else {
step2();
}
}
private void checkIfLocalHostNodeIsRunning() {
// For DAO testnet we ignore local btc node
if (BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ||
BisqEnvironment.getBaseCurrencyNetwork().isDaoTestNet() ||
bisqEnvironment.isIgnoreLocalBtcNode()) {
step3();
} else {
new Thread(() -> {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"),
BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000);
log.info("Localhost Bitcoin node detected.");
UserThread.execute(() -> {
bisqEnvironment.setBitcoinLocalhostNodeRunning(true);
step3();
});
} catch (Throwable e) {
UserThread.execute(BisqSetup.this::step3);
}
}, "checkIfLocalHostNodeIsRunningThread").start();
}
}
private void readMapsFromResources() {
SetupUtils.readFromResources(p2PService.getP2PDataStorage()).addListener((observable, oldValue, newValue) -> {
if (newValue)
step4();
});
}
private void checkCryptoSetup() {
// We want to test if the client is compiled with the correct crypto provider (BountyCastle)
// and if the unlimited Strength for cryptographic keys is set.
// If users compile themselves they might miss that step and then would get an exception in the trade.
// To avoid that we add a sample encryption and signing here at startup to see if it doesn't cause an exception.
// See: https://github.com/bisq-network/exchange/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys
new Thread(() -> {
try {
// just use any simple dummy msg
Ping payload = new Ping(1, 1);
SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload,
keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
DecryptedDataTuple tuple = encryptionService.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate());
if (tuple.getNetworkEnvelope() instanceof Ping &&
((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() &&
((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) {
log.debug("Crypto test succeeded");
} else {
throw new CryptoException("Payload not correct after decryption");
}
} catch (CryptoException | ProtobufferException e) {
e.printStackTrace();
String msg = Res.get("popup.warning.cryptoTestFailed", e.getMessage());
log.error(msg);
if (cryptoSetupFailedHandler != null)
cryptoSetupFailedHandler.accept(msg);
}
}, "checkCryptoThread").start();
}
private void startP2pNetworkAndWallet() {
ChangeListener<Boolean> walletInitializedListener = (observable, oldValue, newValue) -> {
// TODO that seems to be called too often if Tor takes longer to start up...
if (newValue && !p2pNetworkReady.get() && displayTorNetworkSettingsHandler != null)
displayTorNetworkSettingsHandler.accept(true);
};
Timer startupTimeout = UserThread.runAfter(() -> {
if (p2PNetworkSetup.p2pNetworkFailed.get()) {
// Skip this timeout action if the p2p network setup failed
// since a p2p network error prompt will be shown containing the error message
return;
}
log.warn("startupTimeout called");
if (walletsManager.areWalletsEncrypted())
walletInitialized.addListener(walletInitializedListener);
else if (displayTorNetworkSettingsHandler != null)
displayTorNetworkSettingsHandler.accept(true);
log.info("Set log level for org.berndpruenster.netlayer classes to DEBUG to show more details for " +
"Tor network connection issues");
Log.setCustomLogLevel("org.berndpruenster.netlayer", Level.DEBUG);
}, STARTUP_TIMEOUT_MINUTES, TimeUnit.MINUTES);
bisqSetupListeners.forEach(BisqSetupListener::onInitP2pNetwork);
p2pNetworkReady = p2PNetworkSetup.init(this::initWallet, displayTorNetworkSettingsHandler);
// We only init wallet service here if not using Tor for bitcoinj.
// When using Tor, wallet init must be deferred until Tor is ready.
if (!preferences.getUseTorForBitcoinJ() || bisqEnvironment.isBitcoinLocalhostNodeRunning()) {
initWallet();
}
// need to store it to not get garbage collected
p2pNetworkAndWalletInitialized = EasyBind.combine(walletInitialized, p2pNetworkReady,
(a, b) -> {
log.info("walletInitialized={}, p2pNetWorkReady={}", a, b);
return a && b;
});
p2pNetworkAndWalletInitialized.subscribe((observable, oldValue, newValue) -> {
if (newValue) {
startupTimeout.stop();
walletInitialized.removeListener(walletInitializedListener);
if (displayTorNetworkSettingsHandler != null)
displayTorNetworkSettingsHandler.accept(false);
step5();
}
});
}
private void initWallet() {
bisqSetupListeners.forEach(BisqSetupListener::onInitWallet);
Runnable walletPasswordHandler = () -> {
log.info("Wallet password required");
bisqSetupListeners.forEach(BisqSetupListener::onRequestWalletPassword);
if (p2pNetworkReady.get())
p2PNetworkSetup.setSplashP2PNetworkAnimationVisible(true);
if (requestWalletPasswordHandler != null) {
requestWalletPasswordHandler.accept(aesKey -> {
walletsManager.setAesKey(aesKey);
if (preferences.isResyncSpvRequested()) {
if (showFirstPopupIfResyncSPVRequestedHandler != null)
showFirstPopupIfResyncSPVRequestedHandler.run();
} else {
// TODO no guarantee here that the wallet is really fully initialized
// We would need a new walletInitializedButNotEncrypted state to track
// Usually init is fast and we have our wallet initialized at that state though.
walletInitialized.set(true);
}
});
}
};
walletAppSetup.init(chainFileLockedExceptionHandler,
spvFileCorruptedHandler,
showFirstPopupIfResyncSPVRequestedHandler,
walletPasswordHandler,
() -> {
if (allBasicServicesInitialized) {
checkForLockedUpFunds();
checkForInvalidMakerFeeTxs();
}
},
() -> walletInitialized.set(true));
}
private void checkForLockedUpFunds() {
// We check if there are locked up funds in failed or closed trades
try {
Set<String> setOfAllTradeIds = tradeManager.getSetOfFailedOrClosedTradeIdsFromLockedInFunds();
btcWalletService.getAddressEntriesForTrade().stream()
.filter(e -> setOfAllTradeIds.contains(e.getOfferId()) &&
e.getContext() == AddressEntry.Context.MULTI_SIG)
.forEach(e -> {
Coin balance = e.getCoinLockedInMultiSig();
if (balance.isPositive()) {
String message = Res.get("popup.warning.lockedUpFunds",
formatter.formatCoinWithCode(balance), e.getAddressString(), e.getOfferId());
log.warn(message);
if (lockedUpFundsHandler != null) {
lockedUpFundsHandler.accept(message);
}
}
});
} catch (TradeTxException e) {
log.warn(e.getMessage());
if (lockedUpFundsHandler != null) {
lockedUpFundsHandler.accept(e.getMessage());
}
}
}
private void checkForInvalidMakerFeeTxs() {
// We check if we have open offers with no confidence object at the maker fee tx. That can happen if the
// miner fee was too low and the transaction got removed from mempool and got out from our wallet after a
// resync.
openOfferManager.getObservableList().forEach(e -> {
String offerFeePaymentTxId = e.getOffer().getOfferFeePaymentTxId();
if (btcWalletService.getConfidenceForTxId(offerFeePaymentTxId) == null) {
String message = Res.get("popup.warning.openOfferWithInvalidMakerFeeTx",
e.getOffer().getShortId(), offerFeePaymentTxId);
log.warn(message);
if (lockedUpFundsHandler != null) {
lockedUpFundsHandler.accept(message);
}
}
});
}
private void checkForCorrectOSArchitecture() {
if (!Utilities.isCorrectOSArchitecture() && wrongOSArchitectureHandler != null) {
String osArchitecture = Utilities.getOSArchitecture();
// We don't force a shutdown as the osArchitecture might in strange cases return a wrong value.
// Needs at least more testing on different machines...
wrongOSArchitectureHandler.accept(Res.get("popup.warning.wrongVersion",
osArchitecture,
Utilities.getJVMArchitecture(),
osArchitecture));
}
}
private void initDomainServices() {
log.info("initDomainServices");
clockWatcher.start();
tradeLimits.onAllServicesInitialized();
arbitrationManager.onAllServicesInitialized();
mediationManager.onAllServicesInitialized();
refundManager.onAllServicesInitialized();
traderChatManager.onAllServicesInitialized();
tradeManager.onAllServicesInitialized();
if (walletsSetup.downloadPercentageProperty().get() == 1) {
checkForLockedUpFunds();
checkForInvalidMakerFeeTxs();
}
openOfferManager.onAllServicesInitialized();
balances.onAllServicesInitialized();
walletAppSetup.getRejectedTxException().addListener((observable, oldValue, newValue) -> {
if (newValue == null || newValue.getTxId() == null) {
return;
}
RejectMessage rejectMessage = newValue.getRejectMessage();
log.warn("We received reject message: {}", rejectMessage);
// TODO: Find out which reject messages are critical and which not.
// We got a report where a "tx already known" message caused a failed trade but the deposit tx was valid.
// To avoid such false positives we only handle reject messages which we consider clearly critical.
switch (rejectMessage.getReasonCode()) {
case OBSOLETE:
case DUPLICATE:
case NONSTANDARD:
case CHECKPOINT:
case OTHER:
// We ignore those cases to avoid that not critical reject messages trigger a failed trade.
log.warn("We ignore that reject message as it is likely not critical.");
break;
case MALFORMED:
case INVALID:
case DUST:
case INSUFFICIENTFEE:
// We delay as we might get the rejected tx error before we have completed the create offer protocol
log.warn("We handle that reject message as it is likely critical.");
UserThread.runAfter(() -> {
String txId = newValue.getTxId();
openOfferManager.getObservableList().stream()
.filter(openOffer -> txId.equals(openOffer.getOffer().getOfferFeePaymentTxId()))
.forEach(openOffer -> {
// We delay to avoid concurrent modification exceptions
UserThread.runAfter(() -> {
openOffer.getOffer().setErrorMessage(newValue.getMessage());
if (rejectedTxErrorMessageHandler != null) {
rejectedTxErrorMessageHandler.accept(Res.get("popup.warning.openOffer.makerFeeTxRejected", openOffer.getId(), txId));
}
openOfferManager.removeOpenOffer(openOffer, () -> {
log.warn("We removed an open offer because the maker fee was rejected by the Bitcoin " +
"network. OfferId={}, txId={}", openOffer.getShortId(), txId);
}, log::warn);
}, 1);
});
tradeManager.getTradableList().stream()
.filter(trade -> trade.getOffer() != null)
.forEach(trade -> {
String details = null;
if (txId.equals(trade.getDepositTxId())) {
details = Res.get("popup.warning.trade.txRejected.deposit");
}
if (txId.equals(trade.getOffer().getOfferFeePaymentTxId()) || txId.equals(trade.getTakerFeeTxId())) {
details = Res.get("popup.warning.trade.txRejected.tradeFee");
}
if (details != null) {
// We delay to avoid concurrent modification exceptions
String finalDetails = details;
UserThread.runAfter(() -> {
trade.setErrorMessage(newValue.getMessage());
if (rejectedTxErrorMessageHandler != null) {
rejectedTxErrorMessageHandler.accept(Res.get("popup.warning.trade.txRejected",
finalDetails, trade.getShortId(), txId));
}
tradeManager.addTradeToFailedTrades(trade);
}, 1);
}
});
}, 3);
}
});
arbitratorManager.onAllServicesInitialized();
mediatorManager.onAllServicesInitialized();
refundAgentManager.onAllServicesInitialized();
alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) ->
displayAlertIfPresent(newValue, false));
displayAlertIfPresent(alertManager.alertMessageProperty().get(), false);
privateNotificationManager.privateNotificationProperty().addListener((observable, oldValue, newValue) -> {
if (displayPrivateNotificationHandler != null)
displayPrivateNotificationHandler.accept(newValue);
});
p2PService.onAllServicesInitialized();
feeService.onAllServicesInitialized();
if (DevEnv.isDaoActivated()) {
daoSetup.onAllServicesInitialized(errorMessage -> {
if (daoErrorMessageHandler != null)
daoErrorMessageHandler.accept(errorMessage);
}, warningMessage -> {
if (daoWarnMessageHandler != null)
daoWarnMessageHandler.accept(warningMessage);
});
}
tradeStatisticsManager.onAllServicesInitialized();
tradeActivityCheck.onAllServicesInitialized();
assetService.onAllServicesInitialized();
accountAgeWitnessService.onAllServicesInitialized();
signedWitnessService.onAllServicesInitialized();
priceFeedService.setCurrencyCodeOnInit();
filterManager.onAllServicesInitialized();
filterManager.addListener(filter -> {
if (filter != null && filterWarningHandler != null) {
if (filter.getSeedNodes() != null && !filter.getSeedNodes().isEmpty()) {
log.warn(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.seed")));
// Let's keep that more silent. Might be used in case a node is unstable and we don't want to confuse users.
// filterWarningHandler.accept(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.seed")));
}
if (filter.getPriceRelayNodes() != null && !filter.getPriceRelayNodes().isEmpty()) {
log.warn(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.priceRelay")));
// Let's keep that more silent. Might be used in case a node is unstable and we don't want to confuse users.
// filterWarningHandler.accept(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.priceRelay")));
}
if (filterManager.requireUpdateToNewVersionForTrading()) {
filterWarningHandler.accept(Res.get("popup.warning.mandatoryUpdate.trading"));
}
if (filterManager.requireUpdateToNewVersionForDAO()) {
filterWarningHandler.accept(Res.get("popup.warning.mandatoryUpdate.dao"));
}
if (filter.isDisableDao()) {
filterWarningHandler.accept(Res.get("popup.warning.disable.dao"));
}
}
});
voteResultService.getVoteResultExceptions().addListener((ListChangeListener<VoteResultException>) c -> {
c.next();
if (c.wasAdded() && voteResultExceptionHandler != null) {
c.getAddedSubList().forEach(e -> voteResultExceptionHandler.accept(e));
}
});
mobileNotificationService.onAllServicesInitialized();
myOfferTakenEvents.onAllServicesInitialized();
tradeEvents.onAllServicesInitialized();
disputeMsgEvents.onAllServicesInitialized();
priceAlert.onAllServicesInitialized();
marketAlerts.onAllServicesInitialized();
allBasicServicesInitialized = true;
}
private void maybeShowSecurityRecommendation() {
String key = "remindPasswordAndBackup";
user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> {
if (!walletsManager.areWalletsEncrypted() && !user.isPaymentAccountImport() && preferences.showAgain(key) && change.wasAdded() &&
displaySecurityRecommendationHandler != null)
displaySecurityRecommendationHandler.accept(key);
});
}
private void maybeShowLocalhostRunningInfo() {
maybeTriggerDisplayHandler("bitcoinLocalhostNode", displayLocalhostHandler, bisqEnvironment.isBitcoinLocalhostNodeRunning());
}
private void maybeShowAccountSigningStateInfo() {
String keySignedByArbitrator = "accountSignedByArbitrator";
String keySignedByPeer = "accountSignedByPeer";
String keyPeerLimitedLifted = "accountLimitLifted";
String keyPeerSigner = "accountPeerSigner";
// check signed witness on startup
checkSigningState(AccountAgeWitnessService.SignState.ARBITRATOR, keySignedByArbitrator, displaySignedByArbitratorHandler);
checkSigningState(AccountAgeWitnessService.SignState.PEER_INITIAL, keySignedByPeer, displaySignedByPeerHandler);
checkSigningState(AccountAgeWitnessService.SignState.PEER_LIMIT_LIFTED, keyPeerLimitedLifted, displayPeerLimitLiftedHandler);
checkSigningState(AccountAgeWitnessService.SignState.PEER_SIGNER, keyPeerSigner, displayPeerSignerHandler);
// check signed witness during runtime
p2PService.getP2PDataStorage().addAppendOnlyDataStoreListener(
payload -> {
maybeTriggerDisplayHandler(keySignedByArbitrator, displaySignedByArbitratorHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.ARBITRATOR));
maybeTriggerDisplayHandler(keySignedByPeer, displaySignedByPeerHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.PEER_INITIAL));
maybeTriggerDisplayHandler(keyPeerLimitedLifted, displayPeerLimitLiftedHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.PEER_LIMIT_LIFTED));
maybeTriggerDisplayHandler(keyPeerSigner, displayPeerSignerHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.PEER_SIGNER));
});
}
private void checkSigningState(AccountAgeWitnessService.SignState state,
String key, Consumer<String> displayHandler) {
boolean signingStateFound = p2PService.getP2PDataStorage().getAppendOnlyDataStoreMap().values().stream()
.anyMatch(payload -> isSignedWitnessOfMineWithState(payload, state));
maybeTriggerDisplayHandler(key, displayHandler, signingStateFound);
}
private boolean isSignedWitnessOfMineWithState(PersistableNetworkPayload payload,
AccountAgeWitnessService.SignState state) {
if (payload instanceof SignedWitness && user.getPaymentAccounts() != null) {
// We know at this point that it is already added to the signed witness list
// Check if new signed witness is for one of my own accounts
return user.getPaymentAccounts().stream()
.filter(a -> PaymentMethod.hasChargebackRisk(a.getPaymentMethod(), a.getTradeCurrencies()))
.filter(a -> Arrays.equals(((SignedWitness) payload).getAccountAgeWitnessHash(),
accountAgeWitnessService.getMyWitness(a.getPaymentAccountPayload()).getHash()))
.anyMatch(a -> accountAgeWitnessService.getSignState(accountAgeWitnessService.getMyWitness(
a.getPaymentAccountPayload())).equals(state));
}
return false;
}
private void maybeTriggerDisplayHandler(String key, Consumer<String> displayHandler, boolean signingStateFound) {
if (signingStateFound && preferences.showAgain(key) &&
displayHandler != null) {
displayHandler.accept(key);
}
}
} |
package hudson.maven;
import hudson.FilePath;
import hudson.Util;
import hudson.maven.agent.Main;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.DependencyGraph;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.Slave;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.Launcher;
import hudson.remoting.Which;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.tasks.Maven.MavenInstallation;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.ArgumentListBuilder;
import hudson.util.IOException2;
import org.codehaus.classworlds.NoSuchRealmException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
/**
* {@link Run} for {@link MavenModule}.
*
* @author Kohsuke Kawaguchi
*/
public class MavenBuild extends AbstractBuild<MavenModule,MavenBuild> {
/**
* {@link MavenReporter}s that will contribute project actions.
* Can be null if there's none.
*/
/*package*/ List<MavenReporter> projectActionReporters;
public MavenBuild(MavenModule job) throws IOException {
super(job);
}
public MavenBuild(MavenModule job, Calendar timestamp) {
super(job, timestamp);
}
public MavenBuild(MavenModule project, File buildDir) throws IOException {
super(project, buildDir);
}
/**
* Gets the {@link MavenModuleSetBuild} that has the same build number.
*
* @return
* null if no such build exists, which happens when the module build
* is manually triggered.
*/
public MavenModuleSetBuild getParentBuild() {
return getParent().getParent().getBuildByNumber(getNumber());
}
@Override
public ChangeLogSet<? extends Entry> getChangeSet() {
return new FilteredChangeLogSet(this);
}
/**
* We always get the changeset from {@link MavenModuleSetBuild}.
*/
@Override
public boolean hasChangeSetComputed() {
return true;
}
@Override
public AbstractTestResultAction getTestResultAction() {
return getAction(AbstractTestResultAction.class);
}
public void registerAsProjectAction(MavenReporter reporter) {
if(projectActionReporters==null)
projectActionReporters = new ArrayList<MavenReporter>();
projectActionReporters.add(reporter);
}
@Override
public void run() {
run(new RunnerImpl());
getProject().updateTransientActions();
}
/**
* Runs Maven and builds the project.
*
* This code is executed on the remote machine.
*/
private static final class Builder implements Callable<Result,IOException> {
private final BuildListener listener;
private final MavenBuildProxy buildProxy;
private final MavenReporter[] reporters;
private final List<String> goals;
public Builder(BuildListener listener,MavenBuildProxy buildProxy,MavenReporter[] reporters, List<String> goals) {
this.listener = listener;
this.buildProxy = buildProxy;
this.reporters = reporters;
this.goals = goals;
}
public Result call() throws IOException {
try {
int r = Main.launch(goals.toArray(new String[goals.size()]));
return r==0 ? Result.SUCCESS : Result.FAILURE;
} catch (NoSuchMethodException e) {
throw new IOException2(e);
} catch (IllegalAccessException e) {
throw new IOException2(e);
} catch (NoSuchRealmException e) {
throw new IOException2(e);
} catch (InvocationTargetException e) {
throw new IOException2(e);
} catch (ClassNotFoundException e) {
throw new IOException2(e);
}
//MavenProject p=null;
//try {
// MavenEmbedder embedder = MavenUtil.createEmbedder(listener);
// File pom = new File("pom.xml").getAbsoluteFile(); // MavenEmbedder only works if it's absolute
// if(!pom.exists()) {
// listener.error("No POM: "+pom);
// return Result.FAILURE;
// // event monitor is mostly useless. It only provides a few strings
// EventMonitor eventMonitor = new DefaultEventMonitor( new PlexusLoggerAdapter( new EmbedderLoggerImpl(listener) ) );
// p = embedder.readProject(pom);
// PluginManagerInterceptor interceptor;
// try {
// interceptor = (PluginManagerInterceptor)embedder.getContainer().lookup(PluginManager.class.getName());
// interceptor.setBuilder(buildProxy,reporters,listener);
// } catch (ComponentLookupException e) {
// throw new Error(e); // impossible
// for (MavenReporter r : reporters)
// r.preBuild(buildProxy,p,listener);
// embedder.execute(p, goals, eventMonitor,
// new TransferListenerImpl(listener),
// null, // TODO: allow additional properties to be specified
// pom.getParentFile());
// interceptor.fireLeaveModule();
// return null;
//} catch (MavenEmbedderException e) {
// buildProxy.setResult(Result.FAILURE);
// e.printStackTrace(listener.error(e.getMessage()));
//} catch (ProjectBuildingException e) {
// buildProxy.setResult(Result.FAILURE);
// e.printStackTrace(listener.error(e.getMessage()));
//} catch (CycleDetectedException e) {
// buildProxy.setResult(Result.FAILURE);
// e.printStackTrace(listener.error(e.getMessage()));
//} catch (LifecycleExecutionException e) {
// buildProxy.setResult(Result.FAILURE);
// e.printStackTrace(listener.error(e.getMessage()));
//} catch (BuildFailureException e) {
// buildProxy.setResult(Result.FAILURE);
// e.printStackTrace(listener.error(e.getMessage()));
//} catch (DuplicateProjectException e) {
// buildProxy.setResult(Result.FAILURE);
// e.printStackTrace(listener.error(e.getMessage()));
//} catch (AbortException e) {
// listener.error("build aborted");
//} catch (InterruptedException e) {
// listener.error("build aborted");
//} finally {
// // this should happen after a build is marked as a failure
// try {
// if(p!=null)
// for (MavenReporter r : reporters)
// r.postBuild(buildProxy,p,listener);
// } catch (InterruptedException e) {
// buildProxy.setResult(Result.FAILURE);
}
}
/**
* {@link MavenBuildProxy} implementation.
*/
private class ProxyImpl implements MavenBuildProxy, Serializable {
public <V, T extends Throwable> V execute(BuildCallable<V, T> program) throws T, IOException, InterruptedException {
return program.call(MavenBuild.this);
}
public FilePath getRootDir() {
return new FilePath(MavenBuild.this.getRootDir());
}
public FilePath getProjectRootDir() {
return new FilePath(MavenBuild.this.getParent().getRootDir());
}
public FilePath getArtifactsDir() {
return new FilePath(MavenBuild.this.getArtifactsDir());
}
public void setResult(Result result) {
MavenBuild.this.setResult(result);
}
public void registerAsProjectAction(MavenReporter reporter) {
MavenBuild.this.registerAsProjectAction(reporter);
}
private Object writeReplace() {
return Channel.current().export(MavenBuildProxy.class, new ProxyImpl());
}
}
private static final class getJavaExe implements Callable<String,IOException> {
public String call() throws IOException {
return new File(new File(System.getProperty("java.home")),"bin/java").getPath();
}
}
private class RunnerImpl extends AbstractRunner {
protected Result doRun(BuildListener listener) throws Exception {
// pick up a list of reporters to run
List<MavenReporter> reporters = new ArrayList<MavenReporter>();
getProject().getReporters().addAllTo(reporters);
for (MavenReporterDescriptor d : MavenReporters.LIST) {
if(getProject().getReporters().contains(d))
continue; // already configured
MavenReporter auto = d.newAutoInstance(getProject());
if(auto!=null)
reporters.add(auto);
}
// start maven process
ArgumentListBuilder args = buildMavenCmdLine();
Channel channel = launcher.launchChannel(args.toCommandArray(), new String[0],
listener.getLogger(), getProject().getModuleRoot());
// Maven started.
ArgumentListBuilder margs = new ArgumentListBuilder();
margs.add("-N");
margs.addTokenized(getProject().getGoals());
try {
return channel.call(new Builder(
listener,new ProxyImpl(),
reporters.toArray(new MavenReporter[0]), margs.toList()));
} finally {
channel.close();
}
}
// UGLY....
private ArgumentListBuilder buildMavenCmdLine() throws IOException, InterruptedException {
MavenInstallation mvn = getParent().getParent().getMaven();
// find classworlds.jar
File bootDir = new File(mvn.getHomeDir(), "core/boot");
File[] classworlds = bootDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("classworlds") && name.endsWith(".jar");
}
});
if(classworlds==null || classworlds.length==0)
throw new IOException("No classworlds*.jar found in "+bootDir);
boolean isMaster = getCurrentNode()==Hudson.getInstance();
FilePath slaveRoot=null;
if(!isMaster)
slaveRoot = ((Slave)getCurrentNode()).getFilePath();
ArgumentListBuilder args = new ArgumentListBuilder();
args.add(launcher.getChannel().call(new getJavaExe()));
args.add("-cp");
args.add(
(isMaster?Which.jarFile(Main.class).getAbsolutePath():slaveRoot.child("maven-agent.jar").getRemote())+
(launcher.isUnix()?":":";")+
classworlds[0].getAbsolutePath());
args.add(Main.class.getName());
// M2_HOME
args.add(mvn.getMavenHome());
// remoting.jar
args.add(Which.jarFile(Launcher.class).getPath());
// interceptor.jar
args.add(isMaster?
Which.jarFile(hudson.maven.agent.PluginManagerInterceptor.class).getAbsolutePath():
slaveRoot.child("maven-interceptor.jar").getRemote());
return args;
}
public void post(BuildListener listener) {
if(!getResult().isWorseThan(Result.UNSTABLE)) {
// trigger dependency builds
DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
for( AbstractProject<?,?> down : getParent().getDownstreamProjects()) {
if(graph.hasIndirectDependencies(getParent(),down))
// if there's a longer dependency path to this project,
// then scheduling the build now is going to be a waste,
// so don't do that.
// let the longer path eventually trigger this build
continue;
// if the downstream module depends on multiple modules,
// only trigger them when all the upstream dependencies are updated.
boolean trigger = true;
AbstractBuild<?,?> dlb = down.getLastBuild(); // can be null.
for (MavenModule up : Util.filter(down.getUpstreamProjects(),MavenModule.class)) {
MavenBuild ulb;
if(up==getProject()) {
// the current build itself is not registered as lastSuccessfulBuild
// at this point, so we have to take that into account. ugly.
if(getResult()==null || !getResult().isWorseThan(Result.UNSTABLE))
ulb = MavenBuild.this;
else
ulb = up.getLastSuccessfulBuild();
} else
ulb = up.getLastSuccessfulBuild();
if(ulb==null) {
// if no usable build is available from the upstream,
// then we have to wait at least until this build is ready
trigger = false;
break;
}
// if no record of the relationship in the last build
// is available, we'll just have to assume that the condition
// for the new build is met, or else no build will be fired forever.
if(dlb==null) continue;
int n = dlb.getUpstreamRelationship(up);
if(n==-1) continue;
assert ulb.getNumber()>=n;
if(ulb.getNumber()==n) {
// there's no new build of this upstream since the last build
// of the downstream, and the upstream build is in progress.
// The new downstream build should wait until this build is started
if(isUpstreamBuilding(graph,up)) {
trigger = false;
break;
}
}
}
if(trigger) {
listener.getLogger().println("Triggering a new build of "+down.getName());
down.scheduleBuild();
}
}
}
}
/**
* Returns true if any of the upstream project (or itself) is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
private boolean isUpstreamBuilding(DependencyGraph graph, AbstractProject project) {
Set<AbstractProject> tups = graph.getTransitiveUpstream(project);
tups.add(project);
for (AbstractProject tup : tups) {
if(tup.isBuilding() || tup.isInQueue())
return true;
}
return false;
}
}
} |
package me.benjozork.onyx.object;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Polygon;
import com.badlogic.gdx.math.Vector2;
import me.benjozork.onyx.internal.PolygonHelper;
import me.benjozork.onyx.utils.Utils;
/**
* Describes an object that is to be drawn on the screen
* @author Benjozork
*/
public abstract class Drawable {
protected Vector2 position;
protected Vector2 velocity = new Vector2(0, 0);
protected Vector2 acceleration = new Vector2(0, 0);
protected float maxVelocity = 100f;
protected float angle;
protected Polygon bounds;
private float speed, maxSpeed;
private boolean boundsDebug = false;
private boolean defaultMaxSpeed = true;
private Polygon cache;
public Drawable(int x, int y) {
this.position = new Vector2(x, y);
}
public Drawable(Vector2 position) {
this.position = position;
}
/**
* Internally update the Drawable
*
* @param dt The delta time
*/
public void update(float dt) {
if (defaultMaxSpeed) maxSpeed = speed + 1f;
bounds.setPosition(position.x,position.y);
if (speed > maxSpeed) speed = maxSpeed;
if (speed < -maxSpeed) speed = -maxSpeed;
if (angle != 0) {
velocity.x = (float) Math.sin(angle);
velocity.y = (float) Math.cos(angle);
}
position.add(velocity.nor().scl(dt).scl(speed));
}
public abstract void init();
/**
* Update the Drawable
*/
public abstract void update();
public abstract void draw();
/**
* Check if the Drawable collides with a polygon
*
* @param otherBounds The polygon used to check
* @return If the Drawable collides with otherBounds
*/
public boolean collidesWith(Polygon otherBounds) {
return PolygonHelper.polygonCollide(bounds,otherBounds);
}
/**
* The Drawable's position
*
* @return The Drawable's position
*/
public Vector2 getPosition() {
return position;
}
public void setPosition(Vector2 position) {
this.position = position;
this.bounds.setPosition(position.x,position.y);
}
/**
* The X coordinate value
*
* @return The X coordinate value
*/
public float getX() {
return position.x;
}
public void setX(float v) {
position.x = v;
bounds.setPosition(position.x,position.y);
}
/**
* The Y coordinate value
*
* @return The Y coordinate value
*/
public float getY() {
return position.y;
}
public void setY(float v) {
position.y = v;
bounds.setPosition(position.x,position.y);
}
public void move(float dx, float dy) {
// here, we move the position and the bounding box
position.x += dx * Utils.delta();
position.y += dy * Utils.delta();
bounds.setPosition(position.x,position.y);
}
/**
* The velocity
*
* @return The velocity
*/
public Vector2 getVelocity() {
return velocity;
}
public void setVelocity(Vector2 velocity) {
this.velocity = velocity;
}
/**
* The acceleration
*
* @return The acceleration
*/
public Vector2 getAcceleration() {
return acceleration;
}
public void setAcceleration(Vector2 acceleration) {
this.acceleration = acceleration;
}
/**
* Change the speed
*
* @param v The speed offset
*/
public void accelerate(float v) {
speed += v;
if (velocity.x == 0 && velocity.y == 0 && speed > 0f) velocity.set(0, 1); // Prevent this from having no effect
}
/**
* The max velocity
*
* @return The max velocity
*/
public float getMaxVelocity() {
return maxVelocity;
}
public void setMaxVelocity(float maxVelocity) {
this.maxVelocity = maxVelocity;
}
public void rotate(float v) {
angle += v * Utils.delta();
}
/**
* The speed
*
* @return The speed
*/
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public float getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(float maxSpeed) {
this.maxSpeed = maxSpeed;
defaultMaxSpeed = false;
}
/**
* Check if the mouse hovers above the hitbox
*
* @return result
*/
public boolean hovering() {
Vector2 mouse = Utils.unprojectWorld(Gdx.input.getX(), Gdx.input.getY());
return getBounds().contains(mouse);
// if (mouse.x > getBounds().getX()
// && mouse.x < (getBounds().getX() + getBounds().getWidth())
// && mouse.y > getBounds().getY()
// && mouse.y < (getBounds().getY() + getBounds().getHeight())) {
// return true;
// } else return false;
}
/**
* The bounding box
*
* @return The bounding box
*/
public Polygon getBounds() {
return bounds;
}
public void setBounds(Polygon bounds) {
this.bounds = bounds;
}
/**
* Toggle the hitbox debug rendering
*/
public void toggleBoundsDebug() {
boundsDebug = ! boundsDebug;
}
public abstract void dispose();
} |
package pt.fccn.arquivo.tests.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
public class AnalyzeURLs {
/**
* Check if link exists
* @param URLName
* @param text
* @return
*/
public static int linkExists( String URLName ) {
boolean redirect = false;
try {
System.out.println( "[linkExists] url[" + URLName + "]" );
HttpURLConnection con = ( HttpURLConnection ) new URL( URLName ).openConnection( );
con.setConnectTimeout( 5000 );
con.setRequestMethod( "HEAD" );
con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" );
con.addRequestProperty( "User-Agent", "Mozilla" );
con.addRequestProperty( "Referer", "google.com" );
// normally, 3xx is redirect
int status = con.getResponseCode( );
System.out.println( "Status-code = " + status );
redirect = checkRedirect( status );
System.out.println( "[linkExists] url[" + URLName + "] Status-code = " + con.getResponseCode( ) );
con.disconnect( );
while( redirect ) {
// get redirect url from "location" header field
String newUrl = con.getHeaderField( "Location" );
System.out.println( "Redirect: true url["+URLName+"] newurl["+newUrl+"]" );
// get the cookie if need, for login
String cookies = con.getHeaderField( "Set-Cookie" );
// open the new connection again
con = ( HttpURLConnection ) new URL( newUrl ).openConnection( );
con.setConnectTimeout( 5000 );
con.setRequestMethod( "HEAD" );
con.setRequestProperty( "Cookie", cookies );
con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" );
con.addRequestProperty( "User-Agent", "Mozilla" );
con.addRequestProperty( "Referer", "google.com" );
status = con.getResponseCode( );
URLName = newUrl;
System.out.println( "Novo redirect status = " + status + " message = " + con.getResponseMessage( ) );
redirect = checkRedirect( status );
con.disconnect( );
}
return status;
} catch ( MalformedURLException e ) {
System.out.println( "MalformedURLException e = " + e.getMessage( ) );
return -1;
} catch ( IOException e ) {
System.out.println( "IOException e = " + e.getMessage( ) );
return -1;
}
}
/**
* Check if link exists
* @param URLName
* @return
*/
public static boolean linkExists( String URLName , String text , Map< String, String > textTolink ) {
boolean redirect = false;
try {
System.out.println( "[Footer] url[" + URLName + "]" );
HttpURLConnection con = ( HttpURLConnection ) new URL( URLName ).openConnection( );
con.setConnectTimeout( 5000 );
con.setRequestMethod( "HEAD" );
con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" );
con.addRequestProperty( "User-Agent", "Mozilla" );
con.addRequestProperty( "Referer", "google.com" );
// normally, 3xx is redirect
int status = con.getResponseCode( );
System.out.println( "Status-code = " + status );
redirect = checkRedirect( status );
System.out.println( "[Footer] url[" + URLName + "] Status-code = " + con.getResponseCode( ) );
con.disconnect( );
while( redirect ) {
// get redirect url from "location" header field
String newUrl = con.getHeaderField( "Location" );
System.out.println( "Redirect: true url["+URLName+"] newurl["+newUrl+"]" );
// get the cookie if need, for login
String cookies = con.getHeaderField( "Set-Cookie" );
// open the new connection again
con = ( HttpURLConnection ) new URL( newUrl ).openConnection( );
con.setConnectTimeout( 5000 );
con.setRequestMethod( "HEAD" );
con.setRequestProperty( "Cookie", cookies );
con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" );
con.addRequestProperty( "User-Agent", "Mozilla" );
con.addRequestProperty( "Referer", "google.com" );
status = con.getResponseCode( );
URLName = newUrl;
System.out.println( "Novo redirect status = " + status + " message = " + con.getResponseMessage( ) );
redirect = checkRedirect( status );
con.disconnect( );
}
System.out.println( "Compare textTolink.get( "+text+" ) = " + textTolink.get( text ) + " URLName = " + URLName + " Status-code = " + status );
if( status == HttpURLConnection.HTTP_OK && textTolink.get( text ).trim( ).equals( URLName.trim( ) ) )
return true;
else
return false;
} catch ( MalformedURLException e ) {
System.out.println( "MalformedURLException e = " + e.getMessage( ) );
return false;
} catch ( IOException e ) {
System.out.println( "IOException e = " + e.getMessage( ) );
return false;
}
}
/**
* Check if link exists
* @param URLName
* @param text
* @return
*/
public static boolean checkLink( String URLName ) {
boolean redirect = false;
try {
System.out.println( "[linkExists] url[" + URLName + "]" );
HttpURLConnection con = ( HttpURLConnection ) new URL( URLName ).openConnection( );
con.setConnectTimeout( 5000 );
con.setRequestMethod( "HEAD" );
con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" );
con.addRequestProperty( "User-Agent", "Mozilla" );
con.addRequestProperty( "Referer", "google.com" );
// normally, 3xx is redirect
int status = con.getResponseCode( );
System.out.println( "Status-code = " + status );
redirect = checkRedirect( status );
System.out.println( "[linkExists] url[" + URLName + "] Status-code = " + con.getResponseCode( ) );
con.disconnect( );
while( redirect ) {
// get redirect url from "location" header field
String newUrl = con.getHeaderField( "Location" );
System.out.println( "Redirect: true url["+URLName+"] newurl["+newUrl+"]" );
// open the new connection again
con = ( HttpURLConnection ) new URL( newUrl ).openConnection( );
con.setConnectTimeout( 5000 );
con.setRequestMethod( "HEAD" );
con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" );
con.setRequestProperty( "Accept-Charset" , "UTF-8" );
con.setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded;charset=UTF-8" );
con.addRequestProperty( "User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0" );
con.addRequestProperty( "Referer", "google.com" );
status = con.getResponseCode( );
URLName = newUrl;
System.out.println( "Link["+URLName+"] Novo redirect status = " + status + " message = " + con.getResponseMessage( ) );
redirect = checkRedirect( status );
con.disconnect( );
}
System.out.println( "return status-code["+status+"]" );
return checkOk( status );
} catch ( MalformedURLException e ) {
System.out.println( "MalformedURLException e = " + e.getMessage( ) );
return false;
} catch ( IOException e ) {
System.out.println( "IOException e = " + e.getMessage( ) );
return false;
}
}
/**
*
* @param status
* @return
*/
public static boolean checkRedirect( int status ){
if ( status != HttpURLConnection.HTTP_OK ) {
if ( status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER )
return true;
}
return false;
}
/**
*
* @param status
* @return
*/
public static boolean checkOk( int status ){
return ( status == HttpURLConnection.HTTP_OK );
}
} |
package org.antlr.codebuff;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.Vocabulary;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.antlr.v4.runtime.tree.Tree;
import org.antlr.v4.runtime.tree.Trees;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CollectFeatures extends JavaBaseListener {
public static final double MAX_CONTEXT_DIFF_THRESHOLD = 0.15; // anything more than 15% different is probably too far
public static final int INDEX_PREV2_TYPE = 0;
public static final int INDEX_PREV_TYPE = 1;
public static final int INDEX_PREV_END_COLUMN = 2;
public static final int INDEX_PREV_EARLIEST_ANCESTOR = 3;
public static final int INDEX_TYPE = 4;
public static final int INDEX_EARLIEST_ANCESTOR = 5;
public static final int INDEX_ANCESTOR_WIDTH = 6;
public static final int INDEX_NEXT_TYPE = 7;
public static final String[] FEATURE_NAMES = {
"prev^2 type",
"prev type", "prev end column", "previous earliest ancestor rule",
"type", "earliest ancestor rule", "earliest ancestor width",
"next type",
};
public static final String[][] ABBREV_FEATURE_NAMES = {
{"", "LT(-2)"},
{"", "LT(-1)"}, {"LT(-1)", "end col"}, {"LT(-1)", "right ancestor"},
{"","LT(1)"}, {"LT(1)", "left ancestor"}, {"LT(1) anc.", "width"},
{"", "LT(2)"},
};
public static final int[] mismatchCost = {
1, // INDEX_PREV2_TYPE
2, // INDEX_PREV_TYPE
1, // INDEX_PREV_END_COLUMN
2, // INDEX_PREV_EARLIEST_ANCESTOR
2, // INDEX_TYPE
2, // INDEX_EARLIEST_ANCESTOR
1, // INDEX_ANCESTOR_WIDTH
2 // INDEX_NEXT_TYPE
};
public static final int MAX_L0_DISTANCE_COUNT = Tool.sum(mismatchCost);
public static final boolean[] CATEGORICAL = {
true,
true, false, true,
true, true, false,
true
};
protected ParserRuleContext root;
protected CommonTokenStream tokens; // track stream so we can examine previous tokens
protected List<int[]> features = new ArrayList<>();
protected List<Integer> injectNewlines = new ArrayList<>();
protected List<Integer> injectWS = new ArrayList<>();
protected List<Integer> indent = new ArrayList<>();
/** steps to common ancestor whose first token is alignment anchor */
protected List<Integer> levelsToCommonAncestor = new ArrayList<>();
protected Token firstTokenOnLine = null;
protected Map<Token, TerminalNode> tokenToNodeMap = new HashMap<>();
protected int tabSize;
public CollectFeatures(ParserRuleContext root, CommonTokenStream tokens, int tabSize) {
this.root = root;
this.tokens = tokens;
this.tabSize = tabSize;
}
@Override
public void visitTerminal(TerminalNode node) {
Token curToken = node.getSymbol();
if ( curToken.getType()==Token.EOF ) return;
tokenToNodeMap.put(curToken, node); // make an index for fast lookup.
int i = curToken.getTokenIndex();
if ( Tool.getNumberRealTokens(tokens, 0, i-1)<2 ) return;
tokens.seek(i); // see so that LT(1) is tokens.get(i);
Token prevToken = tokens.LT(-1);
// find number of blank lines
int[] features = getNodeFeatures(tokenToNodeMap, tokens, node, tabSize);
int precedingNL = 0; // how many lines to inject
if ( curToken.getLine() > prevToken.getLine() ) { // a newline must be injected
List<Token> wsTokensBeforeCurrentToken = tokens.getHiddenTokensToLeft(i);
for (Token t : wsTokensBeforeCurrentToken) {
precedingNL += Tool.count(t.getText(), '\n');
}
}
// System.out.printf("%5s: ", precedingNL);
// System.out.printf("%s\n", Tool.toString(features));
this.injectNewlines.add(precedingNL);
int columnDelta = 0;
int ws = 0;
int levelsToCommonAncestor = 0;
if ( precedingNL>0 ) {
if ( firstTokenOnLine!=null ) {
columnDelta = curToken.getCharPositionInLine() - firstTokenOnLine.getCharPositionInLine();
}
firstTokenOnLine = curToken;
ParserRuleContext commonAncestor = getFirstTokenOfCommonAncestor(root, tokens, i, tabSize);
List<? extends Tree> ancestors = Trees.getAncestors(node);
Collections.reverse(ancestors);
levelsToCommonAncestor = ancestors.indexOf(commonAncestor);
}
else {
ws = curToken.getCharPositionInLine() -
(prevToken.getCharPositionInLine()+prevToken.getText().length());
}
this.indent.add(columnDelta);
this.injectWS.add(ws); // likely negative if precedingNL
this.levelsToCommonAncestor.add(levelsToCommonAncestor);
this.features.add(features);
}
/** Return number of steps to common ancestor whose first token is alignment anchor.
* Return null if no such common ancestor.
*/
public static ParserRuleContext getFirstTokenOfCommonAncestor(
ParserRuleContext root,
CommonTokenStream tokens,
int tokIndex,
int tabSize)
{
List<Token> tokensOnPreviousLine = getTokensOnPreviousLine(tokens, tokIndex);
// look for alignment
if ( tokensOnPreviousLine.size()>0 ) {
Token curToken = tokens.get(tokIndex);
Token alignedToken = findAlignedToken(tokensOnPreviousLine, curToken);
tokens.seek(tokIndex); // seek so that LT(1) is tokens.get(i);
Token prevToken = tokens.LT(-1);
int prevIndent = tokensOnPreviousLine.get(0).getCharPositionInLine();
int curIndent = curToken.getCharPositionInLine();
boolean tabbed = curIndent>prevIndent && curIndent%tabSize==0;
boolean precedingNL = curToken.getLine()>prevToken.getLine();
if ( precedingNL &&
alignedToken!=null &&
alignedToken!=tokensOnPreviousLine.get(0) &&
!tabbed ) {
// if cur token is on new line and it lines up and it's not left edge,
// it's alignment not 0 indent
// printAlignment(tokens, curToken, tokensOnPreviousLine, alignedToken);
ParserRuleContext commonAncestor = Trees.getRootOfSubtreeEnclosingRegion(root, alignedToken.getTokenIndex(), curToken.getTokenIndex());
// System.out.println("common ancestor: "+JavaParser.ruleNames[commonAncestor.getRuleIndex()]);
if ( commonAncestor.getStart()==alignedToken ) {
// aligned with first token of common ancestor
return commonAncestor;
}
}
}
return null;
}
/** Walk upwards from node while p.start == token; return null if there is
* no ancestor starting at token.
*/
public static ParserRuleContext earliestAncestorStartingAtToken(ParserRuleContext node, Token token) {
ParserRuleContext p = node;
ParserRuleContext prev = null;
while (p!=null && p.getStart()==token) {
prev = p;
p = p.getParent();
}
return prev;
}
/** Walk upwards from node while p.stop == token; return null if there is
* no ancestor stopping at token.
*/
public static ParserRuleContext earliestAncestorStoppingAtToken(ParserRuleContext node, Token token) {
ParserRuleContext p = node;
ParserRuleContext prev = null;
while (p!=null && p.getStop()==token) {
prev = p;
p = p.getParent();
}
if ( prev==null ) return node;
return prev;
}
public static ParserRuleContext deepestCommonAncestor(ParserRuleContext t1, ParserRuleContext t2) {
if ( t1==t2 ) return t1;
List<? extends Tree> t1_ancestors = Trees.getAncestors(t1);
List<? extends Tree> t2_ancestors = Trees.getAncestors(t2);
// first ancestor of t2 that matches an ancestor of t1 is the deepest common ancestor
for (Tree t : t1_ancestors) {
int i = t2_ancestors.indexOf(t);
if ( i>=0 ) {
return (ParserRuleContext)t2_ancestors.get(i);
}
}
return null;
}
public static int[] getNodeFeatures(Map<Token, TerminalNode> tokenToNodeMap,
CommonTokenStream tokens,
TerminalNode node,
int tabSize)
{
Token curToken = node.getSymbol();
int i = curToken.getTokenIndex();
tokens.seek(i); // seek so that LT(1) is tokens.get(i);
// Get a 4-gram of tokens with current token in 3rd position
List<Token> window =
Arrays.asList(tokens.LT(-2), tokens.LT(-1), tokens.LT(1), tokens.LT(2));
// Get context information for previous token
Token prevToken = tokens.LT(-1);
TerminalNode prevTerminalNode = tokenToNodeMap.get(prevToken);
ParserRuleContext parent = (ParserRuleContext)prevTerminalNode.getParent();
ParserRuleContext earliestAncestor = earliestAncestorStoppingAtToken(parent, prevToken);
int prevEarliestAncestorRuleIndex = -1;
if ( earliestAncestor!=null ) {
prevEarliestAncestorRuleIndex = earliestAncestor.getRuleIndex();
}
// Get context information for current token
parent = (ParserRuleContext)node.getParent();
earliestAncestor = earliestAncestorStartingAtToken(parent, curToken);
int earliestAncestorRuleIndex = -1;
int earliestAncestorWidth = -1;
if ( earliestAncestor!=null ) {
earliestAncestorRuleIndex = earliestAncestor.getRuleIndex();
earliestAncestorWidth = earliestAncestor.stop.getStopIndex()-earliestAncestor.start.getStartIndex()+1;
}
int prevTokenEndCharPos = window.get(1).getCharPositionInLine() + window.get(1).getText().length();
int[] features = {
window.get(0).getType(),
window.get(1).getType(), prevTokenEndCharPos, prevEarliestAncestorRuleIndex,
window.get(2).getType(), earliestAncestorRuleIndex, earliestAncestorWidth,
window.get(3).getType(),
};
// System.out.print(curToken+": "+CodekNNClassifier._toString(features));
return features;
}
public static Token findAlignedToken(List<Token> tokens, Token leftEdgeToken) {
for (Token t : tokens) {
if ( t.getCharPositionInLine() == leftEdgeToken.getCharPositionInLine() ) {
return t;
}
}
return null;
}
/** Search backwards from tokIndex into 'tokens' stream and get all on-channel
* tokens on previous line with respect to token at tokIndex.
* return empty list if none found. First token in returned list is
* the first token on the line.
*/
public static List<Token> getTokensOnPreviousLine(CommonTokenStream tokens, int tokIndex) {
// first find previous line by looking for real token on line < tokens.get(i)
Token curToken = tokens.get(tokIndex);
int curLine = curToken.getLine();
int prevLine = 0;
for (int i=tokIndex-1; i>=0; i
Token t = tokens.get(i);
if ( t.getChannel()==Token.DEFAULT_CHANNEL && t.getLine()<curLine ) {
prevLine = t.getLine();
tokIndex = i; // start collecting at this index
break;
}
}
// Now collect the on-channel real tokens for this line
List<Token> online = new ArrayList<>();
for (int i=tokIndex; i>=0; i
Token t = tokens.get(i);
if ( t.getLine()<prevLine ) break; // found last token on that previous line
if ( t.getChannel()==Token.DEFAULT_CHANNEL && t.getLine()==prevLine ) {
online.add(t);
}
}
Collections.reverse(online);
return online;
}
public static void printAlignment(CommonTokenStream tokens, Token curToken, List<Token> tokensOnPreviousLine, Token alignedToken) {
int alignedCol = alignedToken.getCharPositionInLine();
int indent = tokensOnPreviousLine.get(0).getCharPositionInLine();
int first = tokensOnPreviousLine.get(0).getTokenIndex();
int last = tokensOnPreviousLine.get(tokensOnPreviousLine.size()-1).getTokenIndex();
System.out.println(Tool.spaces(alignedCol-indent)+"\u2193");
for (int j=first; j<=last; j++) {
System.out.print(tokens.get(j).getText());
}
System.out.println();
System.out.println(Tool.spaces(alignedCol-indent)+curToken.getText());
}
public List<int[]> getFeatures() {
return features;
}
public List<Integer> getInjectNewlines() {
return injectNewlines;
}
public List<Integer> getInjectWS() {
return injectWS;
}
public List<Integer> getLevelsToCommonAncestor() {
return levelsToCommonAncestor;
}
public List<Integer> getIndent() {
return indent;
}
public static String _toString(int[] features) {
Vocabulary v = org.antlr.groom.JavaParser.VOCABULARY;
return String.format(
"%-15s %-15s %7d %-18s | %-15s %-18s %8d %-15s",
StringUtils.center(v.getDisplayName(features[INDEX_PREV2_TYPE]), 15),
StringUtils.center(v.getDisplayName(features[INDEX_PREV_TYPE]), 15),
features[INDEX_PREV_END_COLUMN],
features[INDEX_PREV_EARLIEST_ANCESTOR]>=0 ? StringUtils.abbreviateMiddle(JavaParser.ruleNames[features[INDEX_PREV_EARLIEST_ANCESTOR]], "..", 18) : "",
StringUtils.center(v.getDisplayName(features[INDEX_TYPE]), 15),
features[INDEX_EARLIEST_ANCESTOR]>=0 ? StringUtils.abbreviateMiddle(JavaParser.ruleNames[features[INDEX_EARLIEST_ANCESTOR]], "..", 18) : "",
features[INDEX_ANCESTOR_WIDTH],
StringUtils.center(v.getDisplayName(features[INDEX_NEXT_TYPE]), 15)
);
}
public static String featureNameHeader() {
String top = String.format(
"%-15s %-15s %7s %-18s | %-15s %-18s %8s %-15s",
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV2_TYPE][0], 15),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV_TYPE][0], 15),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV_END_COLUMN][0], 7),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV_EARLIEST_ANCESTOR][0], 18),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_TYPE][0], 15),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_EARLIEST_ANCESTOR][0], 18),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_ANCESTOR_WIDTH][0], 7),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_NEXT_TYPE][0], 15)
);
String bottom = String.format(
"%-15s %-15s %7s %-18s | %-15s %-18s %8s %-15s",
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV2_TYPE][1], 15),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV_TYPE][1], 15),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV_END_COLUMN][1], 7),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_PREV_EARLIEST_ANCESTOR][1], 18),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_TYPE][1], 15),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_EARLIEST_ANCESTOR][1], 18),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_ANCESTOR_WIDTH][1], 7),
StringUtils.center(ABBREV_FEATURE_NAMES[INDEX_NEXT_TYPE][1], 15)
);
String line = String.format(
"%-15s %-15s %7s %-18s | %-15s %-18s %8s %-15s",
Tool.sequence(15,"="),
Tool.sequence(15,"="),
Tool.sequence(7,"="),
Tool.sequence(18,"="),
Tool.sequence(15,"="),
Tool.sequence(18,"="),
Tool.sequence(8,"="),
Tool.sequence(15,"=")
);
return top+"\n"+bottom+"\n"+line;
}
} |
package com.sun.jna.examples;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Window;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.PopupFactory;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.examples.unix.X11;
import com.sun.jna.examples.unix.X11.Display;
import com.sun.jna.examples.unix.X11.Drawable;
import com.sun.jna.examples.unix.X11.GC;
import com.sun.jna.examples.unix.X11.Pixmap;
import com.sun.jna.examples.unix.X11.XVisualInfo;
import com.sun.jna.examples.unix.X11.Xext;
import com.sun.jna.examples.unix.X11.Xrender.XRenderPictFormat;
import com.sun.jna.examples.win32.GDI32;
import com.sun.jna.examples.win32.User32;
import com.sun.jna.examples.win32.GDI32.BITMAPINFO;
import com.sun.jna.examples.win32.User32.BLENDFUNCTION;
import com.sun.jna.examples.win32.User32.POINT;
import com.sun.jna.examples.win32.User32.SIZE;
import com.sun.jna.examples.win32.W32API.HANDLE;
import com.sun.jna.examples.win32.W32API.HBITMAP;
import com.sun.jna.examples.win32.W32API.HDC;
import com.sun.jna.examples.win32.W32API.HRGN;
import com.sun.jna.examples.win32.W32API.HWND;
import com.sun.jna.ptr.ByteByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
/**
* Provides additional features on a Java {@link Window}.
* <ul>
* <li>Non-rectangular shape (bitmap mask, no antialiasing)
* <li>Transparency (constant alpha applied to window contents or
* transparent background)
* <li>Fully transparent window (the transparency of all painted pixels is
* applied to the window).
* </ul>
* NOTE: since there is no explicit way to force PopupFactory to use a
* heavyweight popup, and anything but a heavyweight popup will be
* clipped by a window mask, an additional subwindow is added to all
* masked windows to implicitly force PopupFactory to use a heavyweight
* window and avoid clipping.
* <p>
* NOTE: {@link #setWindowTransparent} on X11 doesn't composite
* entirely correctly; depending on what's drawn in the window it mey be
* more or less noticable.
* <p>
* NOTE: Neither shaped windows nor transparency
* currently works with Java 1.4 under X11. This is at least partly due
* to 1.4 using multiple X11 windows for a single given Java window. It
* *might* be possible to remedy by applying the window
* region/transparency to all descendants, but I haven't tried it. In
* addition, windows must be both displayable <em>and</em> visible
* before the corresponding native Drawable may be obtained; in later
* Java versions, the window need only be displayable.
* <p>
* NOTE: If you use {@link #setWindowMask(Window,Shape)} and override {@link
* Window#paint(Graphics)} on OS X, you'll need to explicitly set the clip
* mask on the <code>Graphics</code> object with the window mask; only the
* content pane of the window and below have the window mask automatically
* applied.
*/
// TODO: setWindowMask() should accept a threshold; some cases want a
// 50% threshold, some might want zero/non-zero
public class WindowUtils {
public static boolean doPaint;
private static final String TRANSPARENT_OLD_BG = "transparent-old-bg";
private static final String TRANSPARENT_OLD_OPAQUE = "transparent-old-opaque";
private static final String TRANSPARENT_ALPHA = "transparent-alpha";
/** Use this to clear a window mask. */
public static final Shape MASK_NONE = null;
/**
* This class forces a heavyweight popup on the parent
* {@link Window}. See the implementation of {@link PopupFactory};
* a heavyweight is forced if there is an occluding subwindow on the
* target window.
* <p>
* Ideally we'd have more control over {@link PopupFactory} but this
* is a fairly simple, lightweight workaround.
*/
private static class HeavyweightForcer extends Window {
private boolean packed;
public HeavyweightForcer(Window parent) {
super(parent);
pack();
packed = true;
}
public boolean isVisible() {
// Only want to be 'visible' once the peer is instantiated
// via pack
return packed;
}
public Rectangle getBounds() {
return getOwner().getBounds();
}
}
/**
* This can be installed over a {@link JLayeredPane} in order to
* listen for repaint requests. The {@link #update} method will be
* invoked whenever any part of the ancestor window is repainted.
*/
private static abstract class RepaintTrigger extends JComponent {
protected class Listener extends WindowAdapter implements
ComponentListener, HierarchyListener {
public void windowOpened(WindowEvent e) {
repaint();
}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentResized(ComponentEvent e) {
setSize(getParent().getSize());
repaint();
}
public void componentShown(ComponentEvent e) {
repaint();
}
public void hierarchyChanged(HierarchyEvent e) {
repaint();
}
}
private Listener listener = createListener();
public void addNotify() {
super.addNotify();
Window w = SwingUtilities.getWindowAncestor(this);
setSize(getParent().getSize());
w.addComponentListener(listener);
w.addWindowListener(listener);
}
public void removeNotify() {
Window w = SwingUtilities.getWindowAncestor(this);
w.removeComponentListener(listener);
w.removeWindowListener(listener);
super.removeNotify();
}
private boolean painting;
protected void paintComponent(Graphics g) {
if (!painting) {
painting = true;
update();
painting = false;
}
}
protected Listener createListener() {
return new Listener();
}
protected abstract void update();
public static void remove(Container c) {
for (int i = 0; i < c.getComponentCount(); i++) {
if (c.getComponent(i) instanceof RepaintTrigger) {
c.remove(i);
return;
}
}
}
};
/**
* Execute the given action when the given window becomes
* displayable.
*/
public static void whenDisplayable(Window w, final Runnable action) {
if (w.isDisplayable() && (!Holder.requiresVisible || w.isVisible())) {
action.run();
}
else if (Holder.requiresVisible) {
w.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
e.getWindow().removeWindowListener(this);
action.run();
}
public void windowClosed(WindowEvent e) {
e.getWindow().removeWindowListener(this);
}
});
}
else {
// Hierarchy events are fired in direct response to
// displayability
// changes
w.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0
&& e.getComponent().isDisplayable()) {
e.getComponent().removeHierarchyListener(this);
action.run();
}
}
});
}
}
/** Window utilities with differing native implementations. */
public static abstract class NativeWindowUtils {
/**
* Set the overall alpha transparency of the window. An alpha of
* 1.0 is fully opaque, 0.0 is fully transparent.
*/
public void setWindowAlpha(Window w, float alpha) {
// do nothing
}
/** Default: no support. */
public boolean isWindowAlphaSupported() {
return false;
}
/** Return the default graphics configuration. */
public GraphicsConfiguration getAlphaCompatibleGraphicsConfiguration() {
GraphicsEnvironment env = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice dev = env.getDefaultScreenDevice();
return dev.getDefaultConfiguration();
}
/**
* Set the window to be transparent. Only explicitly painted
* pixels will be non-transparent. All pixels will be composited
* with whatever is under the window using their alpha values.
*/
public void setWindowTransparent(Window w, boolean transparent) {
// do nothing
}
protected void setLayersTransparent(Window w, boolean transparent) {
Color bg = transparent ? new Color(0, 0, 0, 0) : null;
if (w instanceof RootPaneContainer) {
RootPaneContainer rpc = (RootPaneContainer)w;
JRootPane root = rpc.getRootPane();
JLayeredPane lp = root.getLayeredPane();
Container c = root.getContentPane();
JComponent content =
(c instanceof JComponent) ? (JComponent)c : null;
if (transparent) {
lp.putClientProperty(TRANSPARENT_OLD_OPAQUE,
Boolean.valueOf(lp.isOpaque()));
lp.setOpaque(false);
root.putClientProperty(TRANSPARENT_OLD_OPAQUE,
Boolean.valueOf(root.isOpaque()));
root.setOpaque(false);
if (content != null) {
content.putClientProperty(TRANSPARENT_OLD_OPAQUE,
Boolean.valueOf(content.isOpaque()));
content.setOpaque(false);
}
root.putClientProperty(TRANSPARENT_OLD_BG,
root.getParent().getBackground());
}
else {
lp.setOpaque(Boolean.TRUE.equals(lp.getClientProperty(TRANSPARENT_OLD_OPAQUE)));
root
.setOpaque(Boolean.TRUE.equals(root.getClientProperty(TRANSPARENT_OLD_OPAQUE)));
if (content != null) {
content.setOpaque(Boolean.TRUE.equals(content.getClientProperty(TRANSPARENT_OLD_OPAQUE)));
}
bg = (Color)root.getClientProperty(TRANSPARENT_OLD_BG);
}
}
w.setBackground(bg);
}
/**
* Set the window mask based on the given Raster, which should
* be treated as a bitmap (zero/nonzero values only). A value of
* <code>null</code> means to remove the mask.
*/
public abstract void setWindowMask(Window w, Raster raster);
/** Set the window mask based on a {@link Shape}. */
public void setWindowMask(Window w, Shape mask) {
Raster raster = null;
if (mask != MASK_NONE) {
Rectangle bounds = mask.getBounds();
if (bounds.width > 0 && bounds.height > 0) {
BufferedImage bitmap =
new BufferedImage(bounds.x + bounds.width,
bounds.y + bounds.height,
BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g = bitmap.createGraphics();
g.setColor(Color.black);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(Color.white);
g.fill(mask);
raster = bitmap.getData();
}
}
setWindowMask(w, raster);
}
/**
* Set the window mask based on an Icon. All non-transparent
* pixels will be included in the mask.
*/
public void setWindowMask(final Window w, Icon mask) {
Raster raster = null;
if (mask != null) {
Rectangle bounds = new Rectangle(0, 0, mask.getIconWidth(),
mask.getIconHeight());
BufferedImage clip = new BufferedImage(bounds.width,
bounds.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = clip.createGraphics();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, bounds.width, bounds.height);
g.setComposite(AlphaComposite.SrcOver);
mask.paintIcon(w, g, 0, 0);
raster = clip.getAlphaRaster();
}
setWindowMask(w, raster);
}
/**
* Use this method to ensure heavyweight popups are used in
* conjunction with a given window. This prevents the window's
* alpha setting or mask region from being applied to the popup.
*/
protected void setForceHeavyweightPopups(Window w, boolean force) {
if (!(w instanceof HeavyweightForcer)) {
Window[] owned = w.getOwnedWindows();
for (int i = 0; i < owned.length; i++) {
if (owned[i] instanceof HeavyweightForcer) {
owned[i].dispose();
}
}
if (force) {
new HeavyweightForcer(w);
}
}
}
}
/** Canonical lazy loading of a singleton. */
private static class Holder {
/**
* Indicates whether a window must be visible before its native
* handle can be obtained. This wart is caused by the Java
* 1.4/X11 implementation.
*/
public static boolean requiresVisible;
public static final NativeWindowUtils INSTANCE;
static {
String os = System.getProperty("os.name");
if (os.startsWith("Windows")) {
INSTANCE = new W32WindowUtils();
}
else if (os.startsWith("Mac")) {
INSTANCE = new MacWindowUtils();
}
else if (os.startsWith("Linux") || os.startsWith("SunOS")) {
INSTANCE = new X11WindowUtils();
requiresVisible = System.getProperty("java.version")
.matches("^1\\.4\\..*");
}
else {
throw new UnsupportedOperationException("No support for " + os);
}
}
}
private static NativeWindowUtils getInstance() {
return Holder.INSTANCE;
}
private static class W32WindowUtils extends NativeWindowUtils {
public HWND getHWnd(Window w) {
HWND hwnd = new HWND();
hwnd.setPointer(Native.getWindowPointer(w));
return hwnd;
}
/**
* W32 alpha will only work if <code>sun.java2d.noddraw</code>
* is set
*/
public boolean isWindowAlphaSupported() {
return Boolean.getBoolean("sun.java2d.noddraw");
}
/** Indicates whether UpdateLayeredWindow is in use. */
private boolean isTransparent(Window w) {
if (w instanceof RootPaneContainer) {
JRootPane root = ((RootPaneContainer)w).getRootPane();
return root.getClientProperty(TRANSPARENT_OLD_BG) != null;
}
return false;
}
/** Keep track of the alpha level, since we can't read it from
* the window itself.
*/
private void storeAlpha(Window w, byte alpha) {
if (w instanceof RootPaneContainer) {
JRootPane root = ((RootPaneContainer)w).getRootPane();
Byte b = alpha == (byte)0xFF ? null : new Byte(alpha);
root.putClientProperty(TRANSPARENT_ALPHA, b);
}
}
/** Return the last alpha level we set on the window. */
private byte getAlpha(Window w) {
if (w instanceof RootPaneContainer) {
JRootPane root = ((RootPaneContainer)w).getRootPane();
Byte b = (Byte)root.getClientProperty(TRANSPARENT_ALPHA);
if (b != null) {
return b.byteValue();
}
}
return (byte)0xFF;
}
public void setWindowAlpha(final Window w, final float alpha) {
if (!isWindowAlphaSupported()) {
throw new UnsupportedOperationException("Set sun.java2d.noddraw=true to enable transparent windows");
}
whenDisplayable(w, new Runnable() {
public void run() {
HWND hWnd = getHWnd(w);
User32 user = User32.INSTANCE;
int flags = user.GetWindowLong(hWnd, User32.GWL_EXSTYLE);
byte level = (byte)((int)(255 * alpha) & 0xFF);
if (isTransparent(w)) {
// If already using UpdateLayeredWindow, continue to
// do so
BLENDFUNCTION blend = new BLENDFUNCTION();
blend.SourceConstantAlpha = level;
blend.AlphaFormat = User32.AC_SRC_ALPHA;
user.UpdateLayeredWindow(hWnd, null, null, null, null,
null, 0, blend,
User32.ULW_ALPHA);
}
else if (alpha == 1f) {
flags &= ~User32.WS_EX_LAYERED;
user.SetWindowLong(hWnd, User32.GWL_EXSTYLE, flags);
}
else {
flags |= User32.WS_EX_LAYERED;
user.SetWindowLong(hWnd, User32.GWL_EXSTYLE, flags);
user.SetLayeredWindowAttributes(hWnd, 0, level,
User32.LWA_ALPHA);
}
setForceHeavyweightPopups(w, alpha != 1f);
storeAlpha(w, level);
}
});
}
private class W32RepaintTrigger extends RepaintTrigger {
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x, y, w, h);
// FIXME this is a hack to get the window to properly
// refresh. figure out what w32 api needs tweaking to
// do it explicitly
if (w > 0 && h > 0)
SwingUtilities.getWindowAncestor(this).toFront();
}
public void update() {
GDI32 gdi = GDI32.INSTANCE;
User32 user = User32.INSTANCE;
Window win = SwingUtilities.getWindowAncestor(this);
int w = win.getWidth();
int h = win.getHeight();
HDC screenDC = user.GetDC(null);
HDC memDC = gdi.CreateCompatibleDC(screenDC);
HBITMAP hBitmap = null;
HANDLE oldBitmap = null;
try {
BufferedImage buf =
new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g = buf.createGraphics();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, w, h);
g.setComposite(AlphaComposite.SrcOver);
Point origin = SwingUtilities.convertPoint(getParent(), 0, 0, win);
getParent().paint(g.create(origin.x, origin.y,
getWidth(), getHeight()));
BITMAPINFO bmi = new BITMAPINFO();
bmi.bmiHeader.biWidth = w;
bmi.bmiHeader.biHeight = h;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = GDI32.BI_RGB;
bmi.bmiHeader.biSizeImage = w * h * 4;
PointerByReference ppbits = new PointerByReference();
hBitmap = gdi.CreateDIBSection(memDC, bmi,
GDI32.DIB_RGB_COLORS,
ppbits, null, 0);
oldBitmap = gdi.SelectObject(memDC, hBitmap);
Pointer pbits = ppbits.getValue();
Raster raster = buf.getData();
int[] pixel = new int[4];
int[] bits = new int[w * h];
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
raster.getPixel(col, h - row - 1, pixel);
int alpha = (pixel[3] & 0xFF) << 24;
int red = (pixel[2] & 0xFF);
int green = (pixel[1] & 0xFF) << 8;
int blue = (pixel[0] & 0xFF) << 16;
bits[col + row * w] = alpha | red | green | blue;
}
}
pbits.write(0, bits, 0, bits.length);
SIZE size = new SIZE();
size.cx = w;
size.cy = h;
POINT srcLoc = new POINT();
BLENDFUNCTION blend = new BLENDFUNCTION();
POINT loc = new POINT();
loc.x = win.getX();
loc.y = win.getY();
HWND hWnd = getHWnd(win);
// extract current constant alpha setting, if possible
ByteByReference bref = new ByteByReference();
IntByReference iref = new IntByReference();
byte level = getAlpha(win);
if (user.GetLayeredWindowAttributes(hWnd, null, bref, iref)
&& (iref.getValue() & User32.LWA_ALPHA) != 0) {
level = bref.getValue();
}
blend.SourceConstantAlpha = level;
blend.AlphaFormat = User32.AC_SRC_ALPHA;
user.UpdateLayeredWindow(hWnd, screenDC, loc, size, memDC,
srcLoc, 0, blend, User32.ULW_ALPHA);
}
finally {
user.ReleaseDC(null, screenDC);
if (hBitmap != null) {
gdi.SelectObject(memDC, oldBitmap);
gdi.DeleteObject(hBitmap);
}
gdi.DeleteDC(memDC);
}
}
}
public void setWindowTransparent(final Window w,
final boolean transparent) {
if (!(w instanceof RootPaneContainer)) {
throw new IllegalArgumentException("Window must be a RootPaneContainer");
}
if (!isWindowAlphaSupported()) {
throw new UnsupportedOperationException("Set sun.java2d.noddraw=true to enable transparent windows");
}
boolean isTransparent = w.getBackground() != null
&& w.getBackground().getAlpha() == 0;
if (!(transparent ^ isTransparent))
return;
whenDisplayable(w, new Runnable() {
public void run() {
User32 user = User32.INSTANCE;
HWND hWnd = getHWnd(w);
int flags = user.GetWindowLong(hWnd, User32.GWL_EXSTYLE);
JRootPane root = ((RootPaneContainer)w).getRootPane();
JLayeredPane lp = root.getLayeredPane();
if (transparent && !isTransparent(w)) {
flags |= User32.WS_EX_LAYERED;
user.SetWindowLong(hWnd, User32.GWL_EXSTYLE, flags);
lp.add(new W32RepaintTrigger(), JLayeredPane.DRAG_LAYER);
}
else if (!transparent && isTransparent(w)) {
flags &= ~User32.WS_EX_LAYERED;
user.SetWindowLong(hWnd, User32.GWL_EXSTYLE, flags);
RepaintTrigger.remove(lp);
}
setLayersTransparent(w, transparent);
setForceHeavyweightPopups(w, transparent);
}
});
}
public void setWindowMask(final Window w, final Raster raster) {
whenDisplayable(w, new Runnable() {
public void run() {
GDI32 gdi = GDI32.INSTANCE;
User32 user = User32.INSTANCE;
HWND hWnd = getHWnd(w);
final HRGN result = gdi.CreateRectRgn(0, 0, 0, 0);
try {
if (raster == null) {
gdi.SetRectRgn(result, 0, 0, w.getWidth(), w.getHeight());
}
else {
final HRGN tempRgn = gdi.CreateRectRgn(0, 0, 0, 0);
try {
RasterRangesUtils.outputOccupiedRanges(raster, new RasterRangesUtils.RangesOutput() {
public boolean outputRange(int x, int y, int w, int h) {
GDI32 gdi = GDI32.INSTANCE;
gdi.SetRectRgn(tempRgn, x, y, x + w, y + h);
return gdi.CombineRgn(result, result, tempRgn, GDI32.RGN_OR) != GDI32.ERROR;
}
});
}
finally {
gdi.DeleteObject(tempRgn);
}
}
user.SetWindowRgn(hWnd, result, true);
}
finally {
gdi.DeleteObject(result);
}
setForceHeavyweightPopups(w, raster != null);
}
});
}
}
private static class MacWindowUtils extends NativeWindowUtils {
private Shape shapeFromRaster(Raster raster) {
final Area area = new Area(new Rectangle(0, 0, 0, 0));
RasterRangesUtils.outputOccupiedRanges(raster, new RasterRangesUtils.RangesOutput() {
public boolean outputRange(int x, int y, int w, int h) {
area.add(new Area(new Rectangle(x, y, w, h)));
return true;
}
});
return area;
}
public boolean isWindowAlphaSupported() {
return true;
}
private OSXTransparentContent installTransparentContent(Window w) {
OSXTransparentContent content;
if (w instanceof RootPaneContainer) {
// TODO: replace layered pane instead?
final RootPaneContainer rpc = (RootPaneContainer)w;
Container oldContent = rpc.getContentPane();
if (oldContent instanceof OSXTransparentContent) {
content = (OSXTransparentContent)oldContent;
}
else {
content = new OSXTransparentContent(oldContent);
// TODO: listen for content pane changes
rpc.setContentPane(content);
}
}
else {
Component oldContent = w.getComponentCount() > 0 ? w.getComponent(0) : null;
if (oldContent instanceof OSXTransparentContent) {
content = (OSXTransparentContent)oldContent;
}
else {
content = new OSXTransparentContent(oldContent);
w.add(content);
}
}
return content;
}
public void setWindowTransparent(Window w, boolean transparent) {
boolean isTransparent = w.getBackground() != null
&& w.getBackground().getAlpha() == 0;
if (!(transparent ^ isTransparent))
return;
installTransparentContent(w);
setBackgroundTransparent(w, transparent);
setLayersTransparent(w, transparent);
}
public void setWindowAlpha(final Window w, final float alpha) {
whenDisplayable(w, new Runnable() {
public void run() {
Object peer = w.getPeer();
try {
peer.getClass().getMethod("setAlpha", new Class[]{
float.class
}).invoke(peer, new Object[]{
new Float(alpha)
});
}
catch (Exception e) {
}
}
});
}
public void setWindowMask(Window w, Raster raster) {
if (raster != null) {
setWindowMask(w, shapeFromRaster(raster));
}
else {
setWindowMask(w, new Rectangle(0, 0, w.getWidth(),
w.getHeight()));
}
}
/** Mask out unwanted pixels and ensure background gets cleared.
* @author Olivier Chafik
*/
static class OSXTransparentContent extends JPanel {
private Shape shape;
public OSXTransparentContent() {
this(null);
}
public OSXTransparentContent(Component oldContent) {
super(new BorderLayout());
if (oldContent != null) {
add(oldContent, BorderLayout.CENTER);
}
}
public void setMask(Shape shape) {
this.shape = shape;
repaint();
}
public void paint(Graphics graphics) {
Graphics2D g = (Graphics2D)graphics.create();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
if (shape != null) {
g = (Graphics2D)graphics.create();
g.setClip(shape);
super.paint(g);
g.dispose();
}
else {
super.paint(graphics);
}
}
}
private void setBackgroundTransparent(Window w, boolean transparent) {
if (transparent) {
w.setBackground(new Color(0,0,0,0));
}
else {
// FIXME restore background to original color
w.setBackground(null);
}
}
public void setWindowMask(Window w, final Shape shape) {
OSXTransparentContent content = installTransparentContent(w);
content.setMask(shape);
setBackgroundTransparent(w, shape != MASK_NONE);
}
}
private static class X11WindowUtils extends NativeWindowUtils {
private Pixmap createBitmap(final Display dpy,
X11.Window win,
Window w, Raster raster) {
final X11 x11 = X11.INSTANCE;
Rectangle bounds = raster.getBounds();
int width = bounds.x + bounds.width;
int height = bounds.y + bounds.height;
final Pixmap pm = x11.XCreatePixmap(dpy, win, width, height, 1);
final GC gc = x11.XCreateGC(dpy, pm, new NativeLong(0), null);
if (gc == null) {
return null;
}
x11.XSetForeground(dpy, gc, new NativeLong(0));
x11.XFillRectangle(dpy, pm, gc, 0, 0, width, height);
final int UNMASKED = 1;
x11.XSetForeground(dpy, gc, new NativeLong(UNMASKED));
X11.XWindowAttributes atts = new X11.XWindowAttributes();
int status = x11.XGetWindowAttributes(dpy, win, atts);
if (status == 0) {
return null;
}
try {
RasterRangesUtils.outputOccupiedRanges(raster, new RasterRangesUtils.RangesOutput() {
public boolean outputRange(int x, int y, int w, int h) {
return x11.XFillRectangle(dpy, pm, gc, x, y, w, h) != 0;
}
});
}
finally {
x11.XFreeGC(dpy, gc);
}
return pm;
}
private boolean didCheck;
private int[] alphaVisuals = {};
public boolean isWindowAlphaSupported() {
if (!didCheck) {
didCheck = true;
alphaVisuals = getAlphaVisuals();
}
return alphaVisuals.length > 0;
}
/** Return the default graphics configuration. */
public GraphicsConfiguration getAlphaCompatibleGraphicsConfiguration() {
if (isWindowAlphaSupported()) {
GraphicsEnvironment env = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = env.getScreenDevices();
for (int i = 0; i < devices.length; i++) {
GraphicsConfiguration[] configs = devices[i]
.getConfigurations();
for (int j = 0; j < configs.length; j++) {
// Use reflection to call
// X11GraphicsConfig.getVisual
try {
Object o = configs[j].getClass()
.getMethod("getVisual", (Class[])null)
.invoke(configs[j], (Object[])null);
int visual = ((Integer)o).intValue();
for (int k = 0; k < alphaVisuals.length; k++) {
if (visual == alphaVisuals[k])
return configs[j];
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
return super.getAlphaCompatibleGraphicsConfiguration();
}
/**
* Return the visual ID of the visual which supports an alpha
* channel.
*/
private int[] getAlphaVisuals() {
X11 x11 = X11.INSTANCE;
Display dpy = x11.XOpenDisplay(null);
if (dpy == null)
return new int[0];
XVisualInfo info = null;
try {
int screen = x11.XDefaultScreen(dpy);
XVisualInfo template = new XVisualInfo();
template.screen = screen;
template.depth = 32;
template.c_class = X11.TrueColor;
NativeLong mask = new NativeLong(X11.VisualScreenMask
| X11.VisualDepthMask
| X11.VisualClassMask);
IntByReference pcount = new IntByReference();
info = x11.XGetVisualInfo(dpy, mask, template, pcount);
if (info != null) {
List list = new ArrayList();
XVisualInfo[] infos =
(XVisualInfo[])info.toArray(pcount.getValue());
for (int i = 0; i < infos.length; i++) {
XRenderPictFormat format =
X11.Xrender.INSTANCE.XRenderFindVisualFormat(dpy,
infos[i].visual);
if (format.type == X11.Xrender.PictTypeDirect
&& format.direct.alphaMask != 0) {
list.add(new Integer(infos[i].visualID));
}
}
int[] ids = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
ids[i] = ((Integer)list.get(i)).intValue();
}
return ids;
}
}
finally {
if (info != null) {
x11.XFree(info.getPointer());
}
x11.XCloseDisplay(dpy);
}
return new int[0];
}
public X11.Window getDrawable(Window w) {
int id = (int)Native.getWindowID(w);
if (id == X11.None)
return null;
return new X11.Window(id);
}
private static final long OPAQUE = 0xFFFFFFFFL;
private static final String OPACITY = "_NET_WM_WINDOW_OPACITY";
public void setWindowAlpha(final Window w, final float alpha) {
if (!isWindowAlphaSupported()) {
throw new UnsupportedOperationException("This X11 display does not provide a 32-bit visual");
}
Runnable action = new Runnable() {
public void run() {
X11 x11 = X11.INSTANCE;
Display dpy = x11.XOpenDisplay(null);
if (dpy == null)
return;
try {
X11.Window win = getDrawable(w);
if (alpha == 1f) {
x11.XDeleteProperty(dpy, win,
x11.XInternAtom(dpy, OPACITY,
false));
}
else {
int opacity = (int)((long)(alpha * OPAQUE) & 0xFFFFFFFF);
IntByReference patom = new IntByReference(opacity);
x11.XChangeProperty(dpy, win,
x11.XInternAtom(dpy, OPACITY,
false),
X11.XA_CARDINAL, 32,
X11.PropModeReplace,
patom.getPointer(), 1);
}
}
finally {
x11.XCloseDisplay(dpy);
}
}
};
whenDisplayable(w, action);
}
private class X11TransparentContent extends JPanel {
private boolean transparent;
public X11TransparentContent(Container oldContent) {
super(new BorderLayout());
add(oldContent, BorderLayout.CENTER);
setTransparent(true);
if (oldContent instanceof JPanel) {
((JComponent)oldContent).setOpaque(false);
}
}
public void setTransparent(boolean transparent) {
this.transparent = transparent;
setOpaque(!transparent);
repaint();
}
public void paint(Graphics gr) {
if (transparent) {
int w = getWidth();
int h = getHeight();
if (w > 0 && h > 0) {
BufferedImage buf =
new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = buf.createGraphics();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, w, h);
g.setComposite(AlphaComposite.SrcOver);
super.paint(g);
g = (Graphics2D)gr.create();
g.setComposite(AlphaComposite.Src);
g.drawImage(buf, 0, 0, w, h, null);
g.dispose();
}
}
else {
super.paint(gr);
}
}
}
public void setWindowTransparent(final Window w,
final boolean transparent) {
if (!(w instanceof RootPaneContainer)) {
throw new IllegalArgumentException("Window must be a RootPaneContainer");
}
if (!isWindowAlphaSupported()) {
throw new UnsupportedOperationException("This X11 display does not provide a 32-bit visual");
}
if (!w.getGraphicsConfiguration()
.equals(getAlphaCompatibleGraphicsConfiguration())) {
throw new IllegalArgumentException("Window GraphicsConfiguration does not support transparency");
}
boolean isTransparent = w.getBackground() != null
&& w.getBackground().getAlpha() == 0;
if (!(transparent ^ isTransparent))
return;
whenDisplayable(w, new Runnable() {
public void run() {
JRootPane root = ((RootPaneContainer)w).getRootPane();
Container content = root.getContentPane();
if (content instanceof X11TransparentContent) {
((X11TransparentContent)content)
.setTransparent(transparent);
}
else if (transparent) {
root.setContentPane(new X11TransparentContent(content));
}
setLayersTransparent(w, transparent);
setForceHeavyweightPopups(w, transparent);
}
});
}
public void setWindowMask(final Window w, final Raster raster) {
Runnable action = new Runnable() {
public void run() {
X11 x11 = X11.INSTANCE;
Xext ext = Xext.INSTANCE;
Display dpy = x11.XOpenDisplay(null);
if (dpy == null)
return;
Pixmap pm = null;
try {
X11.Window win = getDrawable(w);
if (raster == null
|| ((pm = createBitmap(dpy, win, w, raster)) == null)) {
ext.XShapeCombineMask(dpy, win,
X11.Xext.ShapeBounding,
0, 0, Pixmap.None,
X11.Xext.ShapeSet);
}
else {
ext.XShapeCombineMask(dpy, win,
X11.Xext.ShapeBounding, 0, 0,
pm, X11.Xext.ShapeSet);
}
}
finally {
if (pm != null) {
x11.XFreePixmap(dpy, pm);
}
x11.XCloseDisplay(dpy);
}
setForceHeavyweightPopups(w, raster != null);
}
};
whenDisplayable(w, action);
}
}
/**
* Applies the given mask to the given window. Does nothing if the
* operation is not supported. The mask is treated as a bitmap and
* ignores transparency.
*/
public static void setWindowMask(Window w, Shape mask) {
getInstance().setWindowMask(w, mask);
}
/**
* Applies the given mask to the given window. Does nothing if the
* operation is not supported. The mask is treated as a bitmap and
* ignores transparency.
*/
public static void setWindowMask(Window w, Icon mask) {
getInstance().setWindowMask(w, mask);
}
/** Indicate a window can have a global alpha setting. */
public static boolean isWindowAlphaSupported() {
return getInstance().isWindowAlphaSupported();
}
/**
* Returns a {@link GraphicsConfiguration} comptible with alpha
* compositing.
*/
public static GraphicsConfiguration getAlphaCompatibleGraphicsConfiguration() {
return getInstance().getAlphaCompatibleGraphicsConfiguration();
}
/**
* Set the overall window transparency. An alpha of 1.0 is fully
* opaque, 0.0 fully transparent. The alpha level is applied equally
* to all window pixels.<p>
* NOTE: Windows requires that <code>sun.java2d.noddraw=true</code>
* in order for alpha to work.
*/
public static void setWindowAlpha(Window w, float alpha) {
getInstance().setWindowAlpha(w, Math.max(0f, Math.min(alpha, 1f)));
}
/**
* Set the window to be transparent. Only explicitly painted pixels
* will be non-transparent. All pixels will be composited with
* whatever is under the window using their alpha values.
*/
public static void setWindowTransparent(Window w, boolean transparent) {
getInstance().setWindowTransparent(w, transparent);
}
} |
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import util.MyProperties;
public class ProducerMain
{
public static void main(String[] args)
{
//Properties for initializing the Kafka producer
MyProperties myProperties1 = new MyProperties();
myProperties1.loadProperties("src/main/resources/myproducer_clicks.properties");
Producer<String, String> prod1 = new KafkaProducer<>(myProperties1);
MyProperties myProperties2 = new MyProperties();
myProperties2.loadProperties("src/main/resources/myproducer_im.properties");
Producer<String, String> prod2 = new KafkaProducer<>(myProperties2);
MyProperties myProperties3 = new MyProperties();
myProperties3.loadProperties("src/main/resources/myproducer_st.properties");
Producer<String, String> prod3 = new KafkaProducer<>(myProperties3);
//CSV files downloaded from S3
String clicks_path = "/home/hadoop-user/Data_sets/clicks_1.csv";
String impression_path = "/home/hadoop-user/Data_sets/im.csv";
String site_analytics = "/home/hadoop-user/Data_sets/ste.csv";
//Topics for kafka producer
String topic_clicks= "cltest";
String topic_impressions ="imtest";
String topic_site="sitecl";
//Intitalizing object of MyProducer class containing the code for producer implementation
MyProducer pr1 = new MyProducer();
MyProducer pr2 = new MyProducer();
MyProducer pr3 = new MyProducer();
//Start the Kafka producer using the above mentioned topics
pr1.produce(topic_clicks,clicks_path,prod1);
pr2.produce(topic_impressions,impression_path,prod2);
pr3.produce(topic_site,site_analytics,prod3);
}
} |
package battle;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Unit implements Subscriber {
/**
* The name of the Unit.
*/
private final String name;
/**
* The Row this Unit starts battles in.
*/
private Row battleRow;
/**
* The list of all the Skill objects the Unit can execute in battle.
*/
private final Collection<Skill> skillList;
/**
* The list of all the Status objects the Unit has.
*/
private final Collection<Status> statusList;
/**
* The list of TurnItem objects the Unit has inserted into the TurnOrder.
*/
private final Collection<TurnItem> turnItems;
/**
* The TurnOrder that the Unit subscribes to for updates and that the Unit
* submits its TurnItems to.
*/
private TurnOrder turnOrder;
/**
* The time value representing the last time the Unit received a request to
* update.
*/
private int lastUpdated;
/**
* Basic constructor.
* @param name name of the Unit.
*/
public Unit(String name) {
this.name = name;
this.battleRow = Row.FRONT;
this.skillList = new ArrayList<>();
this.statusList = new ArrayList<>();
this.turnItems = new ArrayList<>();
this.lastUpdated = 0;
}
/**
* Adds a new Skill to the Unit object's list of Skill objects.
* @param newSkill Skill to be added to the Unit.
*/
public void addSkill(Skill newSkill) {
skillList.add(newSkill);
}
/**
* Adds a new status to the unit's list of Status objects.
* @param newStatus Status to be added to the Unit.
* @return true if the addition was successful.
*/
public boolean addStatus(Status newStatus) {
if ((newStatus != null) && newStatus.onApply(this)) {
int oldStunDuration = getStunDuration();
if (newStatus.getDuration() != 0) {
Status match = getStatus(newStatus.getName());
if (match != null) {
if (match.isStackable() && newStatus.isStackable()) {
match.setStacks(match.getStacks() + newStatus.getStacks());
}
else if ((match.getDuration() > 0) && (newStatus.getDuration() > 0)) {
int newDuration = match.getDuration() + newStatus.getDuration();
match.setDuration(newDuration);
turnItems.add(turnOrder.addTurnItem(this, newDuration, false));
}
}
else {
statusList.add(newStatus);
if (newStatus.getDuration() > 0) {
turnItems.add(turnOrder.addTurnItem(this, newStatus.getDuration(), false));
}
}
}
int stunDurationChange = getStunDuration() - oldStunDuration;
if (stunDurationChange != 0) {
for (TurnItem nextItem : turnItems) {
if (nextItem.isStunnable()) {
nextItem.setTime(nextItem.getTime().plus(Duration.ofMillis(stunDurationChange)));
}
}
for (Skill nextSkill : skillList) {
if (nextSkill.getMaxCooldown() > 0) {
nextSkill.setCooldown(nextSkill.getCooldown() + stunDurationChange);
}
}
}
return true;
}
return false;
}
/**
* Clears all battle related values.
*/
protected void clearBattleState() {
clearStatus();
if (turnOrder != null) {
turnOrder.removeUnit(this);
turnOrder.unsubscribe(this);
turnOrder = null;
}
turnItems.removeAll(turnItems);
for (Skill nextSkill : skillList) {
nextSkill.setCooldown(nextSkill.getMaxCooldown());
}
}
/**
* Removes all Status objects without calling the onRemove events.
*/
public void clearStatus() {
statusList.removeAll(statusList);
}
/**
* Getter for what place within a team this unit prefers to reside.
* @return Row value that the Unit starts battle in.
*/
public Row getStartingRow() {
return battleRow;
}
/**
* Getter for the name of the unit.
* @return name of the unit.
*/
public String getName() {
return name;
}
/**
* Getter for all the skills of the unit in the form of an iterator.
* @return iterator of the Unit object's skills.
*/
public Iterator<Skill> getSkills() {
return skillList.iterator();
}
/**
* Returns a Status object with the matching Status value as the given Status.
* @param status the object who's value is being match to a Status owned by
* the Unit.
* @return Status object with the matching Status value as the given Status.
* Returns null if no match was found.
*/
public Status getStatus(Status status) {
return getStatus(status.getName());
}
/**
* Checks to see if the unit has a status who's type matches the type passed
* by the caller and returns the first match.
* @param statusName the enumerated value of a Status being searched for.
* @return the Status object matching value given. Returns null if no match
* was found.
*/
public Status getStatus(String statusName) {
Iterator<Status> iterateStatus = getStatuses();
while (iterateStatus.hasNext()) {
Status nextStatus = iterateStatus.next();
if (nextStatus.getName().equals(statusName)) {
return nextStatus;
}
}
//Return null if the search failed to find a match.
return null;
}
/**
* Getter for all Status objects possessed by the Unit returned as an
* iterator.
* @return iterator of the Unit object's Status objects.
*/
public Iterator<Status> getStatuses() {
return statusList.iterator();
}
/**
* Returns true if the Unit has a Status object with the matching
* StatusLibrary value as the status given.
* @param status the object who's value matches the Status searched for.
* @return true if a match was found.
*/
public boolean hasStatus(Status status) {
if (status != null) {
return getStatus(status.getName()) != null;
}
return false;
}
/**
* Returns true if the Unit has a Status object with the matching given
* StatusLibrary value.
* @param statusName the value that matches the Status being searched for.
* @return true if a match was found.
*/
public boolean hasStatus(String statusName) {
return getStatus(statusName) != null;
}
/**
* Returns true when the Unit has a Status that would remove it from combat.
* @return true when the Unit is removed from combat.
*/
public boolean isDefeated() {
for (Status nextStatus : statusList) {
if (nextStatus.isDefeating()) {
return true;
}
}
return false;
}
/**
* Returns true when the Unit has a Status that stuns it.
* @return true when the Unit is stunned.
*/
public boolean isStunned() {
for (Status nextStatus : statusList) {
if (nextStatus.isStunning()) {
return true;
}
}
return false;
}
/**
* Iterates through the list of Status object's and returns the duration of
* the longest Status that stuns.
* @return duration the Unit is stunned.
*/
private int getStunDuration() {
int stunTime = 0;
for (Status nextStatus : statusList) {
if (nextStatus.isStunning()) {
if (stunTime < nextStatus.getDuration()) {
stunTime = nextStatus.getDuration();
}
}
}
return stunTime;
}
/**
* Returns the next Skill in the priority that is off its cooldown, or null if
* their is no Skill that is ready.
* @return Skill object ready for execution. Returns null if there is no Skill
* available.
*/
protected Skill nextSkill() {
if (!isStunned()) {
Iterator<Skill> iterateSkills = skillList.iterator();
while (iterateSkills.hasNext()) {
Skill nextSkill = iterateSkills.next();
if ((nextSkill.getMaxCooldown() > 0) && (nextSkill.getCooldown() <= 0)) {
return nextSkill;
}
}
}
return null;
}
/**
* Removes a Status object from the list of Status objects applied to this
* character. The Status given in the search must be a precise reference to
* the object being removed.
* @param oldStatus object being searched for and removed from the Unit.
* @return true if the Status was successfully removed.
*/
protected boolean removeStatus(Status oldStatus) {
if (statusList.contains(oldStatus) && oldStatus.onRemove(this)) {
return statusList.remove(oldStatus);
}
return false;
}
/**
* Removes a Status object from the list of Status objects applied to this
* character. The Status given in the search must be a precise reference to
* the object being removed.
* @param oldStatus object being searched for and removed from the Unit.
* @return true if the Status was successfully removed.
*/
public boolean removeStatus(String oldStatus) {
Status match = getStatus(oldStatus);
if ((match != null) && match.onRemove(this)) {
return statusList.remove(match);
}
return false;
}
/**
* Removes a specified number of stacks of a Status object from the list of
* Status objects applied to this Unit. The Status object is identified by
* the enumerated StatusLibrary value passed by the caller. The onRemove event
* is triggered before stack decrement. A failed removal results in no changes
* to the statuses state.
* @param oldStatus enumerated value of the Status being searched for.
* @param stacks number of stacks to remove from any Status matching the
* Status value being searched for.
* @return true if the status was successfully removed.
*/
public boolean removeStatus(String oldStatus, int stacks) {
Status match = getStatus(oldStatus);
if ((stacks > 0) && (match != null) && match.onRemove(this)) {
if (match.getStacks() <= stacks) {
statusList.remove(match);
}
else {
match.setStacks(match.getStacks() - stacks);
}
return true;
}
return false;
}
/**
* Removes a Skill from the Unit and returns true if the removal is
* successful.
* @param oldSkill reference to the skill being removed.
* @return true if removal of the skill is successful.
*/
public boolean removeSkill(Skill oldSkill) {
return skillList.remove(oldSkill);
}
/**
* Removes a point in time of a battle. This should be called whenever this
* time point has been passed, or the battle is over.
* @param oldItem TurnItem to be searched for and removed.
*/
protected void removeTurnItem(TurnItem oldItem) {
turnItems.remove(oldItem);
}
/**
* Resets the cooldown on the given Skill and places the Unit into the
* TurnOrder at the time the Skill goes off cooldown again. Returns false if
* the Unit does not possess the given skill.
* @param skill Skill to be searched for and reset.
* @return true if the Skill belongs to the Unit.
*/
protected boolean resetSkill(Skill skill) {
if ((skill != null) && (skillList.contains(skill))) {
skill.setCooldown(skill.getMaxCooldown());
turnItems.add(turnOrder.addTurnItem(this, skill.getCooldown(), true));
return true;
}
return false;
}
/**
* Informs the Unit that it is in a new battle. All previous battle states are
* lost and the Unit is given new information in order to submit its own
* TurnItem objects.
* @param turnOrder the object that the Unit uses to submit its TurnItems to.
*/
protected void setBattleState(TurnOrder turnOrder) {
clearBattleState();
this.turnOrder = turnOrder;
this.turnOrder.subscribe(this);
for (Skill nextSkill : skillList) {
if (nextSkill.getCooldown() > 0) {
turnItems.add(turnOrder.addTurnItem(this, nextSkill.getCooldown(), true));
}
}
lastUpdated = turnOrder.getClock();
}
/**
* Setter for what Row within a Team this Unit starts a battle in.
* @param battleRow Row value Unit will start a battle in.
*/
public void setStartingRow(Row battleRow) {
this.battleRow = battleRow;
}
@Override public String toString() {
return name;
}
@Override public void update() {
int timeChange = turnOrder.getClock() - lastUpdated;
lastUpdated = turnOrder.getClock();
Iterator<Status> iterateStatuses = statusList.iterator();
while (iterateStatuses.hasNext()) {
Status nextStatus = iterateStatuses.next();
if (nextStatus.getDuration() >= 0) {
nextStatus.setDuration(nextStatus.getDuration() - timeChange);
if (nextStatus.getDuration() <= 0) {
if (nextStatus.onRemove(this)) {
iterateStatuses.remove();
}
else {
nextStatus.setDuration(0);
}
}
}
}
Iterator<Skill> iterateSkills = skillList.iterator();
while (iterateSkills.hasNext()) {
Skill s = iterateSkills.next();
s.setCooldown(s.getCooldown() - timeChange);
}
}
} |
package YOUR_PACKAGE_NAME;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.applovin.adview.AppLovinIncentivizedInterstitial;
import com.applovin.sdk.AppLovinAd;
import com.applovin.sdk.AppLovinAdClickListener;
import com.applovin.sdk.AppLovinAdDisplayListener;
import com.applovin.sdk.AppLovinAdLoadListener;
import com.applovin.sdk.AppLovinAdRewardListener;
import com.applovin.sdk.AppLovinAdVideoPlaybackListener;
import com.applovin.sdk.AppLovinErrorCodes;
import com.applovin.sdk.AppLovinSdk;
import com.mopub.common.LifecycleListener;
import com.mopub.common.MoPubReward;
import com.mopub.mobileads.CustomEventRewardedVideo;
import com.mopub.mobileads.MoPubErrorCode;
import com.mopub.mobileads.MoPubRewardedVideoManager;
import java.util.Map;
import static android.util.Log.DEBUG;
import static android.util.Log.ERROR;
// Please note: We have renamed this class from "AppLovinRewardedAdapter" to "AppLovinCustomEventRewardedVideo".
// If this is your first time integrating, please use "YOUR_PACKAGE_NAME.AppLovinCustomEventRewardedVideo" as the custom event classname in the MoPub dashboard.
// If you have integrated this before, please rename this class back to "AppLovinRewardedAdapter" and use "YOUR_PACKAGE_NAME.AppLovinRewardedAdapter" as the custom event classname in the MoPub dashboard.
public class AppLovinCustomEventRewardedVideo
extends CustomEventRewardedVideo
implements AppLovinAdLoadListener, AppLovinAdDisplayListener, AppLovinAdClickListener, AppLovinAdVideoPlaybackListener, AppLovinAdRewardListener
{
private static final boolean LOGGING_ENABLED = true;
private static boolean initialized;
private AppLovinIncentivizedInterstitial incentivizedInterstitial;
private Activity parentActivity;
private boolean fullyWatched;
private MoPubReward reward;
// MoPub Custom Event Methods
@Override
protected boolean checkAndInitializeSdk(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception
{
log( DEBUG, "Initializing AppLovin rewarded video..." );
if ( !initialized )
{
AppLovinSdk.initializeSdk( activity );
AppLovinSdk.getInstance( activity ).setPluginVersion( "MoPub-2.0" );
initialized = true;
return true;
}
return false;
}
@Override
protected void loadWithSdkInitialized(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception
{
log( DEBUG, "Requesting AppLovin rewarded video with serverExtras: " + serverExtras );
parentActivity = activity;
if ( hasVideoAvailable() )
{
MoPubRewardedVideoManager.onRewardedVideoLoadSuccess( AppLovinCustomEventRewardedVideo.class, "" );
}
else
{
getIncentivizedInterstitial().preload( this );
}
}
@Override
protected void showVideo()
{
if ( hasVideoAvailable() )
{
fullyWatched = false;
reward = null;
getIncentivizedInterstitial().show( parentActivity, null, this, this, this, this );
}
else
{
log( ERROR, "Failed to show an AppLovin rewarded video before one was loaded" );
MoPubRewardedVideoManager.onRewardedVideoPlaybackError( AppLovinCustomEventRewardedVideo.class, "", MoPubErrorCode.VIDEO_PLAYBACK_ERROR );
}
}
@Override
protected boolean hasVideoAvailable()
{
return getIncentivizedInterstitial().isAdReadyToDisplay();
}
@Override
@Nullable
protected LifecycleListener getLifecycleListener() { return null; }
@Override
@NonNull
protected String getAdNetworkId() { return ""; }
@Override
protected void onInvalidate() {}
// Ad Load Listener
@Override
public void adReceived(final AppLovinAd ad)
{
log( DEBUG, "Rewarded video did load ad: " + ad.getAdIdNumber() );
MoPubRewardedVideoManager.onRewardedVideoLoadSuccess( AppLovinCustomEventRewardedVideo.class, "" );
}
@Override
public void failedToReceiveAd(final int errorCode)
{
log( DEBUG, "Rewarded video failed to load with error: " + errorCode );
MoPubRewardedVideoManager.onRewardedVideoLoadFailure( AppLovinCustomEventRewardedVideo.class, "", toMoPubErrorCode( errorCode ) );
}
// Ad Display Listener
@Override
public void adDisplayed(final AppLovinAd ad)
{
log( DEBUG, "Rewarded video displayed" );
MoPubRewardedVideoManager.onRewardedVideoStarted( AppLovinCustomEventRewardedVideo.class, "" );
}
@Override
public void adHidden(final AppLovinAd ad)
{
log( DEBUG, "Rewarded video dismissed" );
if ( fullyWatched && reward != null )
{
MoPubRewardedVideoManager.onRewardedVideoCompleted( AppLovinCustomEventRewardedVideo.class, "", reward );
}
MoPubRewardedVideoManager.onRewardedVideoClosed( AppLovinCustomEventRewardedVideo.class, "" );
}
// Ad Click Listener
@Override
public void adClicked(final AppLovinAd ad)
{
log( DEBUG, "Rewarded video clicked" );
MoPubRewardedVideoManager.onRewardedVideoClicked( AppLovinCustomEventRewardedVideo.class, "" );
}
// Video Playback Listener
@Override
public void videoPlaybackBegan(final AppLovinAd ad)
{
log( DEBUG, "Rewarded video playback began" );
}
@Override
public void videoPlaybackEnded(final AppLovinAd ad, final double percentViewed, final boolean fullyWatched)
{
log( DEBUG, "Rewarded video playback ended at playback percent: " + percentViewed );
this.fullyWatched = fullyWatched;
}
// Reward Listener
@Override
public void userOverQuota(final AppLovinAd appLovinAd, final Map map)
{
log( ERROR, "Rewarded video validation request for ad did exceed quota with response: " + map );
}
@Override
public void validationRequestFailed(final AppLovinAd appLovinAd, final int errorCode)
{
log( ERROR, "Rewarded video validation request for ad failed with error code: " + errorCode );
}
@Override
public void userRewardRejected(final AppLovinAd appLovinAd, final Map map)
{
log( ERROR, "Rewarded video validation request was rejected with response: " + map );
}
@Override
public void userDeclinedToViewAd(final AppLovinAd appLovinAd)
{
log( DEBUG, "User declined to view rewarded video" );
MoPubRewardedVideoManager.onRewardedVideoClosed( this.getClass(), "" );
}
@Override
public void userRewardVerified(final AppLovinAd appLovinAd, final Map map)
{
final String currency = (String) map.get( "currency" );
final int amount = (int) Double.parseDouble( (String) map.get( "amount" ) ); // AppLovin returns amount as double
log( DEBUG, "Rewarded " + amount + " " + currency );
reward = MoPubReward.success( currency, amount );
}
// Incentivized Ad Getter
private AppLovinIncentivizedInterstitial getIncentivizedInterstitial()
{
if ( incentivizedInterstitial == null )
{
incentivizedInterstitial = AppLovinIncentivizedInterstitial.create( parentActivity );
}
return incentivizedInterstitial;
}
// Utility Methods
private static void log(final int priority, final String message)
{
if ( LOGGING_ENABLED )
{
Log.println( priority, "AppLovinRewardedVideo", message );
}
}
private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode)
{
if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL )
{
return MoPubErrorCode.NETWORK_NO_FILL;
}
else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR )
{
return MoPubErrorCode.NETWORK_INVALID_STATE;
}
else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK )
{
return MoPubErrorCode.NO_CONNECTION;
}
else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT )
{
return MoPubErrorCode.NETWORK_TIMEOUT;
}
else
{
return MoPubErrorCode.UNSPECIFIED;
}
}
} |
package com.letscode.lcg.screens;
import net.engio.mbassy.listener.Handler;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.letscode.lcg.Context;
import com.letscode.lcg.actor.Board;
import com.letscode.lcg.actor.FieldActor;
import com.letscode.lcg.enums.ActionCost;
import com.letscode.lcg.enums.BuildMode;
import com.letscode.lcg.enums.BuildingGoldCost;
import com.letscode.lcg.enums.CommandType;
import com.letscode.lcg.model.Field;
import com.letscode.lcg.network.Events;
import com.letscode.lcg.network.messages.EndGameMessage;
import com.letscode.lcg.network.messages.MoveDoneMessage;
import com.letscode.lcg.network.messages.MoveMessage;
import com.letscode.lcg.network.messages.NextPlayerMessage;
import com.letscode.lcg.network.messages.YourTurnMessage;
import com.letscode.ui.BaseScreen;
import com.letscode.ui.UiApp;
public class PlayScreen extends BaseScreen {
Context context;
Button endTurnButton;
Button buildTownhallButton, buildGoldmineButton, buildBarricadeButton;
Label actionPointsValueLabel, goldValueLabel, turnPlayerLabel;
Board board;
public PlayScreen(Context context) {
super(context.app);
this.context = context;
UiApp app = context.app;
Events.subscribe(this);
buildTownhallButton = new TextButton("Townhall", app.skin);
buildGoldmineButton = new TextButton("Goldmine", app.skin);
buildBarricadeButton = new TextButton("Barricade", app.skin);
Label actionPointsLabel = new Label("Action Points:", app.skin);
actionPointsValueLabel = new Label("0", app.skin);
Label goldLabel = new Label("Gold: ", app.skin);
goldValueLabel = new Label("0", app.skin);
Table statsTable = new Table(app.skin);
statsTable.add(actionPointsLabel);
statsTable.add(actionPointsValueLabel);
statsTable.row();
statsTable.add(goldLabel);
statsTable.add(goldValueLabel);
mainTable.add(statsTable);
// Setup things about player's turn
Table turnTable = new Table(app.skin);
turnPlayerLabel = new Label("hgw", app.skin);
turnPlayerLabel.setAlignment(Align.center);
setTurnPlayerLabel(context.network.getClientNickname());
endTurnButton = new TextButton("End turn", app.skin);
endTurnButton.addListener(endTurnButtonListener);
endTurnButton.setVisible(false);
turnTable.add(turnPlayerLabel).expandX().fill();
turnTable.row();
turnTable.add(endTurnButton).spaceTop(20);
mainTable.add(turnTable).expandX().fill();
// Setup build buttons
Table buttonsTable = new Table(app.skin);
buildTownhallButton = new TextButton("Townhall", app.skin);
buildTownhallButton.addListener(buildTownhallButtonListener);
buildGoldmineButton = new TextButton("Goldmine", app.skin);
buildGoldmineButton.addListener(buildGoldmineButtonListener);
buildBarricadeButton = new TextButton("Barricade", app.skin);
buildBarricadeButton.addListener(buildBarricadeButtonListener);
buttonsTable.add(buildTownhallButton);
buttonsTable.add(buildGoldmineButton);
buttonsTable.add(buildBarricadeButton);
mainTable.add(buttonsTable);
// Setup game board
board = new Board(context);
mainTable.row();
Table boardTable = new Table(app.skin);
boardTable.setBackground(app.skin.getDrawable("window1"));
boardTable.setColor(Color.valueOf("C5D8C5"));
boardTable.add(board).expand().fill();
mainTable.add(boardTable).expand().fill().colspan(3);
mainTable.layout();
board.init();
board.addListener(boardListener);
context.app.setClearColor(Color.valueOf("9EAE9E"));
}
private void setBuildMode(BuildMode buildMode) {
context.currentBuildMode = buildMode;
buildTownhallButton.setDisabled(true);
buildTownhallButton.setChecked(buildMode == BuildMode.Townhall);
buildTownhallButton.setDisabled(false);
buildGoldmineButton.setDisabled(true);
buildGoldmineButton.setChecked(buildMode == BuildMode.Goldmine);
buildGoldmineButton.setDisabled(false);
buildBarricadeButton.setDisabled(true);
buildBarricadeButton.setChecked(buildMode == BuildMode.Barricade);
buildBarricadeButton.setDisabled(false);
}
private void setTurnPlayerLabel(String playerName) {
boolean thisPlayerMoves = playerName.equals(context.getPlayerNickname());
String labelText = thisPlayerMoves ? "Now you move!" : (playerName != null ? playerName : "");
turnPlayerLabel.setText(labelText);
turnPlayerLabel.setColor(context.colorsForPlayers.get(playerName));
}
/**
* Checks if move is possible and then it's being made.
*
* @param fieldActor
*/
private void tryToMakeMove(FieldActor fieldActor) {
CommandType commandType = null;
boolean shouldSendCommand = false;
int rowIndex = fieldActor.getRowIndex();
int colIndex = fieldActor.getColIndex();
Field field = context.map.getField(rowIndex, colIndex);
String thisPlayerName = context.getPlayerNickname();
boolean isOwnedByPlayer = context.map.isFieldOwnedBy(thisPlayerName, rowIndex, colIndex);
boolean canPlayerBuildOnField = isOwnedByPlayer && field.building == null;
int currentActionPoints = Integer.parseInt(actionPointsValueLabel.getText().toString());
int currentGold = Integer.parseInt(goldValueLabel.getText().toString());
if (context.currentBuildMode == BuildMode.None) {
if (!isOwnedByPlayer) {
commandType = CommandType.conquer;
shouldSendCommand = context.map.canPlayerAttackField(thisPlayerName, rowIndex, colIndex)
&& currentActionPoints >= ActionCost.CONQUER_EMPTY_FIELD;
if (shouldSendCommand) {
field.owner = thisPlayerName;
currentActionPoints -= ActionCost.CONQUER_EMPTY_FIELD;
}
}
else if (field.type == Field.TYPE_GOLD && currentActionPoints >= ActionCost.BUILD_MINE) {
commandType = CommandType.mine_gold;
shouldSendCommand = true;
field.building = Field.BUILDING_GOLDMINE;
currentActionPoints -= ActionCost.BUILD_MINE;
}
}
else if (context.currentBuildMode == BuildMode.Townhall) {
commandType = CommandType.build_townhall;
shouldSendCommand = canPlayerBuildOnField
&& currentActionPoints >= ActionCost.BUILD_TOWNHALL
&& currentGold >= BuildingGoldCost.TOWNHALL;
if (shouldSendCommand) {
field.building = Field.BUILDING_TOWNHALL;
currentActionPoints -= ActionCost.BUILD_TOWNHALL;
currentGold -= BuildingGoldCost.TOWNHALL;
setBuildMode(BuildMode.None);
}
}
else if (context.currentBuildMode == BuildMode.Goldmine) {
commandType = CommandType.build_mine;
shouldSendCommand = canPlayerBuildOnField
&& currentActionPoints >= ActionCost.BUILD_MINE
&& currentGold >= BuildingGoldCost.GOLDMINE;
if (shouldSendCommand) {
field.building = Field.BUILDING_GOLDMINE;
currentActionPoints -= ActionCost.BUILD_MINE;
currentGold -= BuildingGoldCost.GOLDMINE;
setBuildMode(BuildMode.None);
}
}
else if (context.currentBuildMode == BuildMode.Barricade) {
commandType = CommandType.build_barricade;
shouldSendCommand = canPlayerBuildOnField
&& currentActionPoints >= ActionCost.BUILD_BARRICADE
&& currentGold >= BuildingGoldCost.BARRICADE;
if (shouldSendCommand) {
field.building = Field.BUILDING_BARRICADE;
currentActionPoints -= ActionCost.BUILD_BARRICADE;
currentGold -= BuildingGoldCost.BARRICADE;
setBuildMode(BuildMode.None);
}
}
if (shouldSendCommand) {
actionPointsValueLabel.setText(new Integer(currentActionPoints).toString());
goldValueLabel.setText(new Integer(currentGold).toString());
context.network.sendMakeMoveMessage(rowIndex, colIndex, commandType);
}
}
private void updateGoldAndActionPoints(int actionPoints, int gold) {
actionPointsValueLabel.setText(Integer.toString(actionPoints));
goldValueLabel.setText(Integer.toString(gold));
}
// Network Events
@Handler
public void moveHandler(MoveMessage message) {
System.out.println(message);
}
@Handler
public void nextPlayerHandler(NextPlayerMessage message) {
setTurnPlayerLabel(message.nickname);
}
@Handler
public void yourTurnHandler(YourTurnMessage message) {
endTurnButton.setVisible(true);
updateGoldAndActionPoints(message.actionPoints, message.gold);
}
@Handler
public void endGameMessage(EndGameMessage message) {
System.out.println(message);
}
@Handler
public void moveDoneHandler(MoveDoneMessage message) {
updateGoldAndActionPoints(message.actionPoints, message.gold);
}
// GUI Events
ClickListener buildTownhallButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
setBuildMode(buildTownhallButton.isChecked() ? BuildMode.Townhall : BuildMode.None);
super.clicked(event, x, y);
}
};
ClickListener buildGoldmineButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
setBuildMode(buildGoldmineButton.isChecked() ? BuildMode.Goldmine : BuildMode.None);
super.clicked(event, x, y);
}
};
ClickListener buildBarricadeButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
setBuildMode(buildBarricadeButton.isChecked() ? BuildMode.Barricade : BuildMode.None);
super.clicked(event, x, y);
}
};
EventListener boardListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Actor actor = event.getTarget() instanceof FieldActor ? (FieldActor) event.getTarget() : null;
if (actor != null) {
if (actor instanceof FieldActor) {
FieldActor fieldActor = (FieldActor)actor;
fieldActor.animateTouched();
if (fieldActor.getField() != null) {
tryToMakeMove(fieldActor);
}
}
}
};
};
ClickListener endTurnButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
context.network.sendEndTurnMessage();
endTurnButton.setVisible(false);
}
};
@Override
public void act(float delta) {
super.act(delta);
context.network.update();
}
@Override
public void onBackPress() {}
} |
package com.opengamma.engine.depgraph;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.depgraph.DependencyGraphBuilder.GraphBuildingContext;
import com.opengamma.engine.function.ParameterizedFunction;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
/**
* Handles callback notifications of terminal values to populate a graph set.
*/
/* package */class GetTerminalValuesCallback implements ResolvedValueCallback {
private static final Logger s_logger = LoggerFactory.getLogger(GetTerminalValuesCallback.class);
private static final AtomicInteger s_nextDebugId = new AtomicInteger();
private interface DependencyNodeCallback {
void node(DependencyNode node);
}
private interface DependencyNodeProducer {
void getNode(DependencyNodeCallback callback);
}
private final Map<ValueSpecification, DependencyNode> _spec2Node = new HashMap<ValueSpecification, DependencyNode>();
private final Map<ParameterizedFunction, Map<ComputationTarget, Set<DependencyNodeProducer>>> _func2target2nodes =
new HashMap<ParameterizedFunction, Map<ComputationTarget, Set<DependencyNodeProducer>>>();
private final Collection<DependencyNode> _graphNodes = new ArrayList<DependencyNode>();
private final Map<ValueRequirement, ValueSpecification> _resolvedValues = new HashMap<ValueRequirement, ValueSpecification>();
private ResolutionFailureVisitor _failureVisitor;
public GetTerminalValuesCallback(final ResolutionFailureVisitor failureVisitor) {
_failureVisitor = failureVisitor;
}
public void setResolutionFailureVisitor(final ResolutionFailureVisitor failureVisitor) {
_failureVisitor = failureVisitor;
}
@Override
public void failed(final GraphBuildingContext context, final ValueRequirement value, final ResolutionFailure failure) {
s_logger.error("Couldn't resolve {}", value);
if (failure != null) {
if (_failureVisitor != null) {
failure.accept(_failureVisitor);
}
// TODO: check context settings; does the user want all of the failure information in the exceptions?
context.exception(new UnsatisfiableDependencyGraphException(failure));
} else {
s_logger.warn("No failure state for {}", value);
context.exception(new UnsatisfiableDependencyGraphException(value));
}
}
private synchronized Set<DependencyNodeProducer> getOrCreateNodes(final ParameterizedFunction function, final ComputationTarget target) {
Map<ComputationTarget, Set<DependencyNodeProducer>> target2nodes = _func2target2nodes.get(function);
if (target2nodes == null) {
target2nodes = new HashMap<ComputationTarget, Set<DependencyNodeProducer>>();
_func2target2nodes.put(function, target2nodes);
}
Set<DependencyNodeProducer> nodes = target2nodes.get(target);
if (nodes == null) {
nodes = new HashSet<DependencyNodeProducer>();
target2nodes.put(target, nodes);
}
return nodes;
}
private static boolean mismatchUnionImpl(final Set<ValueSpecification> as, final Set<ValueSpecification> bs) {
for (ValueSpecification a : as) {
if (bs.contains(a)) {
// Exact match
continue;
}
for (ValueSpecification b : bs) {
if (a.getValueName() == b.getValueName()) {
// Match the name, but other data wasn't exact so reject
return true;
}
}
}
return false;
}
private static boolean mismatchUnion(final Set<ValueSpecification> as, final Set<ValueSpecification> bs) {
return mismatchUnionImpl(as, bs) || mismatchUnionImpl(bs, as);
}
private final class NodeInputProduction {
private final ResolvedValue _resolvedValue;
private final DependencyNodeCallback _result;
private final boolean _isNew;
private int _count = 2;
private DependencyNode _node;
public NodeInputProduction(final ResolvedValue resolvedValue, final DependencyNode node, final DependencyNodeCallback result, final boolean isNew) {
_resolvedValue = resolvedValue;
_node = node;
_result = result;
_isNew = isNew;
}
public synchronized void addProducer() {
_count++;
}
public void failed() {
final boolean done;
synchronized (this) {
_node = null;
done = (--_count == 0);
}
if (done) {
_result.node(null);
}
}
public void completed() {
final boolean done;
final DependencyNode node;
synchronized (this) {
node = _node;
done = (--_count == 0);
}
if (done) {
if (node != null) {
nodeProduced(_resolvedValue, node, _result, _isNew);
} else {
s_logger.warn("Couldn't produce node for {}", _resolvedValue);
_result.node(null);
}
}
}
}
private void nodeProduced(final ResolvedValue resolvedValue, final DependencyNode node, final DependencyNodeCallback result, final boolean isNew) {
synchronized (this) {
s_logger.debug("Adding {} to graph set", node);
_spec2Node.put(resolvedValue.getValueSpecification(), node);
if (isNew) {
_graphNodes.add(node);
}
}
result.node(node);
}
private static final class FindExistingNodes implements DependencyNodeCallback, DependencyNodeProducer {
private final ResolvedValue _resolvedValue;
private int _pending;
private DependencyNode _found;
private DependencyNodeCallback _callback;
public FindExistingNodes(final ResolvedValue resolvedValue, final Set<DependencyNodeProducer> nodes) {
_resolvedValue = resolvedValue;
synchronized (nodes) {
_pending = nodes.size();
for (DependencyNodeProducer node : nodes) {
node.getNode(this);
}
}
}
public synchronized boolean isDeferred() {
assert _callback == null;
return _pending > 0;
}
public synchronized DependencyNode getNode() {
assert _pending == 0;
assert _callback == null;
return _found;
}
@Override
public void node(final DependencyNode node) {
DependencyNodeCallback callback = null;
synchronized (this) {
_pending
if (_found == null) {
if (node != null) {
if (mismatchUnion(node.getOutputValues(), _resolvedValue.getFunctionOutputs())) {
s_logger.debug("Can't reuse {} for {}", node, _resolvedValue);
} else {
s_logger.debug("Reusing {} for {}", node, _resolvedValue);
_found = node;
callback = _callback;
}
}
}
}
if (callback != null) {
callback.node(_found);
}
}
@Override
public void getNode(final DependencyNodeCallback callback) {
synchronized (this) {
assert _callback == null;
if ((_found == null) && (_pending > 0)) {
_callback = callback;
return;
}
}
callback.node(_found);
}
}
private static final class PublishNode implements DependencyNodeProducer, DependencyNodeCallback {
private final DependencyNodeCallback _underlying;
private DependencyNode _node;
private Collection<DependencyNodeCallback> _callbacks = new LinkedList<DependencyNodeCallback>();
public PublishNode(final DependencyNodeCallback underlying) {
_underlying = underlying;
}
@Override
public void node(final DependencyNode node) {
_underlying.node(node);
final Collection<DependencyNodeCallback> callbacks;
synchronized (this) {
_node = node;
if (_callbacks == null) {
return;
}
if (_callbacks.isEmpty()) {
callbacks = Collections.emptyList();
} else {
callbacks = new ArrayList<DependencyNodeCallback>(_callbacks);
}
_callbacks = null;
}
for (DependencyNodeCallback callback : callbacks) {
callback.node(node);
}
}
@Override
public void getNode(final DependencyNodeCallback callback) {
final DependencyNode node;
synchronized (this) {
if (_callbacks != null) {
_callbacks.add(callback);
return;
}
node = _node;
}
callback.node(node);
}
}
private void getOrCreateNode(final GraphBuildingContext context, final ValueRequirement valueRequirement, final ResolvedValue resolvedValue, final Set<ValueSpecification> downstream,
final DependencyNodeCallback result, final DependencyNode node, final boolean nodeIsNew) {
final int debugId = s_nextDebugId.incrementAndGet();
for (ValueSpecification output : resolvedValue.getFunctionOutputs()) {
node.addOutputValue(output);
}
Set<ValueSpecification> downstreamCopy = null;
NodeInputProduction producers = null;
s_logger.debug("Searching for node for {} inputs at {}", resolvedValue.getFunctionInputs().size(), debugId);
for (final ValueSpecification input : resolvedValue.getFunctionInputs()) {
node.addInputValue(input);
final DependencyNode inputNode;
synchronized (this) {
inputNode = _spec2Node.get(input);
}
if (inputNode != null) {
s_logger.debug("Found node {} for input {}", inputNode, input);
node.addInputNode(inputNode);
} else {
s_logger.debug("Finding node productions for {}", input);
final Map<ResolveTask, ResolvedValueProducer> resolver = context.getTasksProducing(input);
if (!resolver.isEmpty()) {
final Set<ValueSpecification> downstreamFinal;
if (downstreamCopy != null) {
downstreamFinal = downstreamCopy;
} else {
downstreamCopy = new HashSet<ValueSpecification>(downstream);
downstreamCopy.add(resolvedValue.getValueSpecification());
downstreamFinal = downstreamCopy;
s_logger.debug("Downstream = {}", downstreamFinal);
}
if (producers == null) {
producers = new NodeInputProduction(resolvedValue, node, result, nodeIsNew);
// Starts with count of 2 (for this producer, and for the overall "block")
} else {
producers.addProducer();
}
final NodeInputProduction producersFinal = producers;
final ResolvedValueCallback callback = new ResolvedValueCallback() {
@Override
public void failed(final GraphBuildingContext context, final ValueRequirement value, final ResolutionFailure failure) {
s_logger.warn("No node production for {} at {}", value, debugId);
producersFinal.failed();
}
@Override
public void resolved(final GraphBuildingContext context, final ValueRequirement valueRequirement, final ResolvedValue resolvedValue, final ResolutionPump pump) {
s_logger.debug("Resolved {} at {}", input, debugId);
getOrCreateNode(context, valueRequirement, resolvedValue, downstreamFinal, new DependencyNodeCallback() {
@Override
public void node(final DependencyNode inputNode) {
if (inputNode != null) {
synchronized (GetTerminalValuesCallback.this) {
node.addInputNode(inputNode);
}
context.close(pump);
producersFinal.completed();
} else {
context.pump(pump);
}
}
});
}
@Override
public String toString() {
return "node productions for " + input;
}
};
if (resolver.size() > 1) {
final AggregateResolvedValueProducer aggregate = new AggregateResolvedValueProducer(input.toRequirementSpecification());
for (Map.Entry<ResolveTask, ResolvedValueProducer> resolvedEntry : resolver.entrySet()) {
aggregate.addProducer(context, resolvedEntry.getValue());
// Only the values are ref-counted
resolvedEntry.getValue().release(context);
}
aggregate.addCallback(context, callback);
aggregate.start(context);
aggregate.release(context);
} else {
final ResolvedValueProducer valueProducer = resolver.values().iterator().next();
valueProducer.addCallback(context, callback);
valueProducer.release(context);
}
} else {
s_logger.warn("No registered node production for {} at {}", input, debugId);
result.node(null);
return;
}
}
}
if (producers == null) {
nodeProduced(resolvedValue, node, result, nodeIsNew);
} else {
s_logger.debug("Production of {} deferred at {}", node, debugId);
// Release the first call
producers.completed();
}
}
private void getOrCreateNode(final GraphBuildingContext context, final ValueRequirement valueRequirement, final ResolvedValue resolvedValue, final Set<ValueSpecification> downstream,
final DependencyNodeCallback result, final DependencyNode existingNode, final Set<DependencyNodeProducer> nodes) {
if (existingNode != null) {
getOrCreateNode(context, valueRequirement, resolvedValue, downstream, result, existingNode, false);
} else {
final DependencyNode newNode = new DependencyNode(resolvedValue.getComputationTarget());
newNode.setFunction(resolvedValue.getFunction());
final PublishNode publisher = new PublishNode(result);
synchronized (nodes) {
nodes.add(publisher);
}
getOrCreateNode(context, valueRequirement, resolvedValue, downstream, publisher, newNode, true);
publisher.getNode(new DependencyNodeCallback() {
@Override
public void node(final DependencyNode node) {
if (node == null) {
synchronized (nodes) {
nodes.remove(publisher);
}
}
}
});
}
}
private void getOrCreateNode(final GraphBuildingContext context, final ValueRequirement valueRequirement, final ResolvedValue resolvedValue, final Set<ValueSpecification> downstream,
final DependencyNodeCallback result) {
s_logger.debug("Resolved {} to {}", valueRequirement, resolvedValue.getValueSpecification());
if (downstream.contains(resolvedValue.getValueSpecification())) {
s_logger.debug("Already have downstream production of {} in {}", resolvedValue.getValueSpecification(), downstream);
result.node(null);
return;
}
final DependencyNode existingNode;
synchronized (this) {
existingNode = _spec2Node.get(resolvedValue.getValueSpecification());
}
if (existingNode != null) {
s_logger.debug("Existing production of {} found in graph set", resolvedValue);
result.node(existingNode);
return;
}
// [PLAT-346] Here is a good spot to tackle PLAT-346; what do we merge into a single node, and which outputs
// do we discard if there are multiple functions that can produce them.
final Set<DependencyNodeProducer> nodes = getOrCreateNodes(resolvedValue.getFunction(), resolvedValue.getComputationTarget());
final FindExistingNodes findExisting = new FindExistingNodes(resolvedValue, nodes);
if (findExisting.isDeferred()) {
s_logger.debug("Deferring evaluation of {} existing nodes", nodes.size());
findExisting.getNode(new DependencyNodeCallback() {
@Override
public void node(final DependencyNode node) {
getOrCreateNode(context, valueRequirement, resolvedValue, downstream, result, node, nodes);
}
});
} else {
getOrCreateNode(context, valueRequirement, resolvedValue, downstream, result, findExisting.getNode(), nodes);
}
}
@Override
public synchronized void resolved(final GraphBuildingContext context, final ValueRequirement valueRequirement, final ResolvedValue resolvedValue, final ResolutionPump pump) {
s_logger.info("Resolved {} to {}", valueRequirement, resolvedValue.getValueSpecification());
context.close(pump);
getOrCreateNode(context, valueRequirement, resolvedValue, Collections.<ValueSpecification>emptySet(), new DependencyNodeCallback() {
@Override
public void node(final DependencyNode node) {
if (node == null) {
s_logger.error("Resolved {} to {} but couldn't create one or more dependency nodes", valueRequirement, resolvedValue.getValueSpecification());
} else {
synchronized (GetTerminalValuesCallback.this) {
_resolvedValues.put(valueRequirement, resolvedValue.getValueSpecification());
}
}
}
});
}
@Override
public String toString() {
return "TerminalValueCallback";
}
public synchronized Collection<DependencyNode> getGraphNodes() {
return new ArrayList<DependencyNode>(_graphNodes);
}
public synchronized Map<ValueRequirement, ValueSpecification> getTerminalValues() {
return new HashMap<ValueRequirement, ValueSpecification>(_resolvedValues);
}
}; |
package ar.fiuba.tecnicas.output;
public interface IOutput {
public void out (String mensaje);
} |
package cn.cerc.mis.core;
import cn.cerc.db.core.IHandle;
public interface IUserLoginCheck extends IHandle {
String getToken(String userCode, String password, String device, String machineCode, String clientIP,
String language, String loginType);
String getUserCode(String mobile) throws Exception;// FIXME
String getMessage();
} |
package com.jetbrains.python.refactoring.move;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.MoveCallback;
import com.intellij.refactoring.move.MoveHandlerDelegate;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.psi.PyClass;
import com.jetbrains.python.psi.PyFile;
import com.jetbrains.python.psi.PyFunction;
import com.jetbrains.python.psi.impl.PyQualifiedName;
import com.jetbrains.python.psi.resolve.ResolveImportUtil;
import com.jetbrains.python.refactoring.classes.PyClassRefactoringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author vlan
*/
public class PyMoveClassOrFunctionDelegate extends MoveHandlerDelegate {
@Override
public void doMove(Project project,
PsiElement[] elements,
@Nullable PsiElement targetContainer,
@Nullable MoveCallback callback) {
PsiNamedElement[] elementsToMove = new PsiNamedElement[elements.length];
for (int i = 0; i < elements.length; i++) {
PsiNamedElement e = getElementToMove(elements[i]);
if (e == null) {
return;
}
elementsToMove[i] = e;
}
final PsiFile targetFile;
boolean previewUsages = false;
if (targetContainer instanceof PyFile) {
targetFile = (PsiFile)targetContainer;
} else {
final PyMoveClassOrFunctionDialog dialog = new PyMoveClassOrFunctionDialog(project, elementsToMove);
dialog.show();
if (!dialog.isOK()) {
return;
}
targetFile = dialog.getTargetFile();
previewUsages = dialog.isPreviewUsages();
}
CommonRefactoringUtil.checkReadOnlyStatus(project, targetFile);
for (PsiNamedElement e: elementsToMove) {
CommonRefactoringUtil.checkReadOnlyStatus(project, e);
}
try {
if (!(targetFile instanceof PyFile)) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.class.or.function.error.cannot.place.elements.into.nonpython.file"));
}
PyFile file = (PyFile)targetFile;
for (PsiNamedElement e: elementsToMove) {
assert e instanceof PyClass || e instanceof PyFunction;
if (e instanceof PyClass && file.findTopLevelClass(e.getName()) != null) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.class.or.function.error.destination.file.contains.class.$0", e.getName()));
}
if (e instanceof PyFunction && file.findTopLevelFunction(e.getName()) != null) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.class.or.function.error.destination.file.contains.function.$0", e.getName()));
}
checkValidImportableFile(file, e.getContainingFile().getVirtualFile());
checkValidImportableFile(e, file.getVirtualFile());
}
// TODO: Check for resulting circular imports
final BaseRefactoringProcessor processor = new PyMoveClassOrFunctionProcessor(project, elementsToMove, (PyFile)targetFile,
previewUsages);
processor.run();
}
catch (IncorrectOperationException e) {
CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.getMessage(),
null, project);
}
}
private static void checkValidImportableFile(PsiElement anchor, VirtualFile file) {
final PyQualifiedName qName = ResolveImportUtil.findShortestImportableQName(anchor, file);
if (!PyClassRefactoringUtil.isValidQualifiedName(qName)) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.class.or.function.error.cannot.use.module.name.$0", qName));
}
}
@Override
public boolean tryToMove(@NotNull PsiElement element,
@NotNull Project project,
@Nullable DataContext dataContext,
@Nullable PsiReference reference,
@Nullable Editor editor) {
final PsiNamedElement elementToMove = getElementToMove(element);
if (elementToMove != null) {
doMove(project, new PsiElement[] {element}, null, null);
return true;
}
if (element instanceof PsiNamedElement) {
return true;
}
return false;
}
@Nullable
private static PsiNamedElement getElementToMove(@NotNull PsiElement element) {
if (element instanceof PyFunction && ((PyFunction)element).isTopLevel() ||
element instanceof PyClass && ((PyClass)element).isTopLevel()) {
return (PsiNamedElement)element;
}
return null;
}
} |
package cn.cerc.mis.queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import cn.cerc.db.core.DataRow;
import cn.cerc.db.core.Datetime;
import cn.cerc.db.core.ISession;
import cn.cerc.mis.client.ServiceSign;
import cn.cerc.mis.core.Application;
import cn.cerc.mis.core.BookHandle;
import cn.cerc.mis.core.IUserMessage;
import cn.cerc.mis.message.MessageProcess;
import cn.cerc.mis.task.AbstractTask;
/**
*
*
* @author ZhangGong
*/
public class ProcessService extends AbstractTask {
private static final Logger log = LoggerFactory.getLogger(ProcessService.class);
public static void main(String[] args) {
Application.initOnlyFramework();
ISession session = Application.getSession();
ProcessService ps = new ProcessService();
ps.setSession(session);
ps.run();
}
@Override
public void execute() throws JsonProcessingException {
IUserMessage um = Application.getBean(this, IUserMessage.class);
for (String uid : um.getWaitList()) {
log.info("UID=" + uid);
processService(uid);
}
}
private void processService(String taskId) throws JsonProcessingException {
IUserMessage um = Application.getBean(this, IUserMessage.class);
DataRow ds = um.readAsyncService(taskId);
if (ds == null) {
return;
}
String corpNo = ds.getString("corpNo");
String userCode = ds.getString("userCode");
String content = ds.getString("content");
String subject = ds.getString("subject");
AsyncService async = new AsyncService(this);
async.read(content);
async.setProcess(MessageProcess.working);
updateTaskprocess(async, taskId, subject);
try {
BookHandle handle = new BookHandle(this, corpNo).setUserCode(userCode);
ServiceSign auto = async.getSign().call(handle, async.dataIn());
if (auto.isOk()) {
async.setProcess(MessageProcess.ok);
} else {
async.setProcess(MessageProcess.error);
}
async.dataOut().appendDataSet(auto.dataOut(), true);
async.dataOut().head().setValue("_message_", auto.dataOut().message());
updateTaskprocess(async, taskId, subject);
} catch (Throwable e) {
e.printStackTrace();
async.setProcess(MessageProcess.error);
async.dataOut().head().setValue("_message_", e.getMessage());
updateTaskprocess(async, taskId, subject);
}
}
private void updateTaskprocess(AsyncService async, String msgId, String subject) {
async.setProcessTime(new Datetime().toString());
IUserMessage um = Application.getBean(this, IUserMessage.class);
if (!um.updateAsyncService(msgId, async.toString(), async.getProcess())) {
throw new RuntimeException(String.format("msgId %s not find.", msgId));
}
log.debug(async.getService() + ":" + subject + ":" + async.getProcess().getTitle());
}
} |
package cn.momia.mapi.api.user;
import cn.momia.api.user.ChildServiceApi;
import cn.momia.api.user.SmsServiceApi;
import cn.momia.api.course.CouponServiceApi;
import cn.momia.api.im.ImServiceApi;
import cn.momia.api.user.AuthServiceApi;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.dto.Child;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.common.core.util.MobileUtil;
import cn.momia.mapi.api.AbstractApi;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/v1/auth")
public class AuthV1Api extends AbstractApi {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthV1Api.class);
@Autowired private SmsServiceApi smsServiceApi;
@Autowired private AuthServiceApi authServiceApi;
@Autowired private CouponServiceApi couponServiceApi;
@Autowired private ImServiceApi imServiceApi;
@Autowired private ChildServiceApi childServiceApi;
@Autowired private UserServiceApi userServiceApi;
@RequestMapping(value = "/send", method = RequestMethod.POST)
public MomiaHttpResponse send(@RequestParam String mobile) {
if (MobileUtil.isInvalid(mobile)) return MomiaHttpResponse.FAILED("");
if (!smsServiceApi.send(mobile)) return MomiaHttpResponse.FAILED("");
return MomiaHttpResponse.SUCCESS;
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public MomiaHttpResponse register(@RequestParam(value = "nickname") String nickName,
@RequestParam String mobile,
@RequestParam String password,
@RequestParam String code) {
if (StringUtils.isBlank(nickName)) return MomiaHttpResponse.FAILED("");
if (MobileUtil.isInvalid(mobile)) return MomiaHttpResponse.FAILED("");
if (StringUtils.isBlank(password)) return MomiaHttpResponse.FAILED("");
if (StringUtils.isBlank(code)) return MomiaHttpResponse.FAILED("");
User user = completeUserImgs(authServiceApi.register(nickName, mobile, password, code));
distributeInviteCoupon(user.getId(), mobile);
generateImToken(user, user.getNickName(), user.getAvatar());
addDefaultChild(user);
return MomiaHttpResponse.SUCCESS(user);
}
private void distributeInviteCoupon(long userId, String mobile) {
try {
couponServiceApi.distributeInviteCoupon(userId, mobile);
} catch (Exception e) {
LOGGER.error("", e);
}
}
private void generateImToken(User user, String nickName, String avatar) {
try {
String imToken = imServiceApi.generateImToken(user.getId(), nickName, avatar);
if (!StringUtils.isBlank(imToken)) userServiceApi.updateImToken(user.getToken(), imToken);
} catch (Exception e) {
LOGGER.error("fail to generate im token for user: {}", user.getId(), e);
}
}
private void addDefaultChild(User user) {
try {
Child child = new Child();
child.setUserId(user.getId());
child.setName(user.getNickName() + "");
child.setSex("");
child.setBirthday(new Date(new Date().getTime() - 5 * 365 * 24 * 60 * 60 * 1000L));
List<Child> children = new ArrayList<Child>();
children.add(child);
childServiceApi.add(user.getToken(), JSON.toJSONString(children));
} catch (Exception e) {
LOGGER.error("fail to add default child for user: {}", user.getId(), e);
}
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public MomiaHttpResponse login(@RequestParam String mobile, @RequestParam String password) {
if (MobileUtil.isInvalid(mobile)) return MomiaHttpResponse.FAILED("");
if (StringUtils.isBlank(password)) return MomiaHttpResponse.FAILED("");
return MomiaHttpResponse.SUCCESS(completeUserImgs(authServiceApi.login(mobile, password)));
}
@RequestMapping(value = "/password", method = RequestMethod.POST)
public MomiaHttpResponse updatePassword(@RequestParam String mobile, @RequestParam String password, @RequestParam String code) {
if (MobileUtil.isInvalid(mobile)) return MomiaHttpResponse.FAILED("");
if (StringUtils.isBlank(password)) return MomiaHttpResponse.FAILED("");
if (StringUtils.isBlank(code)) return MomiaHttpResponse.FAILED("");
return MomiaHttpResponse.SUCCESS(completeUserImgs(authServiceApi.updatePassword(mobile, password, code)));
}
} |
package no.deichman.services.patch;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public final class PatchObjectTypeAdapter implements JsonDeserializer<List<PatchObject>> {
public List<PatchObject> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<PatchObject> vals = new ArrayList<PatchObject>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
vals.add(ctx.deserialize(e, PatchObject.class));
}
} else if (json.isJsonObject()) {
vals.add(ctx.deserialize(json, PatchObject.class));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return vals;
}
} |
package com.intellij.refactoring.extractMethod;
import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.codeInsight.PsiEquivalenceUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.text.BlockSupport;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.classMembers.ElementNeedsThis;
import com.intellij.refactoring.util.duplicates.DuplicatesFinder;
import com.intellij.refactoring.util.duplicates.Match;
import com.intellij.refactoring.util.duplicates.MatchProvider;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.IntArrayList;
import org.jetbrains.annotations.NonNls;
import java.util.*;
public class ExtractMethodProcessor implements MatchProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.extractMethod.ExtractMethodProcessor");
private final Project myProject;
private final Editor myEditor;
private final PsiElement[] myElements;
private final PsiBlockStatement myEnclosingBlockStatement;
private final PsiType myForcedReturnType;
private final String myRefactoringName;
private final String myInitialMethodName;
private final String myHelpId;
private final PsiManager myManager;
private final PsiElementFactory myElementFactory;
private final CodeStyleManager myStyleManager;
private PsiExpression myExpression;
private PsiElement myCodeFragementMember; // parent of myCodeFragment
private String myMethodName; // name for extracted method
private PsiType myReturnType; // return type for extracted method
private PsiTypeParameterList myTypeParameterList; //type parameter list of extracted method
private ParameterTablePanel.VariableData[] myVariableDatum; // parameter data for extracted method
private PsiClassType[] myThrownExceptions; // exception to declare as thrown by extracted method
private boolean myStatic; // whether to declare extracted method static
private PsiClass myTargetClass; // class to create the extracted method in
private PsiElement myAnchor; // anchor to insert extracted method after it
private ControlFlow myControlFlow; // control flow of myCodeFragment
private int myFlowStart; // offset in control flow corresponding to the start of the code to be extracted
private int myFlowEnd; // offset in control flow corresponding to position just after the end of the code to be extracted
private PsiVariable[] myInputVariables; // input variables
private PsiVariable[] myOutputVariables; // output variables
private PsiVariable myOutputVariable; // the only output variable
private List<PsiStatement> myExitStatements;
private boolean myHasReturnStatement; // there is a return statement
private boolean myHasReturnStatementOutput; // there is a return statement and its type is not void
private boolean myHasExpressionOutput; // extracted code is an expression with non-void type
private boolean myNeedChangeContext; // target class is not immediate container of the code to be extracted
private boolean myShowErrorDialogs = true;
private boolean myCanBeStatic;
private List<Match> myDuplicates;
private String myMethodVisibility = PsiModifier.PRIVATE;
private boolean myGenerateConditionalExit;
private PsiStatement myFirstExitStatementCopy;
public ExtractMethodProcessor(Project project, Editor editor, PsiElement[] elements,
PsiType forcedReturnType, String refactoringName,
String initialMethodName, String helpId) {
myProject = project;
myEditor = editor;
if (elements.length != 1 || (elements.length == 1 && !(elements[0] instanceof PsiBlockStatement))) {
myElements = elements;
myEnclosingBlockStatement = null;
}
else {
myEnclosingBlockStatement = (PsiBlockStatement)elements[0];
PsiElement[] codeBlockChildren = myEnclosingBlockStatement.getCodeBlock().getChildren();
myElements = processCodeBlockChildren(codeBlockChildren);
}
myForcedReturnType = forcedReturnType;
myRefactoringName = refactoringName;
myInitialMethodName = initialMethodName;
myHelpId = helpId;
myManager = PsiManager.getInstance(myProject);
myElementFactory = myManager.getElementFactory();
myStyleManager = CodeStyleManager.getInstance(myProject);
}
private static PsiElement[] processCodeBlockChildren(PsiElement[] codeBlockChildren) {
int resultStart = 0;
int resultLast = codeBlockChildren.length;
if (codeBlockChildren.length == 0) return PsiElement.EMPTY_ARRAY;
final PsiElement first = codeBlockChildren[0];
if (first instanceof PsiJavaToken && ((PsiJavaToken)first).getTokenType() == JavaTokenType.LBRACE) {
resultStart++;
}
final PsiElement last = codeBlockChildren[codeBlockChildren.length - 1];
if (last instanceof PsiJavaToken && ((PsiJavaToken)last).getTokenType() == JavaTokenType.RBRACE) {
resultLast
}
final ArrayList<PsiElement> result = new ArrayList<PsiElement>();
for (int i = resultStart; i < resultLast; i++) {
PsiElement element = codeBlockChildren[i];
if (!(element instanceof PsiWhiteSpace)) {
result.add(element);
}
}
return result.toArray(new PsiElement[result.size()]);
}
/**
* Method for test purposes
*/
public void setShowErrorDialogs(boolean showErrorDialogs) {
myShowErrorDialogs = showErrorDialogs;
}
private boolean areExitStatementsTheSame() {
if (myExitStatements.size() == 0) return false;
PsiStatement firstExitStatement = myExitStatements.get(0);
for (int i = 1; i < myExitStatements.size(); i++) {
PsiStatement statement = myExitStatements.get(i);
if (!PsiEquivalenceUtil.areElementsEquivalent(firstExitStatement, statement)) return false;
}
myFirstExitStatementCopy = (PsiStatement)firstExitStatement.copy();
return true;
}
/**
* Invoked in atomic action
*/
public boolean prepare() throws PrepareFailedException {
myExpression = null;
if (myElements.length == 1 && myElements[0] instanceof PsiExpression) {
final PsiExpression expression = (PsiExpression)myElements[0];
if (expression.getParent() instanceof PsiExpressionStatement) {
myElements[0] = expression.getParent();
}
else {
myExpression = expression;
}
}
final PsiElement codeFragment = ControlFlowUtil.findCodeFragment(myElements[0]);
myCodeFragementMember = codeFragment.getParent();
ControlFlowAnalyzer analyzer = new ControlFlowAnalyzer(codeFragment, new LocalsControlFlowPolicy(codeFragment), false);
try {
myControlFlow = analyzer.buildControlFlow();
}
catch (AnalysisCanceledException e) {
throw new PrepareFailedException(RefactoringBundle.message("extract.method.control.flow.analysis.failed"),
e.getErrorElement());
}
if (LOG.isDebugEnabled()) {
LOG.debug(myControlFlow.toString());
}
calculateFlowStartAndEnd();
IntArrayList exitPoints = new IntArrayList();
myExitStatements = new ArrayList<PsiStatement>();
ControlFlowUtil.findExitPointsAndStatements
(myControlFlow, myFlowStart, myFlowEnd, exitPoints, myExitStatements,
ControlFlowUtil.DEFAULT_EXIT_STATEMENTS_CLASSES);
if (LOG.isDebugEnabled()) {
LOG.debug("exit points:");
for (int i = 0; i < exitPoints.size(); i++) {
LOG.debug(" " + exitPoints.get(i));
}
LOG.debug("exit statements:");
for (PsiStatement exitStatement : myExitStatements) {
LOG.debug(" " + exitStatement);
}
}
if (exitPoints.size() == 0) {
// if the fragment never exits assume as if it exits in the end
exitPoints.add(myControlFlow.getEndOffset(myElements[myElements.length - 1]));
}
myOutputVariables = ControlFlowUtil.getOutputVariables(myControlFlow, myFlowStart, myFlowEnd, exitPoints.toArray());
if (exitPoints.size() != 1) {
if (!areExitStatementsTheSame()) {
showMultipleExitPointsMessage();
return false;
}
myGenerateConditionalExit = true;
} else {
myHasReturnStatement = myExpression == null &&
ControlFlowUtil.returnPresentBetween(myControlFlow, myFlowStart, myFlowEnd);
}
myInputVariables = ControlFlowUtil.getInputVariables(myControlFlow, myFlowStart, myFlowEnd);
//varargs variables go last
Arrays.sort(myInputVariables, new Comparator<PsiVariable>() {
public int compare(final PsiVariable v1, final PsiVariable v2) {
return v1.getType() instanceof PsiEllipsisType ? 1 :
v2.getType() instanceof PsiEllipsisType ? -1 : 0;
}
});
chooseTargetClass();
PsiType expressionType = null;
if (myExpression != null) {
if (myForcedReturnType != null) {
expressionType = myForcedReturnType;
}
else {
expressionType = RefactoringUtil.getTypeByExpressionWithExpectedType(myExpression);
}
}
if (expressionType == null) {
expressionType = PsiType.VOID;
}
myHasExpressionOutput = expressionType != PsiType.VOID;
PsiType returnStatementType = null;
if (myHasReturnStatement) {
returnStatementType = myCodeFragementMember instanceof PsiMethod
? ((PsiMethod)myCodeFragementMember).getReturnType()
: null;
}
myHasReturnStatementOutput = returnStatementType != null && returnStatementType != PsiType.VOID;
if (!myHasReturnStatementOutput) {
int outputCount = (myHasExpressionOutput ? 1 : 0) +
(myGenerateConditionalExit ? 1 : 0) +
myOutputVariables.length;
if (outputCount > 1) {
showMultipleOutputMessage(expressionType);
return false;
}
}
myOutputVariable = myOutputVariables.length > 0 ? myOutputVariables[0] : null;
if (myHasReturnStatementOutput) {
myReturnType = returnStatementType;
}
else if (myOutputVariable != null) {
myReturnType = myOutputVariable.getType();
}
else if (myGenerateConditionalExit) {
myReturnType = PsiType.BOOLEAN;
}
else {
myReturnType = expressionType;
}
PsiElement container = PsiTreeUtil.getParentOfType(myElements[0], PsiClass.class, PsiMethod.class);
if (container instanceof PsiMethod) {
myTypeParameterList = ((PsiMethod)container).getTypeParameterList();
}
myThrownExceptions = ExceptionUtil.getThrownCheckedExceptions(myElements);
myStatic = shouldBeStatic();
if (myTargetClass.getContainingClass() == null ||
myTargetClass.hasModifierProperty(PsiModifier.STATIC)) {
ElementNeedsThis needsThis = new ElementNeedsThis(myTargetClass);
for (int i = 0; i < myElements.length && !needsThis.usesMembers(); i++) {
PsiElement element = myElements[i];
element.accept(needsThis);
}
myCanBeStatic = !needsThis.usesMembers();
}
else {
myCanBeStatic = false;
}
final DuplicatesFinder duplicatesFinder;
if (myExpression != null) {
duplicatesFinder = new DuplicatesFinder(myElements, Arrays.asList(myInputVariables), new ArrayList<PsiVariable>(), false);
myDuplicates = duplicatesFinder.findDuplicates(myTargetClass);
}
else {
duplicatesFinder = new DuplicatesFinder(myElements, Arrays.asList(myInputVariables), Arrays.asList(myOutputVariables), false);
myDuplicates = duplicatesFinder.findDuplicates(myTargetClass);
}
return true;
}
private boolean shouldBeStatic() {
PsiElement codeFragementMember = myCodeFragementMember;
while (codeFragementMember != null && PsiTreeUtil.isAncestor(myTargetClass, codeFragementMember, true)) {
if (((PsiModifierListOwner)codeFragementMember).hasModifierProperty(PsiModifier.STATIC)) {
return true;
}
codeFragementMember = PsiTreeUtil.getParentOfType(codeFragementMember, PsiModifierListOwner.class, true);
}
return false;
}
public boolean showDialog() {
ExtractMethodDialog dialog = new ExtractMethodDialog(myProject,
myTargetClass,
myInputVariables,
myReturnType,
myTypeParameterList,
myThrownExceptions,
myStatic,
myCanBeStatic,
myInitialMethodName,
myRefactoringName,
myHelpId);
dialog.show();
if (!dialog.isOK()) return false;
myMethodName = dialog.getChoosenMethodName();
myVariableDatum = dialog.getChoosenParameters();
myStatic = myStatic || dialog.isMakeStatic();
myMethodVisibility = dialog.getVisibility();
return true;
}
public void testRun() throws IncorrectOperationException {
ExtractMethodDialog dialog = new ExtractMethodDialog(myProject,
myTargetClass,
myInputVariables,
myReturnType,
myTypeParameterList, myThrownExceptions,
myStatic,
myCanBeStatic, myInitialMethodName,
myRefactoringName,
myHelpId);
myMethodName = dialog.getChoosenMethodName();
myVariableDatum = dialog.getChoosenParameters();
doRefactoring();
}
/**
* Invoked in command and in atomic action
*/
public void doRefactoring() throws IncorrectOperationException {
chooseAnchor();
int col = myEditor.getCaretModel().getLogicalPosition().column;
int line = myEditor.getCaretModel().getLogicalPosition().line;
LogicalPosition pos = new LogicalPosition(0, 0);
myEditor.getCaretModel().moveToLogicalPosition(pos);
PsiMethodCallExpression methodCall = doExtract();
LogicalPosition pos1 = new LogicalPosition(line, col);
myEditor.getCaretModel().moveToLogicalPosition(pos1);
int offset = methodCall.getMethodExpression().getTextRange().getStartOffset();
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
myEditor.getSelectionModel().removeSelection();
}
private PsiMethodCallExpression doExtract() throws IncorrectOperationException {
renameInputVariables();
PsiMethod newMethod = generateEmptyMethod(myThrownExceptions, myStatic);
LOG.assertTrue(myElements[0].isValid());
PsiCodeBlock body = newMethod.getBody();
PsiMethodCallExpression methodCall = generateMethodCall(null);
LOG.assertTrue(myElements[0].isValid());
if (myExpression == null) {
String outVariableName = myOutputVariable != null ? getNewVariableName(myOutputVariable) : null;
PsiReturnStatement returnStatement;
if (myOutputVariable != null) {
returnStatement =
(PsiReturnStatement)myElementFactory.createStatementFromText("return " + outVariableName + ";", null);
}
else if (myGenerateConditionalExit) {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return true;", null);
}
else {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return;", null);
}
boolean hasNormalExit = false;
PsiElement lastElement = myElements[myElements.length - 1];
if (!(lastElement instanceof PsiReturnStatement || lastElement instanceof PsiBreakStatement ||
lastElement instanceof PsiContinueStatement)) {
hasNormalExit = true;
}
PsiStatement exitStatementCopy = null;
// replace all exit-statements such as break's or continue's with appropriate return
for (PsiStatement exitStatement : myExitStatements) {
if (exitStatement instanceof PsiReturnStatement) {
if (!myGenerateConditionalExit) continue;
}
else if (exitStatement instanceof PsiBreakStatement) {
PsiStatement statement = ((PsiBreakStatement)exitStatement).findExitedStatement();
if (statement == null) continue;
int startOffset = myControlFlow.getStartOffset(statement);
int endOffset = myControlFlow.getEndOffset(statement);
if (myFlowStart <= startOffset && endOffset <= myFlowEnd) continue;
}
else if (exitStatement instanceof PsiContinueStatement) {
PsiStatement statement = ((PsiContinueStatement)exitStatement).findContinuedStatement();
if (statement == null) continue;
int startOffset = myControlFlow.getStartOffset(statement);
int endOffset = myControlFlow.getEndOffset(statement);
if (myFlowStart <= startOffset && endOffset <= myFlowEnd) continue;
}
else {
LOG.assertTrue(false, exitStatement.toString());
continue;
}
int index = -1;
for (int j = 0; j < myElements.length; j++) {
if (exitStatement.equals(myElements[j])) {
index = j;
break;
}
}
if (exitStatementCopy == null) {
exitStatementCopy = (PsiStatement)exitStatement.copy();
}
PsiElement result = exitStatement.replace(returnStatement);
if (index >= 0) {
myElements[index] = result;
}
}
declareNecessaryVariablesInsideBody(myFlowStart, myFlowEnd, body);
if (myNeedChangeContext) {
for (PsiElement element : myElements) {
ChangeContextUtil.encodeContextInfo(element, false);
}
}
body.addRange(myElements[0], myElements[myElements.length - 1]);
if (myGenerateConditionalExit) {
body.add(myElementFactory.createStatementFromText("return false;", null));
}
else if (!myHasReturnStatement && hasNormalExit && myOutputVariable != null) {
body.add(returnStatement);
}
if (myGenerateConditionalExit) {
PsiIfStatement ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (a) b;", null);
ifStatement = (PsiIfStatement)addToMethodCallLocation(ifStatement);
methodCall = (PsiMethodCallExpression)ifStatement.getCondition().replace(methodCall);
ifStatement.getThenBranch().replace(myFirstExitStatementCopy);
}
else if (myOutputVariable != null) {
String name = myOutputVariable.getName();
boolean toDeclare = isDeclaredInside(myOutputVariable);
if (!toDeclare) {
PsiExpressionStatement statement = (PsiExpressionStatement)myElementFactory.createStatementFromText(
name + "=x;", null);
statement = (PsiExpressionStatement)myStyleManager.reformat(statement);
statement = (PsiExpressionStatement)addToMethodCallLocation(statement);
PsiAssignmentExpression assignment = (PsiAssignmentExpression)statement.getExpression();
methodCall = (PsiMethodCallExpression)assignment.getRExpression().replace(methodCall);
}
else {
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name,
myOutputVariable.getType(),
methodCall);
statement = (PsiDeclarationStatement)addToMethodCallLocation(statement);
PsiVariable var = (PsiVariable)statement.getDeclaredElements()[0];
methodCall = (PsiMethodCallExpression)var.getInitializer();
var.getModifierList().replace(myOutputVariable.getModifierList());
}
}
else if (myHasReturnStatementOutput) {
PsiStatement statement = myElementFactory.createStatementFromText("return x;", null);
statement = (PsiStatement)addToMethodCallLocation(statement);
methodCall = (PsiMethodCallExpression)((PsiReturnStatement)statement).getReturnValue().replace(methodCall);
}
else {
PsiStatement statement = myElementFactory.createStatementFromText("x();", null);
statement = (PsiStatement)addToMethodCallLocation(statement);
methodCall =
(PsiMethodCallExpression)((PsiExpressionStatement)statement).getExpression().replace(methodCall);
}
if (myHasReturnStatement && !myHasReturnStatementOutput && !hasNormalExit) {
PsiStatement statement = myElementFactory.createStatementFromText("return;", null);
addToMethodCallLocation(statement);
}
else if (!myGenerateConditionalExit && exitStatementCopy != null) {
addToMethodCallLocation(exitStatementCopy);
}
declareNecessaryVariablesAfterCall(myFlowEnd, myOutputVariable);
deleteExtracted();
}
else {
if (myHasExpressionOutput) {
PsiReturnStatement returnStatement =
(PsiReturnStatement)myElementFactory.createStatementFromText("return x;", null);
final PsiExpression returnValue;
returnValue = RefactoringUtil.convertInitializerToNormalExpression(myExpression, myForcedReturnType);
returnStatement.getReturnValue().replace(returnValue);
body.add(returnStatement);
}
else {
PsiExpressionStatement statement = (PsiExpressionStatement)myElementFactory.createStatementFromText("x;", null);
statement.getExpression().replace(myExpression);
body.add(statement);
}
methodCall = (PsiMethodCallExpression)myExpression.replace(methodCall);
}
if (myAnchor instanceof PsiField) {
((PsiField)myAnchor).normalizeDeclaration();
}
newMethod = (PsiMethod)myTargetClass.addAfter(newMethod, myAnchor);
if (myNeedChangeContext) {
ChangeContextUtil.decodeContextInfo(newMethod, myTargetClass,
RefactoringUtil.createThisExpression(myManager, null));
}
return methodCall;
}
public List<Match> getDuplicates() {
return myDuplicates;
}
public void processMatch(Match match) throws IncorrectOperationException {
final PsiMethodCallExpression methodCallExpression = generateMethodCall(match.getInstanceExpression());
final PsiExpression[] expressions = methodCallExpression.getArgumentList().getExpressions();
ArrayList<ParameterTablePanel.VariableData> datas = new ArrayList<ParameterTablePanel.VariableData>();
for (final ParameterTablePanel.VariableData variableData : myVariableDatum) {
if (variableData.passAsParameter) {
datas.add(variableData);
}
}
LOG.assertTrue(expressions.length == datas.size());
for (int i = 0; i < datas.size(); i++) {
ParameterTablePanel.VariableData data = datas.get(i);
final PsiElement parameterValue = match.getParameterValue(data.variable);
expressions[i].replace(parameterValue);
}
match.replace(methodCallExpression, myOutputVariable);
}
private void deleteExtracted() throws IncorrectOperationException {
if (myEnclosingBlockStatement == null) {
myElements[0].getParent().deleteChildRange(myElements[0], myElements[myElements.length - 1]);
}
else {
myEnclosingBlockStatement.delete();
}
}
private PsiElement addToMethodCallLocation(PsiElement statement) throws IncorrectOperationException {
if (myEnclosingBlockStatement == null) {
return myElements[0].getParent().addBefore(statement, myElements[0]);
}
else {
return myEnclosingBlockStatement.getParent().addBefore(statement, myEnclosingBlockStatement);
}
}
private void calculateFlowStartAndEnd() {
int index = 0;
myFlowStart = -1;
while (index < myElements.length) {
myFlowStart = myControlFlow.getStartOffset(myElements[index]);
if (myFlowStart >= 0) break;
index++;
}
if (myFlowStart < 0) {
// no executable code
myFlowStart = 0;
myFlowEnd = 0;
}
else {
index = myElements.length - 1;
while (true) {
myFlowEnd = myControlFlow.getEndOffset(myElements[index]);
if (myFlowEnd >= 0) break;
index
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("start offset:" + myFlowStart);
LOG.debug("end offset:" + myFlowEnd);
}
}
private void renameInputVariables() throws IncorrectOperationException {
for (ParameterTablePanel.VariableData data : myVariableDatum) {
PsiVariable variable = data.variable;
if (!data.name.equals(variable.getName())) {
for (PsiElement element : myElements) {
RefactoringUtil.renameVariableReferences(variable, data.name, new LocalSearchScope(element));
}
}
}
}
public PsiClass getTargetClass() {
return myTargetClass;
}
private PsiMethod generateEmptyMethod(PsiClassType[] exceptions, boolean isStatic) throws IncorrectOperationException {
PsiMethod newMethod = myElementFactory.createMethod(myMethodName, myReturnType);
newMethod.getModifierList().setModifierProperty(myMethodVisibility, true);
newMethod.getModifierList().setModifierProperty(PsiModifier.STATIC, isStatic);
if (myTypeParameterList != null) {
newMethod.getTypeParameterList().replace(myTypeParameterList);
}
PsiCodeBlock body = newMethod.getBody();
boolean isFinal = CodeStyleSettingsManager.getSettings(myProject).GENERATE_FINAL_PARAMETERS;
PsiParameterList list = newMethod.getParameterList();
for (ParameterTablePanel.VariableData data : myVariableDatum) {
if (data.passAsParameter) {
PsiParameter parm = myElementFactory.createParameter(data.name, data.type);
if (isFinal) {
parm.getModifierList().setModifierProperty(PsiModifier.FINAL, true);
}
list.add(parm);
}
else {
@NonNls StringBuffer buffer = new StringBuffer();
if (isFinal) {
buffer.append("final ");
}
buffer.append("int ");
buffer.append(data.name);
buffer.append("=x;");
String text = buffer.toString();
PsiDeclarationStatement declaration = (PsiDeclarationStatement)myElementFactory.createStatementFromText(text,
null);
declaration = (PsiDeclarationStatement)myStyleManager.reformat(declaration);
final PsiTypeElement typeElement = myElementFactory.createTypeElement(data.type);
((PsiVariable)declaration.getDeclaredElements()[0]).getTypeElement().replace(typeElement);
declaration = (PsiDeclarationStatement)body.add(declaration);
PsiExpression initializer = ((PsiVariable)declaration.getDeclaredElements()[0]).getInitializer();
TextRange range = initializer.getTextRange();
BlockSupport blockSupport = myProject.getComponent(BlockSupport.class);
blockSupport.reparseRange(body.getContainingFile(), range.getStartOffset(), range.getEndOffset(), "...");
}
}
PsiReferenceList throwsList = newMethod.getThrowsList();
for (PsiClassType exception : exceptions) {
throwsList.add(myManager.getElementFactory().createReferenceElementByType(exception));
}
return (PsiMethod)myStyleManager.reformat(newMethod);
}
private PsiMethodCallExpression generateMethodCall(PsiExpression instanceQualifier) throws IncorrectOperationException {
@NonNls StringBuffer buffer = new StringBuffer();
final boolean skipInstanceQualifier = instanceQualifier == null || instanceQualifier instanceof PsiThisExpression;
if (skipInstanceQualifier) {
if (myNeedChangeContext) {
boolean needsThisQualifier = false;
PsiElement parent = myCodeFragementMember;
while (!myTargetClass.equals(parent)) {
if (parent instanceof PsiMethod) {
String methodName = ((PsiMethod)parent).getName();
if (methodName.equals(myMethodName)) {
needsThisQualifier = true;
break;
}
}
parent = parent.getParent();
}
if (needsThisQualifier) {
buffer.append(myTargetClass.getName());
buffer.append(".this.");
}
}
}
else {
buffer.append("qqq.");
}
buffer.append(myMethodName);
buffer.append("(");
int count = 0;
for (ParameterTablePanel.VariableData data : myVariableDatum) {
if (data.passAsParameter) {
if (count > 0) {
buffer.append(",");
}
buffer.append(data.variable.getName());
count++;
}
}
buffer.append(")");
String text = buffer.toString();
PsiMethodCallExpression expr = (PsiMethodCallExpression)myElementFactory.createExpressionFromText(text, null);
expr = (PsiMethodCallExpression)myStyleManager.reformat(expr);
if (!skipInstanceQualifier) {
expr.getMethodExpression().getQualifierExpression().replace(instanceQualifier);
}
return expr;
}
private void declareNecessaryVariablesInsideBody(int start, int end, PsiCodeBlock body) throws IncorrectOperationException {
PsiVariable[] usedVariables = ControlFlowUtil.getUsedVariables(myControlFlow, start, end);
for (PsiVariable variable : usedVariables) {
boolean toDeclare = !isDeclaredInside(variable) && !contains(myInputVariables, variable);
if (toDeclare) {
String name = variable.getName();
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name,
variable.getType(),
null);
body.add(statement);
}
}
}
private void declareNecessaryVariablesAfterCall(int end, PsiVariable outputVariable) throws IncorrectOperationException {
PsiVariable[] usedVariables = ControlFlowUtil.getUsedVariables(myControlFlow, end, myControlFlow.getSize());
for (PsiVariable variable : usedVariables) {
boolean toDeclare = isDeclaredInside(variable) && !variable.equals(outputVariable);
if (toDeclare) {
String name = variable.getName();
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name,
variable.getType(),
null);
addToMethodCallLocation(statement);
}
}
}
private boolean isDeclaredInside(PsiVariable variable) {
if(variable instanceof ImplicitVariable) return false;
int startOffset = myElements[0].getTextRange().getStartOffset();
int endOffset = myElements[myElements.length - 1].getTextRange().getEndOffset();
final TextRange range = variable.getNameIdentifier().getTextRange();
if (range == null) return false;
int offset = range.getStartOffset();
return startOffset <= offset && offset <= endOffset;
}
private String getNewVariableName(PsiVariable variable) {
for (ParameterTablePanel.VariableData data : myVariableDatum) {
if (data.variable.equals(variable)) {
return data.name;
}
}
return variable.getName();
}
private static boolean contains(Object[] array, Object object) {
for (Object elem : array) {
if (Comparing.equal(elem, object)) return true;
}
return false;
}
private void chooseTargetClass() {
myNeedChangeContext = false;
myTargetClass = (PsiClass)myCodeFragementMember.getParent();
if (myTargetClass instanceof PsiAnonymousClass) {
PsiElement target = myTargetClass.getParent();
PsiElement targetMember = myTargetClass;
while (true) {
if (target instanceof PsiFile) break;
if (target instanceof PsiClass && !(target instanceof PsiAnonymousClass)) break;
targetMember = target;
target = target.getParent();
}
if (target instanceof PsiClass) {
PsiClass newTargetClass = (PsiClass)target;
List<PsiVariable> array = new ArrayList<PsiVariable>();
boolean success = true;
for (PsiElement element : myElements) {
if (!ControlFlowUtil.collectOuterLocals(array, element, myCodeFragementMember, targetMember)) {
success = false;
break;
}
}
if (success) {
myTargetClass = newTargetClass;
PsiVariable[] newInputVariables = new PsiVariable[myInputVariables.length + array.size()];
System.arraycopy(myInputVariables, 0, newInputVariables, 0, myInputVariables.length);
for (int i = 0; i < array.size(); i++) {
newInputVariables[myInputVariables.length + i] = array.get(i);
}
myInputVariables = newInputVariables;
myNeedChangeContext = true;
}
}
}
}
private void chooseAnchor() {
myAnchor = myCodeFragementMember;
while (!myAnchor.getParent().equals(myTargetClass)) {
myAnchor = myAnchor.getParent();
}
}
private void showMultipleExitPointsMessage() {
if (myShowErrorDialogs) {
HighlightManager highlightManager = HighlightManager.getInstance(myProject);
PsiStatement[] exitStatementsArray = myExitStatements.toArray(new PsiStatement[myExitStatements.size()]);
EditorColorsManager manager = EditorColorsManager.getInstance();
TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
highlightManager.addOccurrenceHighlights(myEditor, exitStatementsArray, attributes, true, null);
String message = RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("there.are.multiple.exit.points.in.the.selected.code.fragment"));
CommonRefactoringUtil.showErrorMessage(myRefactoringName, message, myHelpId, myProject);
WindowManager.getInstance().getStatusBar(myProject).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
}
}
private void showMultipleOutputMessage(PsiType expressionType) {
if (myShowErrorDialogs) {
StringBuffer buffer = new StringBuffer();
buffer.append(RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("there.are.multiple.output.values.for.the.selected.code.fragment")));
buffer.append("\n");
if (myHasExpressionOutput) {
buffer.append(" ").append(RefactoringBundle.message("expression.result")).append(": ");
buffer.append(PsiFormatUtil.formatType(expressionType, 0, PsiSubstitutor.EMPTY));
buffer.append(",\n");
}
if (myGenerateConditionalExit) {
buffer.append(" ").append(RefactoringBundle.message("boolean.method.result"));
buffer.append(",\n");
}
for (int i = 0; i < myOutputVariables.length; i++) {
PsiVariable var = myOutputVariables[i];
buffer.append(" ");
buffer.append(var.getName());
buffer.append(" : ");
buffer.append(PsiFormatUtil.formatType(var.getType(), 0, PsiSubstitutor.EMPTY));
if (i < myOutputVariables.length - 1) {
buffer.append(",\n");
}
else {
buffer.append(".");
}
}
CommonRefactoringUtil.showErrorMessage(myRefactoringName, buffer.toString(), myHelpId, myProject);
}
}
public boolean hasDuplicates() {
final List<Match> duplicates = getDuplicates();
return duplicates != null && !duplicates.isEmpty();
}
} |
package com.scwang.smartrefresh.layout;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.NestedScrollingChildHelper;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.NestedScrollingParentHelper;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Scroller;
import android.widget.TextView;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer;
import com.scwang.smartrefresh.layout.api.RefreshContent;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshInternal;
import com.scwang.smartrefresh.layout.api.RefreshKernel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.api.ScrollBoundaryDecider;
import com.scwang.smartrefresh.layout.constant.DimensionStatus;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.impl.RefreshContentWrapper;
import com.scwang.smartrefresh.layout.impl.RefreshFooterWrapper;
import com.scwang.smartrefresh.layout.impl.RefreshHeaderWrapper;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnStateChangedListener;
import com.scwang.smartrefresh.layout.util.DelayedRunnable;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.scwang.smartrefresh.layout.util.ViscousFluidInterpolator;
import java.util.ArrayList;
import java.util.List;
import static android.view.MotionEvent.obtain;
import static android.view.View.MeasureSpec.AT_MOST;
import static android.view.View.MeasureSpec.EXACTLY;
import static android.view.View.MeasureSpec.getSize;
import static android.view.View.MeasureSpec.makeMeasureSpec;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static com.scwang.smartrefresh.layout.util.DensityUtil.dp2px;
import static com.scwang.smartrefresh.layout.util.SmartUtil.fling;
import static com.scwang.smartrefresh.layout.util.SmartUtil.getColor;
import static com.scwang.smartrefresh.layout.util.SmartUtil.isContentView;
import static java.lang.System.currentTimeMillis;
@SuppressLint("RestrictedApi")
@SuppressWarnings({"unused", "WeakerAccess"})
public class SmartRefreshLayout extends ViewGroup implements RefreshLayout, NestedScrollingParent/*, NestedScrollingChild*/ {
//<editor-fold desc=" property and variable">
//<editor-fold desc="">
protected int mTouchSlop;
protected int mSpinner;// Spinner
protected int mLastSpinner;//Spinner
protected int mTouchSpinner;//Spinner
protected int mFloorDuration = 250;
protected int mReboundDuration = 250;
protected int mScreenHeightPixels;
protected float mTouchX;
protected float mTouchY;
protected float mLastTouchX;//Header
protected float mLastTouchY;
protected float mDragRate = .5f;
protected char mDragDirection = 'n';// none-n horizontal-h vertical-v
protected boolean mIsBeingDragged;
protected boolean mSuperDispatchTouchEvent;
protected int mFixedHeaderViewId = View.NO_ID;
protected int mFixedFooterViewId = View.NO_ID;
protected int mHeaderTranslationViewId = View.NO_ID;//HeaderId
protected int mFooterTranslationViewId = View.NO_ID;//FooterId
protected int mMinimumVelocity;
protected int mMaximumVelocity;
protected int mCurrentVelocity;
protected Scroller mScroller;
protected VelocityTracker mVelocityTracker;
protected Interpolator mReboundInterpolator;
//</editor-fold>
//<editor-fold desc="">
protected int[] mPrimaryColors;
protected boolean mEnableRefresh = true;
protected boolean mEnableLoadMore = false;
protected boolean mEnableClipHeaderWhenFixedBehind = true;// Header FixedBehind Header
protected boolean mEnableClipFooterWhenFixedBehind = true;// Footer FixedBehind Footer
protected boolean mEnableHeaderTranslationContent = true;
protected boolean mEnableFooterTranslationContent = true;
protected boolean mEnableFooterFollowWhenLoadFinished = false;//Footer 1.0.4-6
protected boolean mEnablePreviewInEditMode = true;
protected boolean mEnableOverScrollBounce = true;
protected boolean mEnableOverScrollDrag = false;//1.0.4-6
protected boolean mEnableAutoLoadMore = true;
protected boolean mEnablePureScrollMode = false;
protected boolean mEnableScrollContentWhenLoaded = true;
protected boolean mEnableScrollContentWhenRefreshed = true;
protected boolean mEnableLoadMoreWhenContentNotFull = true;
protected boolean mDisableContentWhenRefresh = false;
protected boolean mDisableContentWhenLoading = false;
protected boolean mFooterNoMoreData = false;
protected boolean mManualLoadMore = false;//LoadMore
protected boolean mManualNestedScrolling = false;// NestedScrolling
protected boolean mManualHeaderTranslationContent = false;
protected boolean mManualFooterTranslationContent = false;
//</editor-fold>
//<editor-fold desc="">
protected OnRefreshListener mRefreshListener;
protected OnLoadMoreListener mLoadMoreListener;
protected OnMultiPurposeListener mOnMultiPurposeListener;
protected ScrollBoundaryDecider mScrollBoundaryDecider;
//</editor-fold>
//<editor-fold desc="">
protected int mTotalUnconsumed;
protected boolean mNestedInProgress;
protected int[] mParentOffsetInWindow = new int[2];
protected NestedScrollingChildHelper mNestedChild = new NestedScrollingChildHelper(this);
protected NestedScrollingParentHelper mNestedParent = new NestedScrollingParentHelper(this);
//</editor-fold>
//<editor-fold desc="">
protected int mHeaderHeight;
protected DimensionStatus mHeaderHeightStatus = DimensionStatus.DefaultUnNotify;
protected int mFooterHeight;
protected DimensionStatus mFooterHeightStatus = DimensionStatus.DefaultUnNotify;
protected int mHeaderInsetStart; // Header
protected int mFooterInsetStart; // Footer
protected float mHeaderMaxDragRate = 2.5f; //(/Header)
protected float mFooterMaxDragRate = 2.5f; //(/Footer)
protected float mHeaderTriggerRate = 1.0f; // HeaderHeight
protected float mFooterTriggerRate = 1.0f; // FooterHeight
protected RefreshInternal mRefreshHeader;
protected RefreshInternal mRefreshFooter;
protected RefreshContent mRefreshContent;
//</editor-fold>
protected Paint mPaint;
protected Handler mHandler;
protected RefreshKernel mKernel = new RefreshKernelImpl();
protected List<DelayedRunnable> mListDelayedRunnable;
protected RefreshState mState = RefreshState.None;
protected RefreshState mViceState = RefreshState.None;
protected long mLastOpenTime = 0;
protected int mHeaderBackgroundColor = 0; //Header
protected int mFooterBackgroundColor = 0;
protected boolean mHeaderNeedTouchEventWhenRefreshing; //Header
protected boolean mFooterNeedTouchEventWhenLoading;
protected boolean mFooterLocked = false;//Footer loading
protected static DefaultRefreshFooterCreator sFooterCreator = new DefaultRefreshFooterCreator() {
@NonNull
@Override
public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
return new BallPulseFooter(context);
}
};
protected static DefaultRefreshHeaderCreator sHeaderCreator = new DefaultRefreshHeaderCreator() {
@NonNull
@Override
public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
return new BezierRadarHeader(context);
}
};
protected static DefaultRefreshInitializer sRefreshInitializer;
//</editor-fold>
//<editor-fold desc=" construction methods">
public SmartRefreshLayout(Context context) {
this(context, null);
}
public SmartRefreshLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SmartRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
super.setClipToPadding(false);
DensityUtil density = new DensityUtil();
ViewConfiguration configuration = ViewConfiguration.get(context);
mScroller = new Scroller(context);
mVelocityTracker = VelocityTracker.obtain();
mScreenHeightPixels = context.getResources().getDisplayMetrics().heightPixels;
mReboundInterpolator = new ViscousFluidInterpolator();
mTouchSlop = configuration.getScaledTouchSlop();
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mFooterHeight = density.dip2px(60);
mHeaderHeight = density.dip2px(100);
if (sRefreshInitializer != null) {
sRefreshInitializer.initialize(context, this);
}
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SmartRefreshLayout);
mNestedChild.setNestedScrollingEnabled(ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableNestedScrolling, mNestedChild.isNestedScrollingEnabled()));
mDragRate = ta.getFloat(R.styleable.SmartRefreshLayout_srlDragRate, mDragRate);
mHeaderMaxDragRate = ta.getFloat(R.styleable.SmartRefreshLayout_srlHeaderMaxDragRate, mHeaderMaxDragRate);
mFooterMaxDragRate = ta.getFloat(R.styleable.SmartRefreshLayout_srlFooterMaxDragRate, mFooterMaxDragRate);
mHeaderTriggerRate = ta.getFloat(R.styleable.SmartRefreshLayout_srlHeaderTriggerRate, mHeaderTriggerRate);
mFooterTriggerRate = ta.getFloat(R.styleable.SmartRefreshLayout_srlFooterTriggerRate, mFooterTriggerRate);
mEnableRefresh = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableRefresh, mEnableRefresh);
mReboundDuration = ta.getInt(R.styleable.SmartRefreshLayout_srlReboundDuration, mReboundDuration);
mEnableLoadMore = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableLoadMore, mEnableLoadMore);
mHeaderHeight = ta.getDimensionPixelOffset(R.styleable.SmartRefreshLayout_srlHeaderHeight, mHeaderHeight);
mFooterHeight = ta.getDimensionPixelOffset(R.styleable.SmartRefreshLayout_srlFooterHeight, mFooterHeight);
mHeaderInsetStart = ta.getDimensionPixelOffset(R.styleable.SmartRefreshLayout_srlHeaderInsetStart, mHeaderInsetStart);
mFooterInsetStart = ta.getDimensionPixelOffset(R.styleable.SmartRefreshLayout_srlFooterInsetStart, mFooterInsetStart);
mDisableContentWhenRefresh = ta.getBoolean(R.styleable.SmartRefreshLayout_srlDisableContentWhenRefresh, mDisableContentWhenRefresh);
mDisableContentWhenLoading = ta.getBoolean(R.styleable.SmartRefreshLayout_srlDisableContentWhenLoading, mDisableContentWhenLoading);
mEnableHeaderTranslationContent = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableHeaderTranslationContent, mEnableHeaderTranslationContent);
mEnableFooterTranslationContent = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableFooterTranslationContent, mEnableFooterTranslationContent);
mEnablePreviewInEditMode = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnablePreviewInEditMode, mEnablePreviewInEditMode);
mEnableAutoLoadMore = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableAutoLoadMore, mEnableAutoLoadMore);
mEnableOverScrollBounce = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableOverScrollBounce, mEnableOverScrollBounce);
mEnablePureScrollMode = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnablePureScrollMode, mEnablePureScrollMode);
mEnableScrollContentWhenLoaded = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableScrollContentWhenLoaded, mEnableScrollContentWhenLoaded);
mEnableScrollContentWhenRefreshed = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableScrollContentWhenRefreshed, mEnableScrollContentWhenRefreshed);
mEnableLoadMoreWhenContentNotFull = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableLoadMoreWhenContentNotFull, mEnableLoadMoreWhenContentNotFull);
mEnableFooterFollowWhenLoadFinished = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableFooterFollowWhenLoadFinished, mEnableFooterFollowWhenLoadFinished);
mEnableClipHeaderWhenFixedBehind = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableClipHeaderWhenFixedBehind, mEnableClipHeaderWhenFixedBehind);
mEnableClipFooterWhenFixedBehind = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableClipFooterWhenFixedBehind, mEnableClipFooterWhenFixedBehind);
mEnableOverScrollDrag = ta.getBoolean(R.styleable.SmartRefreshLayout_srlEnableOverScrollDrag, mEnableOverScrollDrag);
mFixedHeaderViewId = ta.getResourceId(R.styleable.SmartRefreshLayout_srlFixedHeaderViewId, mFixedHeaderViewId);
mFixedFooterViewId = ta.getResourceId(R.styleable.SmartRefreshLayout_srlFixedFooterViewId, mFixedFooterViewId);
mHeaderTranslationViewId = ta.getResourceId(R.styleable.SmartRefreshLayout_srlHeaderTranslationViewId, mHeaderTranslationViewId);
mFooterTranslationViewId = ta.getResourceId(R.styleable.SmartRefreshLayout_srlFooterTranslationViewId, mFooterTranslationViewId);
if (mEnablePureScrollMode && !ta.hasValue(R.styleable.SmartRefreshLayout_srlEnableOverScrollDrag)) {
mEnableOverScrollDrag = true;
}
mManualLoadMore = ta.hasValue(R.styleable.SmartRefreshLayout_srlEnableLoadMore);
mManualHeaderTranslationContent = ta.hasValue(R.styleable.SmartRefreshLayout_srlEnableHeaderTranslationContent);
mManualFooterTranslationContent = ta.hasValue(R.styleable.SmartRefreshLayout_srlEnableFooterTranslationContent);
mManualNestedScrolling = mManualNestedScrolling || ta.hasValue(R.styleable.SmartRefreshLayout_srlEnableNestedScrolling);
mHeaderHeightStatus = ta.hasValue(R.styleable.SmartRefreshLayout_srlHeaderHeight) ? DimensionStatus.XmlLayoutUnNotify : mHeaderHeightStatus;
mFooterHeightStatus = ta.hasValue(R.styleable.SmartRefreshLayout_srlFooterHeight) ? DimensionStatus.XmlLayoutUnNotify : mFooterHeightStatus;
int accentColor = ta.getColor(R.styleable.SmartRefreshLayout_srlAccentColor, 0);
int primaryColor = ta.getColor(R.styleable.SmartRefreshLayout_srlPrimaryColor, 0);
if (primaryColor != 0) {
if (accentColor != 0) {
mPrimaryColors = new int[]{primaryColor, accentColor};
} else {
mPrimaryColors = new int[]{primaryColor};
}
} else if (accentColor != 0) {
mPrimaryColors = new int[]{0, accentColor};
}
ta.recycle();
}//86985902
//</editor-fold>
//<editor-fold desc=" life cycle">
@Override
protected void onFinishInflate() {
super.onFinishInflate();
final int count = super.getChildCount();
if (count > 3) {
throw new RuntimeException("3ViewMost only support three sub view");
}
int contentLevel = 0;
int indexContent = -1;
for (int i = 0; i < count; i++) {
View view = super.getChildAt(i);
if (isContentView(view) && (contentLevel < 2 || i == 1)) {
indexContent = i;
contentLevel = 2;
} else if (!(view instanceof RefreshInternal) && contentLevel < 1) {
indexContent = i;
contentLevel = i > 0 ? 1 : 0;
}
}
// int[] indexArray = {1,0,2};
// for (int index : indexArray) {
// if (index < count) {
// View view = super.getChildAt(index);
// if (!(view instanceof RefreshInternal)) {
// indexContent = index;
// if (isContentView(view)) {
// indexContent = index;
// break;
int indexHeader = -1;
int indexFooter = -1;
if (indexContent >= 0) {
mRefreshContent = new RefreshContentWrapper(super.getChildAt(indexContent));
if (indexContent == 1) {
indexHeader = 0;
if (count == 3) {
indexFooter = 2;
}
} else if (count == 2) {
indexFooter = 1;
}
}
for (int i = 0; i < count; i++) {
View view = super.getChildAt(i);
if (i == indexHeader || (i != indexFooter && indexHeader == -1 && mRefreshHeader == null && view instanceof RefreshHeader)) {
mRefreshHeader = (view instanceof RefreshHeader) ? (RefreshHeader) view : new RefreshHeaderWrapper(view);
} else if (i == indexFooter || (indexFooter == -1 && view instanceof RefreshFooter)) {
mEnableLoadMore = (mEnableLoadMore || !mManualLoadMore);
mRefreshFooter = (view instanceof RefreshFooter) ? (RefreshFooter) view : new RefreshFooterWrapper(view);
// } else if (mRefreshContent == null) {
// mRefreshContent = new RefreshContentWrapper(view);
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
final View thisView = this;
if (!thisView.isInEditMode()) {
if (mHandler == null) {
mHandler = new Handler();
}
if (mListDelayedRunnable != null) {
for (DelayedRunnable runnable : mListDelayedRunnable) {
mHandler.postDelayed(runnable, runnable.delayMillis);
}
mListDelayedRunnable.clear();
mListDelayedRunnable = null;
}
if (mRefreshHeader == null) {
setRefreshHeader(sHeaderCreator.createRefreshHeader(thisView.getContext(), this));
}
if (mRefreshFooter == null) {
setRefreshFooter(sFooterCreator.createRefreshFooter(thisView.getContext(), this));
} else {
mEnableLoadMore = mEnableLoadMore || !mManualLoadMore;
}
if (mRefreshContent == null) {
for (int i = 0, len = getChildCount(); i < len; i++) {
View view = getChildAt(i);
if ((mRefreshHeader == null || view != mRefreshHeader.getView())&&
(mRefreshFooter == null || view != mRefreshFooter.getView())) {
mRefreshContent = new RefreshContentWrapper(view);
}
}
}
if (mRefreshContent == null) {
final int padding = DensityUtil.dp2px(20);
final TextView errorView = new TextView(thisView.getContext());
errorView.setTextColor(0xffff6600);
errorView.setGravity(Gravity.CENTER);
errorView.setTextSize(20);
errorView.setText(R.string.srl_content_empty);
super.addView(errorView, MATCH_PARENT, MATCH_PARENT);
mRefreshContent = new RefreshContentWrapper(errorView);
mRefreshContent.getView().setPadding(padding, padding, padding, padding);
}
View fixedHeaderView = mFixedHeaderViewId > 0 ? thisView.findViewById(mFixedHeaderViewId) : null;
View fixedFooterView = mFixedFooterViewId > 0 ? thisView.findViewById(mFixedFooterViewId) : null;
mRefreshContent.setScrollBoundaryDecider(mScrollBoundaryDecider);
mRefreshContent.setEnableLoadMoreWhenContentNotFull(mEnableLoadMoreWhenContentNotFull);
mRefreshContent.setUpComponent(mKernel, fixedHeaderView, fixedFooterView);
if (mSpinner != 0) {
notifyStateChanged(RefreshState.None);
mRefreshContent.moveSpinner(mSpinner = 0, mHeaderTranslationViewId, mFooterTranslationViewId);
}
if (!mManualNestedScrolling && !isNestedScrollingEnabled()) {
post(new Runnable() {
@Override
public void run() {
final View thisView = SmartRefreshLayout.this;
for (ViewParent parent = thisView.getParent() ; parent != null ; ) {
if (parent instanceof NestedScrollingParent) {
View target = SmartRefreshLayout.this;
//noinspection RedundantCast
if (((NestedScrollingParent)parent).onStartNestedScroll(target,target,ViewCompat.SCROLL_AXIS_VERTICAL)) {
setNestedScrollingEnabled(true);
mManualNestedScrolling = false;
break;
}
}
if (parent instanceof View) {
View thisParent = (View) parent;
parent = thisParent.getParent();
} else {
break;
}
}
}
});
}
}
if (mPrimaryColors != null) {
if (mRefreshHeader != null) {
mRefreshHeader.setPrimaryColors(mPrimaryColors);
}
if (mRefreshFooter != null) {
mRefreshFooter.setPrimaryColors(mPrimaryColors);
}
}
if (mRefreshContent != null) {
super.bringChildToFront(mRefreshContent.getView());
}
if (mRefreshHeader != null && mRefreshHeader.getSpinnerStyle() != SpinnerStyle.FixedBehind) {
super.bringChildToFront(mRefreshHeader.getView());
}
if (mRefreshFooter != null && mRefreshFooter.getSpinnerStyle() != SpinnerStyle.FixedBehind) {
super.bringChildToFront(mRefreshFooter.getView());
}
}
@Override
protected void onMeasure(final int widthMeasureSpec,final int heightMeasureSpec) {
int minimumHeight = 0;
final View thisView = this;
final boolean isInEditMode = thisView.isInEditMode() && mEnablePreviewInEditMode;
for (int i = 0, len = super.getChildCount(); i < len; i++) {
View child = super.getChildAt(i);
if (mRefreshHeader != null && mRefreshHeader.getView() == child) {
final View headerView = mRefreshHeader.getView();
final LayoutParams lp = (LayoutParams) headerView.getLayoutParams();
final int widthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, lp.leftMargin + lp.rightMargin, lp.width);
int heightSpec = heightMeasureSpec;
if (mHeaderHeightStatus.gteStatusWith(DimensionStatus.XmlLayoutUnNotify)) {
heightSpec = makeMeasureSpec(Math.max(mHeaderHeight - lp.bottomMargin - lp.topMargin, 0), EXACTLY);
headerView.measure(widthSpec, heightSpec);
} else if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.MatchLayout) {
int headerHeight = 0;
if (!mHeaderHeightStatus.notified) {
super.measureChild(headerView, widthSpec, makeMeasureSpec(Math.max(getSize(heightSpec) - lp.bottomMargin - lp.topMargin, 0), AT_MOST));
headerHeight = headerView.getMeasuredHeight();
}
headerView.measure(widthSpec, makeMeasureSpec(Math.max(getSize(heightSpec) - lp.bottomMargin - lp.topMargin, 0), EXACTLY));
if (headerHeight > 0 && headerHeight != headerView.getMeasuredHeight()) {
mHeaderHeight = headerHeight + lp.bottomMargin + lp.topMargin;
}
} else if (lp.height > 0) {
if (mHeaderHeightStatus.canReplaceWith(DimensionStatus.XmlExactUnNotify)) {
mHeaderHeight = lp.height + lp.bottomMargin + lp.topMargin;
mHeaderHeightStatus = DimensionStatus.XmlExactUnNotify;
}
heightSpec = makeMeasureSpec(lp.height, EXACTLY);
headerView.measure(widthSpec, heightSpec);
} else if (lp.height == WRAP_CONTENT) {
heightSpec = makeMeasureSpec(Math.max(getSize(heightMeasureSpec) - lp.bottomMargin - lp.topMargin, 0), AT_MOST);
headerView.measure(widthSpec, heightSpec);
int measuredHeight = headerView.getMeasuredHeight();
if (measuredHeight > 0 && mHeaderHeightStatus.canReplaceWith(DimensionStatus.XmlWrapUnNotify)) {
mHeaderHeightStatus = DimensionStatus.XmlWrapUnNotify;
mHeaderHeight = headerView.getMeasuredHeight() + lp.bottomMargin + lp.topMargin;
} else if (measuredHeight <= 0) {
heightSpec = makeMeasureSpec(Math.max(mHeaderHeight - lp.bottomMargin - lp.topMargin, 0), EXACTLY);
headerView.measure(widthSpec, heightSpec);
}
} else if (lp.height == MATCH_PARENT) {
heightSpec = makeMeasureSpec(Math.max(mHeaderHeight - lp.bottomMargin - lp.topMargin, 0), EXACTLY);
headerView.measure(widthSpec, heightSpec);
} else {
headerView.measure(widthSpec, heightSpec);
}
if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.Scale && !isInEditMode) {
final int height = Math.max(0, isEnableRefreshOrLoadMore(mEnableRefresh) ? mSpinner : 0);
heightSpec = makeMeasureSpec(Math.max(height - lp.bottomMargin - lp.topMargin, 0), EXACTLY);
headerView.measure(widthSpec, heightSpec);
}
if (!mHeaderHeightStatus.notified) {
mHeaderHeightStatus = mHeaderHeightStatus.notified();
mRefreshHeader.onInitialized(mKernel, mHeaderHeight, (int) (mHeaderMaxDragRate * mHeaderHeight));
}
if (isInEditMode && isEnableRefreshOrLoadMore(mEnableRefresh)) {
minimumHeight += headerView.getMeasuredHeight();
}
}
if (mRefreshFooter != null && mRefreshFooter.getView() == child) {
final View footerView = mRefreshFooter.getView();
final LayoutParams lp = (LayoutParams) footerView.getLayoutParams();
final int widthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, lp.leftMargin + lp.rightMargin, lp.width);
int heightSpec = heightMeasureSpec;
if (mFooterHeightStatus.gteStatusWith(DimensionStatus.XmlLayoutUnNotify)) {
heightSpec = makeMeasureSpec(Math.max(mFooterHeight - lp.topMargin - lp.bottomMargin, 0), EXACTLY);
footerView.measure(widthSpec, heightSpec);
} else if (mRefreshFooter.getSpinnerStyle() == SpinnerStyle.MatchLayout) {
int footerHeight = 0;
if (!mFooterHeightStatus.notified) {
super.measureChild(footerView, widthSpec, makeMeasureSpec(getSize(heightSpec) - lp.topMargin - lp.bottomMargin, AT_MOST));
footerHeight = footerView.getMeasuredHeight();
}
footerView.measure(widthSpec, makeMeasureSpec(getSize(heightSpec) - lp.topMargin - lp.bottomMargin, EXACTLY));
if (footerHeight > 0 && footerHeight != footerView.getMeasuredHeight()) {
mHeaderHeight = footerHeight + lp.topMargin + lp.bottomMargin;
}
} else if (lp.height > 0) {
if (mFooterHeightStatus.canReplaceWith(DimensionStatus.XmlExactUnNotify)) {
mFooterHeight = lp.height + lp.topMargin + lp.bottomMargin;
mFooterHeightStatus = DimensionStatus.XmlExactUnNotify;
}
heightSpec = makeMeasureSpec(lp.height, EXACTLY);
footerView.measure(widthSpec, heightSpec);
} else if (lp.height == WRAP_CONTENT) {
heightSpec = makeMeasureSpec(Math.max(getSize(heightMeasureSpec) - lp.topMargin - lp.bottomMargin, 0), AT_MOST);
footerView.measure(widthSpec, heightSpec);
int measuredHeight = footerView.getMeasuredHeight();
if (measuredHeight > 0 && mFooterHeightStatus.canReplaceWith(DimensionStatus.XmlWrapUnNotify)) {
mFooterHeightStatus = DimensionStatus.XmlWrapUnNotify;
mFooterHeight = footerView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
} else if (measuredHeight <= 0) {
heightSpec = makeMeasureSpec(Math.max(mFooterHeight - lp.topMargin - lp.bottomMargin, 0), EXACTLY);
footerView.measure(widthSpec, heightSpec);
}
} else if (lp.height == MATCH_PARENT) {
heightSpec = makeMeasureSpec(Math.max(mFooterHeight - lp.topMargin - lp.bottomMargin, 0), EXACTLY);
footerView.measure(widthSpec, heightSpec);
} else {
footerView.measure(widthSpec, heightSpec);
}
if (mRefreshFooter.getSpinnerStyle() == SpinnerStyle.Scale && !isInEditMode) {
final int height = Math.max(0, mEnableLoadMore ? -mSpinner : 0);
heightSpec = makeMeasureSpec(Math.max(height - lp.topMargin - lp.bottomMargin, 0), EXACTLY);
footerView.measure(widthSpec, heightSpec);
}
if (!mFooterHeightStatus.notified) {
mFooterHeightStatus = mFooterHeightStatus.notified();
mRefreshFooter.onInitialized(mKernel, mFooterHeight, (int) (mFooterMaxDragRate * mFooterHeight));
}
if (isInEditMode && isEnableRefreshOrLoadMore(mEnableLoadMore)) {
minimumHeight += footerView.getMeasuredHeight();
}
}
if (mRefreshContent != null && mRefreshContent.getView() == child) {
final View contentView = mRefreshContent.getView();
final LayoutParams lp = (LayoutParams) contentView.getLayoutParams();
final int widthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec,
thisView.getPaddingLeft() + thisView.getPaddingRight() +
lp.leftMargin + lp.rightMargin, lp.width);
final int heightSpec = ViewGroup.getChildMeasureSpec(heightMeasureSpec,
thisView.getPaddingTop() + thisView.getPaddingBottom() +
lp.topMargin + lp.bottomMargin +
((isInEditMode && isEnableRefreshOrLoadMore(mEnableRefresh) && mRefreshHeader != null && isEnableTranslationContent(mEnableHeaderTranslationContent, mRefreshHeader)) ? mHeaderHeight : 0) +
((isInEditMode && isEnableRefreshOrLoadMore(mEnableLoadMore) && mRefreshFooter != null && isEnableTranslationContent(mEnableFooterTranslationContent, mRefreshFooter)) ? mFooterHeight : 0), lp.height);
contentView.measure(widthSpec, heightSpec);
minimumHeight += contentView.getMeasuredHeight();
}
}
super.setMeasuredDimension(
View.resolveSize(super.getSuggestedMinimumWidth(), widthMeasureSpec),
View.resolveSize(minimumHeight, heightMeasureSpec));
mLastTouchX = thisView.getMeasuredWidth() / 2;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final View thisView = this;
final int paddingLeft = thisView.getPaddingLeft();
final int paddingTop = thisView.getPaddingTop();
final int paddingBottom = thisView.getPaddingBottom();
for (int i = 0, len = super.getChildCount(); i < len; i++) {
View child = super.getChildAt(i);
if (mRefreshContent != null && mRefreshContent.getView() == child) {
boolean isPreviewMode = thisView.isInEditMode() && mEnablePreviewInEditMode && isEnableRefreshOrLoadMore(mEnableRefresh) && mRefreshHeader != null;
final View contentView = mRefreshContent.getView();
final LayoutParams lp = (LayoutParams) contentView.getLayoutParams();
int left = paddingLeft + lp.leftMargin;
int top = paddingTop + lp.topMargin;
int right = left + contentView.getMeasuredWidth();
int bottom = top + contentView.getMeasuredHeight();
if (isPreviewMode && (isEnableTranslationContent(mEnableHeaderTranslationContent, mRefreshHeader))) {
top = top + mHeaderHeight;
bottom = bottom + mHeaderHeight;
}
contentView.layout(left, top, right, bottom);
}
if (mRefreshHeader != null && mRefreshHeader.getView() == child) {
boolean isPreviewMode = thisView.isInEditMode() && mEnablePreviewInEditMode && isEnableRefreshOrLoadMore(mEnableRefresh);
final View headerView = mRefreshHeader.getView();
final LayoutParams lp = (LayoutParams) headerView.getLayoutParams();
int left = lp.leftMargin;
int top = lp.topMargin + mHeaderInsetStart;
int right = left + headerView.getMeasuredWidth();
int bottom = top + headerView.getMeasuredHeight();
if (!isPreviewMode) {
if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.Translate) {
top = top - mHeaderHeight;
bottom = bottom - mHeaderHeight;
/*
* SpinnerStyle.Scale headerView.getMeasuredHeight()
**/
// } else if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.Scale && mSpinner > 0) {
// bottom = top + Math.max(Math.max(0, isEnableRefreshOrLoadMore(mEnableRefresh) ? mSpinner : 0) - lp.bottomMargin - lp.topMargin, 0);
}
}
headerView.layout(left, top, right, bottom);
}
if (mRefreshFooter != null && mRefreshFooter.getView() == child) {
final boolean isPreviewMode = thisView.isInEditMode() && mEnablePreviewInEditMode && isEnableRefreshOrLoadMore(mEnableLoadMore);
final View footerView = mRefreshFooter.getView();
final LayoutParams lp = (LayoutParams) footerView.getLayoutParams();
final SpinnerStyle style = mRefreshFooter.getSpinnerStyle();
int left = lp.leftMargin;
int top = lp.topMargin + thisView.getMeasuredHeight() - mFooterInsetStart;
if (isPreviewMode
|| style == SpinnerStyle.FixedFront
|| style == SpinnerStyle.FixedBehind) {
top = top - mFooterHeight;
} else if (style == SpinnerStyle.Scale && mSpinner < 0) {
top = top - Math.max(isEnableRefreshOrLoadMore(mEnableLoadMore) ? -mSpinner : 0, 0);
}
int right = left + footerView.getMeasuredWidth();
int bottom = top + footerView.getMeasuredHeight();
footerView.layout(left, top, right, bottom);
}
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mKernel.moveSpinner(0, true);
notifyStateChanged(RefreshState.None);
if (mHandler != null) {
mHandler.removeCallbacksAndMessages(null);
mHandler = null;
}
if (mListDelayedRunnable != null) {
mListDelayedRunnable.clear();
mListDelayedRunnable = null;
}
mManualLoadMore = true;
mManualNestedScrolling = true;
animationRunnable = null;
if (reboundAnimator != null) {
reboundAnimator.removeAllListeners();
reboundAnimator.removeAllUpdateListeners();
reboundAnimator.cancel();
reboundAnimator = null;
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final View thisView = this;
final View contentView = mRefreshContent != null ? mRefreshContent.getView() : null;
if (mRefreshHeader != null && mRefreshHeader.getView() == child) {
if (!isEnableRefreshOrLoadMore(mEnableRefresh) || (!mEnablePreviewInEditMode && thisView.isInEditMode())) {
return true;
}
if (contentView != null) {
int bottom = Math.max(contentView.getTop() + contentView.getPaddingTop() + mSpinner, child.getTop());
if (mHeaderBackgroundColor != 0 && mPaint != null) {
mPaint.setColor(mHeaderBackgroundColor);
if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.Scale) {
bottom = child.getBottom();
} else if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.Translate) {
bottom = child.getBottom() + mSpinner;
}
canvas.drawRect(child.getLeft(), child.getTop(), child.getRight(), bottom, mPaint);
}
if (mEnableClipHeaderWhenFixedBehind && mRefreshHeader.getSpinnerStyle() == SpinnerStyle.FixedBehind) {
canvas.save();
canvas.clipRect(child.getLeft(), child.getTop(), child.getRight(), bottom);
boolean ret = super.drawChild(canvas, child, drawingTime);
canvas.restore();
return ret;
}
}
}
if (mRefreshFooter != null && mRefreshFooter.getView() == child) {
if (!isEnableRefreshOrLoadMore(mEnableLoadMore) || (!mEnablePreviewInEditMode && thisView.isInEditMode())) {
return true;
}
if (contentView != null) {
int top = Math.min(contentView.getBottom() - contentView.getPaddingBottom() + mSpinner, child.getBottom());
if (mFooterBackgroundColor != 0 && mPaint != null) {
mPaint.setColor(mFooterBackgroundColor);
if (mRefreshFooter.getSpinnerStyle() == SpinnerStyle.Scale) {
top = child.getTop();
} else if (mRefreshFooter.getSpinnerStyle() == SpinnerStyle.Translate) {
top = child.getTop() + mSpinner;
}
canvas.drawRect(child.getLeft(), top, child.getRight(), child.getBottom(), mPaint);
}
if (mEnableClipFooterWhenFixedBehind && mRefreshFooter.getSpinnerStyle() == SpinnerStyle.FixedBehind) {
canvas.save();
canvas.clipRect(child.getLeft(), top, child.getRight(), child.getBottom());
boolean ret = super.drawChild(canvas, child, drawingTime);
canvas.restore();
return ret;
}
}
}
return super.drawChild(canvas, child, drawingTime);
}
//<editor-fold desc="">
protected boolean mVerticalPermit = false;
@Override
public void computeScroll() {
int lastCurY = mScroller.getCurrY();
if (mScroller.computeScrollOffset()) {
int finalY = mScroller.getFinalY();
if ((finalY < 0 && (mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableRefresh)) && mRefreshContent.canRefresh())
|| (finalY > 0 && (mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableLoadMore)) && mRefreshContent.canLoadMore())) {
if(mVerticalPermit) {
float velocity;
if (Build.VERSION.SDK_INT >= 14) {
velocity = finalY > 0 ? -mScroller.getCurrVelocity() : mScroller.getCurrVelocity();
} else {
velocity = 1f * (mScroller.getCurrY() - finalY) / Math.max((mScroller.getDuration() - mScroller.timePassed()), 1);
}
animSpinnerBounce(velocity);
}
mScroller.forceFinished(true);
} else {
mVerticalPermit = true;
final View thisView = this;
thisView.invalidate();
}
}
}
//</editor-fold>
//</editor-fold>
//<editor-fold desc=" judgement of slide">
protected MotionEvent mFalsifyEvent = null;
@Override
public boolean dispatchTouchEvent(MotionEvent e) {
//<editor-fold desc="">
final int action = e.getActionMasked();
final boolean pointerUp = action == MotionEvent.ACTION_POINTER_UP;
final int skipIndex = pointerUp ? e.getActionIndex() : -1;
// Determine focal point
float sumX = 0, sumY = 0;
final int count = e.getPointerCount();
for (int i = 0; i < count; i++) {
if (skipIndex == i) continue;
sumX += e.getX(i);
sumY += e.getY(i);
}
final int div = pointerUp ? count - 1 : count;
final float touchX = sumX / div;
final float touchY = sumY / div;
if ((action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_POINTER_DOWN)
&& mIsBeingDragged) {
mTouchY += touchY - mLastTouchY;
}
mLastTouchX = touchX;
mLastTouchY = touchY;
//</editor-fold>
final View thisView = this;
if (mNestedInProgress) {// onHorizontalDrag
int totalUnconsumed = mTotalUnconsumed;
boolean ret = super.dispatchTouchEvent(e);
//noinspection ConstantConditions
if (action == MotionEvent.ACTION_MOVE) {
if (totalUnconsumed == mTotalUnconsumed) {
final int offsetX = (int) mLastTouchX;
final int offsetMax = thisView.getWidth();
final float percentX = mLastTouchX / (offsetMax == 0 ? 1 : offsetMax);
if (isEnableRefreshOrLoadMore(mEnableRefresh) && mSpinner > 0 && mRefreshHeader != null && mRefreshHeader.isSupportHorizontalDrag()) {
mRefreshHeader.onHorizontalDrag(percentX, offsetX, offsetMax);
} else if (isEnableRefreshOrLoadMore(mEnableLoadMore) && mSpinner < 0 && mRefreshFooter != null && mRefreshFooter.isSupportHorizontalDrag()) {
mRefreshFooter.onHorizontalDrag(percentX, offsetX, offsetMax);
}
}
}
return ret;
} else if (!thisView.isEnabled()
|| (!isEnableRefreshOrLoadMore(mEnableRefresh) && !isEnableRefreshOrLoadMore(mEnableLoadMore) && !mEnableOverScrollDrag)
|| (mHeaderNeedTouchEventWhenRefreshing && ((mState.isOpening || mState.isFinishing) && mState.isHeader))
|| (mFooterNeedTouchEventWhenLoading && ((mState.isOpening || mState.isFinishing) && mState.isFooter))) {
return super.dispatchTouchEvent(e);
}
if (interceptAnimatorByAction(action) || mState.isFinishing
|| (mState == RefreshState.Loading && mDisableContentWhenLoading)
|| (mState == RefreshState.Refreshing && mDisableContentWhenRefresh)) {
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mCurrentVelocity = 0;
mVelocityTracker.addMovement(e);
mScroller.forceFinished(true);
mTouchX = touchX;
mTouchY = touchY;
mLastSpinner = 0;
mTouchSpinner = mSpinner;
mIsBeingDragged = false;
mSuperDispatchTouchEvent = super.dispatchTouchEvent(e);
if (mState == RefreshState.TwoLevel && mTouchY < 5 * thisView.getMeasuredHeight() / 6) {
mDragDirection = 'h';
return mSuperDispatchTouchEvent;
}
if (mRefreshContent != null) {
// RefreshContent View
mRefreshContent.onActionDown(e);
}
return true;
case MotionEvent.ACTION_MOVE:
float dx = touchX - mTouchX;
float dy = touchY - mTouchY;
mVelocityTracker.addMovement(e);
if (!mIsBeingDragged && mDragDirection != 'h' && mRefreshContent != null) {// canRefresh canLoadMore
if (mDragDirection == 'v' || (Math.abs(dy) >= mTouchSlop && Math.abs(dx) < Math.abs(dy))) {
mDragDirection = 'v';
if (dy > 0 && (mSpinner < 0 || ((mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableRefresh)) && mRefreshContent.canRefresh()))) {
mIsBeingDragged = true;
mTouchY = touchY - mTouchSlop;// mTouchSlop
} else if (dy < 0 && (mSpinner > 0 || ((mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableLoadMore)) && ((mState==RefreshState.Loading&&mFooterLocked)||mRefreshContent.canLoadMore())))) {
mIsBeingDragged = true;
mTouchY = touchY + mTouchSlop;// mTouchSlop
}
if (mIsBeingDragged) {
dy = touchY - mTouchY;// mTouchSlop dy
if (mSuperDispatchTouchEvent) {
e.setAction(MotionEvent.ACTION_CANCEL);
super.dispatchTouchEvent(e);
}
if (mSpinner > 0 || (mSpinner == 0 && dy > 0)) {
mKernel.setState(RefreshState.PullDownToRefresh);
} else {
mKernel.setState(RefreshState.PullUpToLoad);
}
ViewParent parent = thisView.getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
} else if (Math.abs(dx) >= mTouchSlop && Math.abs(dx) > Math.abs(dy) && mDragDirection != 'v') {
mDragDirection = 'h';
}
}
if (mIsBeingDragged) {
int spinner = (int) dy + mTouchSpinner;
if ((mViceState.isHeader && (spinner < 0 || mLastSpinner < 0)) || (mViceState.isFooter && (spinner > 0 || mLastSpinner > 0))) {
mLastSpinner = spinner;
long time = e.getEventTime();
if (mFalsifyEvent == null) {
mFalsifyEvent = obtain(time, time, MotionEvent.ACTION_DOWN, mTouchX + dx, mTouchY, 0);
super.dispatchTouchEvent(mFalsifyEvent);
}
MotionEvent em = obtain(time, time, MotionEvent.ACTION_MOVE, mTouchX + dx, mTouchY + spinner, 0);
super.dispatchTouchEvent(em);
if (mFooterLocked && dy > mTouchSlop && mSpinner < 0) {
mFooterLocked = false;// Footer
}
if (spinner > 0 && ((mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableRefresh)) && mRefreshContent.canRefresh())) {
mTouchY = mLastTouchY = touchY;
mTouchSpinner = spinner = 0;
mKernel.setState(RefreshState.PullDownToRefresh);
} else if (spinner < 0 && ((mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableLoadMore)) && mRefreshContent.canLoadMore())) {
mTouchY = mLastTouchY = touchY;
mTouchSpinner = spinner = 0;
mKernel.setState(RefreshState.PullUpToLoad);
}
if ((mViceState.isHeader && spinner < 0) || (mViceState.isFooter && spinner > 0)) {
if (mSpinner != 0) {
moveSpinnerInfinitely(0);
}
return true;
} else if (mFalsifyEvent != null) {
mFalsifyEvent = null;
em.setAction(MotionEvent.ACTION_CANCEL);
super.dispatchTouchEvent(em);
}
em.recycle();
}
moveSpinnerInfinitely(spinner);
return true;
} else if (mFooterLocked && dy > mTouchSlop && mSpinner < 0) {
mFooterLocked = false;// Footer
}
break;
case MotionEvent.ACTION_UP:
mVelocityTracker.addMovement(e);
mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
mCurrentVelocity = (int) mVelocityTracker.getYVelocity();
startFlingIfNeed(null);
case MotionEvent.ACTION_CANCEL:
// mRefreshContent.onActionUpOrCancel();
mVelocityTracker.clear();
mDragDirection = 'n';
if (mFalsifyEvent != null) {
mFalsifyEvent.recycle();
mFalsifyEvent = null;
long time = e.getEventTime();
MotionEvent ec = obtain(time, time, action, mTouchX, touchY, 0);
super.dispatchTouchEvent(ec);
ec.recycle();
}
overSpinner();
if (mIsBeingDragged) {
mIsBeingDragged = false;
return true;
}
break;
}
return super.dispatchTouchEvent(e);
}
/**
* @param flingVelocity
* @return true Fling
*/
protected boolean startFlingIfNeed(Float flingVelocity) {
final float velocity = flingVelocity == null ? mCurrentVelocity : flingVelocity;
if (Math.abs(velocity) > mMinimumVelocity) {
if (velocity * mSpinner < 0) {
if (mState.isOpening) {
if (mState != RefreshState.TwoLevel && mState != mViceState) {
/*
*
*
* :loading refreshing noMoreData
*/
animationRunnable = new FlingRunnable(velocity).start();
return true;
}
} else if (mSpinner > mHeaderHeight * mHeaderTriggerRate || -mSpinner > mFooterHeight * mFooterTriggerRate) {
return true;// Fling
}
}
if ((velocity < 0 && ((mEnableOverScrollBounce && (mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableLoadMore))) || (mState == RefreshState.Loading && mSpinner >= 0) || (mEnableAutoLoadMore&&isEnableRefreshOrLoadMore(mEnableLoadMore))))
|| (velocity > 0 && ((mEnableOverScrollBounce && (mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableRefresh))) || (mState == RefreshState.Refreshing && mSpinner <= 0)))) {
mVerticalPermit = false;
mScroller.fling(0, 0, 0, (int) -velocity, 0, 0, -Integer.MAX_VALUE, Integer.MAX_VALUE);
mScroller.computeScrollOffset();
final View thisView = this;
thisView.invalidate();
}
}
return false;
}
protected boolean interceptAnimatorByAction(int action) {
if (action == MotionEvent.ACTION_DOWN) {
if (reboundAnimator != null) {
if (mState.isFinishing || mState == RefreshState.TwoLevelReleased) {
return true;
}
if (mState == RefreshState.PullDownCanceled) {
mKernel.setState(RefreshState.PullDownToRefresh);
} else if (mState == RefreshState.PullUpCanceled) {
mKernel.setState(RefreshState.PullUpToLoad);
}
reboundAnimator.cancel();
reboundAnimator = null;
}
animationRunnable = null;
}
return reboundAnimator != null;
}
// /*
// * SwipeRefreshLayout
// *
// *
// */
// @Override
// public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// // if this is a List < L or another view that doesn't support nested
// // scrolling, ignore this request so that the vertical scroll event
// // isn't stolen
// View target = mRefreshContent.getScrollableView();
// if ((android.os.Build.VERSION.SDK_INT >= 21 || !(target instanceof AbsListView))
// && (target == null || ViewCompat.isNestedScrollingEnabled(target))) {
// super.requestDisallowInterceptTouchEvent(disallowIntercept);
// //} else {
// // Nope.
//</editor-fold>
//<editor-fold desc=" state changes">
protected void notifyStateChanged(RefreshState state) {
final RefreshState oldState = mState;
if (oldState != state) {
mState = state;
mViceState = state;
final OnStateChangedListener refreshHeader = mRefreshHeader;
final OnStateChangedListener refreshFooter = mRefreshFooter;
final OnStateChangedListener refreshListener = mOnMultiPurposeListener;
if (refreshHeader != null) {
refreshHeader.onStateChanged(this, oldState, state);
}
if (refreshFooter != null) {
refreshFooter.onStateChanged(this, oldState, state);
}
if (refreshListener != null) {
refreshListener.onStateChanged(this, oldState, state);
}
}
}
protected void setStateDirectLoading() {
if (mState != RefreshState.Loading) {
mLastOpenTime = currentTimeMillis();
// if (mState != RefreshState.LoadReleased) {
// if (mState != RefreshState.ReleaseToLoad) {
// if (mState != RefreshState.PullUpToLoad) {
// mKernel.setState(RefreshState.PullUpToLoad);
// mKernel.setState(RefreshState.ReleaseToLoad);
// notifyStateChanged(RefreshState.LoadReleased);
// if (mRefreshFooter != null) {
// mRefreshFooter.onReleased(this, mFooterHeight, (int) (mFooterMaxDragRate * mFooterHeight));
mFooterLocked = true;
notifyStateChanged(RefreshState.Loading);
if (mLoadMoreListener != null) {
mLoadMoreListener.onLoadMore(this);
} else if (mOnMultiPurposeListener == null) {
finishLoadMore(2000);
}
if (mRefreshFooter != null) {
mRefreshFooter.onStartAnimator(this, mFooterHeight, (int) (mFooterMaxDragRate * mFooterHeight));
}
if (mOnMultiPurposeListener != null && mRefreshFooter instanceof RefreshFooter) {
mOnMultiPurposeListener.onLoadMore(this);
mOnMultiPurposeListener.onFooterStartAnimator((RefreshFooter) mRefreshFooter, mFooterHeight, (int) (mFooterMaxDragRate * mFooterHeight));
}
}
}
protected void setStateLoading() {
AnimatorListenerAdapter listener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
setStateDirectLoading();
}
};
notifyStateChanged(RefreshState.LoadReleased);
ValueAnimator animator = mKernel.animSpinner(-mFooterHeight);
if (animator != null) {
animator.addListener(listener);
}
if (mRefreshFooter != null) {
//onReleased animSpinner onAnimationEnd
// onReleased animSpinner
mRefreshFooter.onReleased(this, mFooterHeight, (int) (mFooterMaxDragRate * mFooterHeight));
}
if (mOnMultiPurposeListener != null && mRefreshFooter instanceof RefreshFooter) {
// mRefreshFooter.onReleased
mOnMultiPurposeListener.onFooterReleased((RefreshFooter) mRefreshFooter, mFooterHeight, (int) (mFooterMaxDragRate * mFooterHeight));
}
if (animator == null) {
//onAnimationEnd loading onReleased
listener.onAnimationEnd(null);
}
}
protected void setStateRefreshing() {
AnimatorListenerAdapter listener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLastOpenTime = currentTimeMillis();
notifyStateChanged(RefreshState.Refreshing);
if (mRefreshListener != null) {
mRefreshListener.onRefresh(SmartRefreshLayout.this);
} else if (mOnMultiPurposeListener == null) {
finishRefresh(3000);
}
if (mRefreshHeader != null) {
mRefreshHeader.onStartAnimator(SmartRefreshLayout.this, mHeaderHeight, (int) (mHeaderMaxDragRate * mHeaderHeight));
}
if (mOnMultiPurposeListener != null && mRefreshHeader instanceof RefreshHeader) {
mOnMultiPurposeListener.onRefresh(SmartRefreshLayout.this);
mOnMultiPurposeListener.onHeaderStartAnimator((RefreshHeader) mRefreshHeader, mHeaderHeight, (int) (mHeaderMaxDragRate * mHeaderHeight));
}
}
};
notifyStateChanged(RefreshState.RefreshReleased);
ValueAnimator animator = mKernel.animSpinner(mHeaderHeight);
if (animator != null) {
animator.addListener(listener);
}
if (mRefreshHeader != null) {
//onReleased animSpinner onAnimationEnd
// onRefreshReleased animSpinner
mRefreshHeader.onReleased(this, mHeaderHeight, (int) (mHeaderMaxDragRate * mHeaderHeight));
}
if (mOnMultiPurposeListener != null && mRefreshHeader instanceof RefreshHeader) {
// mRefreshHeader.onReleased
mOnMultiPurposeListener.onHeaderReleased((RefreshHeader)mRefreshHeader, mHeaderHeight, (int) (mHeaderMaxDragRate * mHeaderHeight));
}
if (animator == null) {
//onAnimationEnd Refreshing onReleased
listener.onAnimationEnd(null);
}
}
protected void resetStatus() {
if (mState != RefreshState.None) {
if (mSpinner == 0) {
notifyStateChanged(RefreshState.None);
}
}
if (mSpinner != 0) {
mKernel.animSpinner(0);
}
}
protected void setViceState(RefreshState state) {
if (mState.isDragging && mState.isHeader != state.isHeader) {
notifyStateChanged(RefreshState.None);
}
if (mViceState != state) {
mViceState = state;
}
}
protected boolean isEnableTranslationContent(boolean enable, RefreshInternal internal) {
return enable || mEnablePureScrollMode || internal == null || internal.getSpinnerStyle() == SpinnerStyle.FixedBehind;
}
protected boolean isEnableRefreshOrLoadMore(boolean enable) {
return enable && !mEnablePureScrollMode;
}
//</editor-fold>
//<editor-fold desc=" displacement">
//<editor-fold desc=" Animator Listener">
protected Runnable animationRunnable;
protected ValueAnimator reboundAnimator;
protected class FlingRunnable implements Runnable {
int mOffset;
int mFrame = 0;
int mFrameDelay = 10;
float mVelocity;
float mDamping = 0.98f;
long mStartTime = 0;
long mLastTime = AnimationUtils.currentAnimationTimeMillis();
FlingRunnable(float velocity) {
mVelocity = velocity;
mOffset = mSpinner;
}
public Runnable start() {
if (mState.isFinishing) {
return null;
}
if (mSpinner != 0 && (!(mState.isOpening || (mFooterNoMoreData && mEnableFooterFollowWhenLoadFinished && isEnableRefreshOrLoadMore(mEnableLoadMore)))
|| ((mState == RefreshState.Loading || (mFooterNoMoreData && mEnableFooterFollowWhenLoadFinished && isEnableRefreshOrLoadMore(mEnableLoadMore))) && mSpinner < -mFooterHeight)
|| (mState == RefreshState.Refreshing && mSpinner > mHeaderHeight))) {
int frame = 0;
int offset = mSpinner;
int spinner = mSpinner;
float velocity = mVelocity;
while (spinner * offset > 0) {
velocity *= Math.pow(mDamping, (++frame) * mFrameDelay / 10);
float velocityFrame = (velocity * (1f * mFrameDelay / 1000));
if (Math.abs(velocityFrame) < 1) {
if (!mState.isOpening
|| (mState == RefreshState.Refreshing && offset > mHeaderHeight)
|| (mState != RefreshState.Refreshing && offset < -mFooterHeight)) {
return null;
}
break;
}
offset += velocityFrame;
}
}
mStartTime = AnimationUtils.currentAnimationTimeMillis();
postDelayed(this, mFrameDelay);
return this;
}
@Override
public void run() {
if (animationRunnable == this && !mState.isFinishing) {
// mVelocity *= Math.pow(mDamping, ++mFrame);
long now = AnimationUtils.currentAnimationTimeMillis();
long span = now - mLastTime;
mVelocity *= Math.pow(mDamping, (now - mStartTime) / (1000 / mFrameDelay));
float velocity = (mVelocity * (1f * span / 1000));
if (Math.abs(velocity) > 1) {
mLastTime = now;
mOffset += velocity;
if (mSpinner * mOffset > 0) {
mKernel.moveSpinner(mOffset, true);
postDelayed(this, mFrameDelay);
} else {
animationRunnable = null;
mKernel.moveSpinner(0, true);
fling(mRefreshContent.getScrollableView(), (int) -mVelocity);
if (mFooterLocked && velocity > 0) {
mFooterLocked = false;
}
}
} else {
animationRunnable = null;
}
}
}
}
protected class BounceRunnable implements Runnable {
int mFrame = 0;
int mFrameDelay = 10;
int mSmoothDistance;
long mLastTime;
float mOffset = 0;
float mVelocity;
BounceRunnable(float velocity, int smoothDistance){
mVelocity = velocity;
mSmoothDistance = smoothDistance;
mLastTime = AnimationUtils.currentAnimationTimeMillis();
postDelayed(this, mFrameDelay);
}
@Override
public void run() {
if (animationRunnable == this && !mState.isFinishing) {
if (Math.abs(mSpinner) >= Math.abs(mSmoothDistance)) {
if (mSmoothDistance != 0) {
mVelocity *= Math.pow(0.45f, ++mFrame);
} else {
mVelocity *= Math.pow(0.85f, ++mFrame);
}
} else {
mVelocity *= Math.pow(0.95f, ++mFrame);
}
long now = AnimationUtils.currentAnimationTimeMillis();
float t = 1f * (now - mLastTime) / 1000;
float velocity = mVelocity * t;
if (Math.abs(velocity) >= 1) {
mLastTime = now;
mOffset += velocity;
moveSpinnerInfinitely(mOffset);
postDelayed(this, mFrameDelay);
} else {
animationRunnable = null;
if (Math.abs(mSpinner) >= Math.abs(mSmoothDistance)) {
int duration = 10 * Math.min(Math.max((int) DensityUtil.px2dp(Math.abs(mSpinner-mSmoothDistance)), 30), 100);
animSpinner(mSmoothDistance, 0, mReboundInterpolator, duration);
}
}
}
}
}
//</editor-fold>
protected ValueAnimator animSpinner(int endSpinner, int startDelay, Interpolator interpolator, int duration) {
if (mSpinner != endSpinner) {
if (reboundAnimator != null) {
reboundAnimator.cancel();
}
animationRunnable = null;
reboundAnimator = ValueAnimator.ofInt(mSpinner, endSpinner);
reboundAnimator.setDuration(duration);
reboundAnimator.setInterpolator(interpolator);
reboundAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationEnd(animation);
}
@Override
public void onAnimationEnd(Animator animation) {
reboundAnimator = null;
if (mSpinner == 0) {
if (mState != RefreshState.None && !mState.isOpening) {
notifyStateChanged(RefreshState.None);
}
} else if (mState != mViceState) {
setViceState(mState);
}
}
});
reboundAnimator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mKernel.moveSpinner((int) animation.getAnimatedValue(), false);
}
});
reboundAnimator.setStartDelay(startDelay);
// reboundAnimator.setDuration(20000);
reboundAnimator.start();
return reboundAnimator;
}
return null;
}
protected void animSpinnerBounce(final float velocity) {
if (reboundAnimator == null) {
if (velocity > 0 && (mState == RefreshState.Refreshing || mState == RefreshState.TwoLevel)) {
animationRunnable = new BounceRunnable(velocity, mHeaderHeight);
} else if (velocity < 0 && (mState == RefreshState.Loading
|| (mEnableFooterFollowWhenLoadFinished && mFooterNoMoreData && isEnableRefreshOrLoadMore(mEnableLoadMore))
|| (mEnableAutoLoadMore && !mFooterNoMoreData && isEnableRefreshOrLoadMore(mEnableLoadMore) && mState != RefreshState.Refreshing))) {
animationRunnable = new BounceRunnable(velocity, -mFooterHeight);
} else if (mSpinner == 0 && mEnableOverScrollBounce) {
animationRunnable = new BounceRunnable(velocity, 0);
}
}
}
protected void overSpinner() {
if (mState == RefreshState.TwoLevel) {
final View thisView = this;
if (mCurrentVelocity > -1000 && mSpinner > thisView.getMeasuredHeight() / 2) {
ValueAnimator animator = mKernel.animSpinner(thisView.getMeasuredHeight());
if (animator != null) {
animator.setDuration(mFloorDuration);
}
} else if (mIsBeingDragged) {
mKernel.finishTwoLevel();
}
} else if (mState == RefreshState.Loading
|| (mEnableFooterFollowWhenLoadFinished && mFooterNoMoreData && mSpinner < 0 && isEnableRefreshOrLoadMore(mEnableLoadMore))) {
if (mSpinner < -mFooterHeight) {
mKernel.animSpinner(-mFooterHeight);
} else if (mSpinner > 0) {
mKernel.animSpinner(0);
}
} else if (mState == RefreshState.Refreshing) {
if (mSpinner > mHeaderHeight) {
mKernel.animSpinner(mHeaderHeight);
} else if (mSpinner < 0) {
mKernel.animSpinner(0);
}
} else if (mState == RefreshState.PullDownToRefresh) {
mKernel.setState(RefreshState.PullDownCanceled);
} else if (mState == RefreshState.PullUpToLoad) {
mKernel.setState(RefreshState.PullUpCanceled);
} else if (mState == RefreshState.ReleaseToRefresh) {
mKernel.setState(RefreshState.Refreshing);
} else if (mState == RefreshState.ReleaseToLoad) {
mKernel.setState(RefreshState.Loading);
} else if (mState == RefreshState.ReleaseToTwoLevel) {
mKernel.setState(RefreshState.TwoLevelReleased);
} else if (mState == RefreshState.RefreshReleased) {
if (reboundAnimator == null) {
mKernel.animSpinner(mHeaderHeight);
}
} else if (mState == RefreshState.LoadReleased) {
if (reboundAnimator == null) {
mKernel.animSpinner(-mFooterHeight);
}
} else if (mSpinner != 0) {
mKernel.animSpinner(0);
}
}
protected void moveSpinnerInfinitely(float spinner) {
final View thisView = this;
if (mState == RefreshState.TwoLevel && spinner > 0) {
mKernel.moveSpinner(Math.min((int) spinner, thisView.getMeasuredHeight()), true);
} else if (mState == RefreshState.Refreshing && spinner >= 0) {
if (spinner < mHeaderHeight) {
mKernel.moveSpinner((int) spinner, true);
} else {
final double M = (mHeaderMaxDragRate - 1) * mHeaderHeight;
final double H = Math.max(mScreenHeightPixels * 4 / 3, thisView.getHeight()) - mHeaderHeight;
final double x = Math.max(0, (spinner - mHeaderHeight) * mDragRate);
final double y = Math.min(M * (1 - Math.pow(100, -x / (H == 0 ? 1 : H))), x);// y = M(1-100^(-x/H))
mKernel.moveSpinner((int) y + mHeaderHeight, true);
}
} else if (spinner < 0 && (mState == RefreshState.Loading
|| (mEnableFooterFollowWhenLoadFinished && mFooterNoMoreData && isEnableRefreshOrLoadMore(mEnableLoadMore))
|| (mEnableAutoLoadMore && !mFooterNoMoreData && isEnableRefreshOrLoadMore(mEnableLoadMore)))) {
if (spinner > -mFooterHeight) {
mKernel.moveSpinner((int) spinner, true);
} else {
final double M = (mFooterMaxDragRate - 1) * mFooterHeight;
final double H = Math.max(mScreenHeightPixels * 4 / 3, thisView.getHeight()) - mFooterHeight;
final double x = -Math.min(0, (spinner + mFooterHeight) * mDragRate);
final double y = -Math.min(M * (1 - Math.pow(100, -x / (H == 0 ? 1 : H))), x);// y = M(1-100^(-x/H))
mKernel.moveSpinner((int) y - mFooterHeight, true);
}
} else if (spinner >= 0) {
final double M = mHeaderMaxDragRate * mHeaderHeight;
final double H = Math.max(mScreenHeightPixels / 2, thisView.getHeight());
final double x = Math.max(0, spinner * mDragRate);
final double y = Math.min(M * (1 - Math.pow(100, -x / (H == 0 ? 1 : H))), x);// y = M(1-100^(-x/H))
mKernel.moveSpinner((int) y, true);
} else {
final double M = mFooterMaxDragRate * mFooterHeight;
final double H = Math.max(mScreenHeightPixels / 2, thisView.getHeight());
final double x = -Math.min(0, spinner * mDragRate);
final double y = -Math.min(M * (1 - Math.pow(100, -x / (H == 0 ? 1 : H))), x);// y = M(1-100^(-x/H))
mKernel.moveSpinner((int) y, true);
}
if (mEnableAutoLoadMore && !mFooterNoMoreData && isEnableRefreshOrLoadMore(mEnableLoadMore) && spinner < 0
&& mState != RefreshState.Refreshing
&& mState != RefreshState.Loading
&& mState != RefreshState.LoadFinish) {
setStateDirectLoading();
if (mDisableContentWhenLoading) {
animationRunnable = null;
mKernel.animSpinner(-mFooterHeight);
}
}
}
//</editor-fold>
//<editor-fold desc=" LayoutParams">
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(MATCH_PARENT, MATCH_PARENT);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
final View thisView = this;
return new LayoutParams(thisView.getContext(), attrs);
}
public static class LayoutParams extends MarginLayoutParams {
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SmartRefreshLayout_Layout);
backgroundColor = ta.getColor(R.styleable.SmartRefreshLayout_Layout_layout_srlBackgroundColor, backgroundColor);
if (ta.hasValue(R.styleable.SmartRefreshLayout_Layout_layout_srlSpinnerStyle)) {
spinnerStyle = SpinnerStyle.values()[ta.getInt(R.styleable.SmartRefreshLayout_Layout_layout_srlSpinnerStyle, SpinnerStyle.Translate.ordinal())];
}
ta.recycle();
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public int backgroundColor = 0;
public SpinnerStyle spinnerStyle = null;
}
//</editor-fold>
//<editor-fold desc=" NestedScrolling">
//<editor-fold desc="NestedScrollingParent">
@Override
public int getNestedScrollAxes() {
return mNestedParent.getNestedScrollAxes();
}
@Override
public boolean onStartNestedScroll(@NonNull View child, @NonNull View target, int nestedScrollAxes) {
final View thisView = this;
boolean accepted = thisView.isEnabled() && isNestedScrollingEnabled() && (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
accepted = accepted && (mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableRefresh) || isEnableRefreshOrLoadMore(mEnableLoadMore));
return accepted;
}
@Override
public void onNestedScrollAccepted(@NonNull View child, @NonNull View target, int axes) {
// Reset the counter of how much leftover scroll needs to be consumed.
mNestedParent.onNestedScrollAccepted(child, target, axes);
// Dispatch up to the nested parent
mNestedChild.startNestedScroll(axes & ViewCompat.SCROLL_AXIS_VERTICAL);
mTotalUnconsumed = mSpinner;
mNestedInProgress = true;
}
@Override
public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed) {
// If we are in the middle of consuming, a scroll, then we want to move the spinner back up
// before allowing the list to scroll
int consumedY = 0;
if (dy * mTotalUnconsumed > 0) {
if (Math.abs(dy) > Math.abs(mTotalUnconsumed)) {
consumedY = mTotalUnconsumed;
mTotalUnconsumed = 0;
} else {
consumedY = dy;
mTotalUnconsumed -= dy;
}
moveSpinnerInfinitely(mTotalUnconsumed);
if (mViceState.isOpening || mViceState == RefreshState.None) {
if (mSpinner > 0) {
mKernel.setState(RefreshState.PullDownToRefresh);
} else {
mKernel.setState(RefreshState.PullUpToLoad);
}
}
} else if (dy > 0 && mFooterLocked) {
consumedY = dy;
mTotalUnconsumed -= dy;
moveSpinnerInfinitely(mTotalUnconsumed);
}
// Now let our nested parent consume the leftovers
mNestedChild.dispatchNestedPreScroll(dx, dy - consumedY, consumed, null);
consumed[1] += consumedY;
}
@Override
public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
// Dispatch up to the nested parent first
mNestedChild.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, mParentOffsetInWindow);
// This is a bit of a hack. Nested scrolling works from the bottom up, and as we are
// sometimes between two nested scrolling views, we need a way to be able to know when any
// nested scrolling parent has stopped handling events. We do that by using the
// 'offset in window 'functionality to see if we have been moved from the event.
// This is a decent indication of whether we should take over the event stream or not.
final int dy = dyUnconsumed + mParentOffsetInWindow[1];
if (dy != 0 && (mEnableOverScrollDrag || (dy < 0 && isEnableRefreshOrLoadMore(mEnableRefresh)) || (dy > 0 && isEnableRefreshOrLoadMore(mEnableLoadMore)))) {
if (mViceState == RefreshState.None) {
mKernel.setState(dy > 0 ? RefreshState.PullUpToLoad : RefreshState.PullDownToRefresh);
}
moveSpinnerInfinitely(mTotalUnconsumed -= dy);
}
}
@Override
public boolean onNestedPreFling(@NonNull View target, float velocityX, float velocityY) {
return mFooterLocked && velocityY > 0 || startFlingIfNeed(-velocityY) || mNestedChild.dispatchNestedPreFling(velocityX, velocityY);
}
@Override
public boolean onNestedFling(@NonNull View target, float velocityX, float velocityY, boolean consumed) {
return mNestedChild.dispatchNestedFling(velocityX, velocityY, consumed);
}
@Override
public void onStopNestedScroll(@NonNull View target) {
mNestedParent.onStopNestedScroll(target);
mNestedInProgress = false;
// Finish the spinner for nested scrolling if we ever consumed any
// unconsumed nested scroll
mTotalUnconsumed = 0;
overSpinner();
// Dispatch up our nested parent
mNestedChild.stopNestedScroll();
}
//</editor-fold>
//<editor-fold desc="NestedScrollingChild">
@Override
public void setNestedScrollingEnabled(boolean enabled) {
mManualNestedScrolling = true;
mNestedChild.setNestedScrollingEnabled(enabled);
}
@Override
public boolean isNestedScrollingEnabled() {
return mNestedChild.isNestedScrollingEnabled();
}
// @Override
// public boolean canScrollVertically(int direction) {
// View target = mRefreshContent.getScrollableView();
// if (direction < 0) {
// return mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableRefresh) || ScrollBoundaryUtil.canScrollUp(target);
// } else if (direction > 0) {
// return mEnableOverScrollDrag || isEnableRefreshOrLoadMore(mEnableLoadMore) || ScrollBoundaryUtil.canScrollDown(target);
// return true;
// @Override
// @Deprecated
// public boolean startNestedScroll(int axes) {
// return mNestedChild.startNestedScroll(axes);
// @Override
// @Deprecated
// public void stopNestedScroll() {
// mNestedChild.stopNestedScroll();
// @Override
// @Deprecated
// public boolean hasNestedScrollingParent() {
// return mNestedChild.hasNestedScrollingParent();
// @Override
// @Deprecated
// public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
// int dyUnconsumed, int[] offsetInWindow) {
// return mNestedChild.dispatchNestedScroll(dxConsumed, dyConsumed,
// dxUnconsumed, dyUnconsumed, offsetInWindow);
// @Override
// @Deprecated
// public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
// return mNestedChild.dispatchNestedPreScroll(
// dx, dy, consumed, offsetInWindow);
// @Override
// @Deprecated
// public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
// return mNestedChild.dispatchNestedFling(velocityX, velocityY, consumed);
// @Override
// @Deprecated
// public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
// return mNestedChild.dispatchNestedPreFling(velocityX, velocityY);
//</editor-fold>
//</editor-fold>
//<editor-fold desc=" open interface">
@Override
public SmartRefreshLayout setFooterHeight(float heightDp) {
if (mFooterHeightStatus.canReplaceWith(DimensionStatus.CodeExact)) {
mFooterHeight = dp2px(heightDp);
mFooterHeightStatus = DimensionStatus.CodeExactUnNotify;
if (mRefreshFooter != null) {
mRefreshFooter.getView().requestLayout();
}
}
return this;
}
@Override
public SmartRefreshLayout setHeaderHeight(float heightDp) {
if (mHeaderHeightStatus.canReplaceWith(DimensionStatus.CodeExact)) {
mHeaderHeight = dp2px(heightDp);
mHeaderHeightStatus = DimensionStatus.CodeExactUnNotify;
if (mRefreshHeader != null) {
mRefreshHeader.getView().requestLayout();
}
}
return this;
}
@Override
public SmartRefreshLayout setHeaderInsetStart(float insetDp) {
mHeaderInsetStart = dp2px(insetDp);
return this;
}
@Override
public SmartRefreshLayout setFooterInsetStart(float insetDp) {
mFooterInsetStart = dp2px(insetDp);
return this;
}
/**
* @param rate /
* @return RefreshLayout
*/
@Override
public SmartRefreshLayout setDragRate(float rate) {
this.mDragRate = rate;
return this;
}
/**
* Header
* @param rate Header
*/
@Override
public SmartRefreshLayout setHeaderMaxDragRate(float rate) {
this.mHeaderMaxDragRate = rate;
if (mRefreshHeader != null && mHandler != null) {
mRefreshHeader.onInitialized(mKernel, mHeaderHeight, (int) (mHeaderMaxDragRate * mHeaderHeight));
} else {
mHeaderHeightStatus = mHeaderHeightStatus.unNotify();
}
return this;
}
/**
* Footer
* @param rate Footer
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setFooterMaxDragRate(float rate) {
this.mFooterMaxDragRate = rate;
if (mRefreshFooter != null && mHandler != null) {
mRefreshFooter.onInitialized(mKernel, mFooterHeight, (int)(mFooterHeight * mFooterMaxDragRate));
} else {
mFooterHeightStatus = mFooterHeightStatus.unNotify();
}
return this;
}
/**
* HeaderHeight
* @param rate HeaderHeight
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setHeaderTriggerRate(float rate) {
this.mHeaderTriggerRate = rate;
return this;
}
/**
* FooterHeight
* @param rate FooterHeight
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setFooterTriggerRate(float rate) {
this.mFooterTriggerRate = rate;
return this;
}
/**
*
* @param interpolator
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setReboundInterpolator(@NonNull Interpolator interpolator) {
this.mReboundInterpolator = interpolator;
return this;
}
/**
*
* @param duration
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setReboundDuration(int duration) {
this.mReboundDuration = duration;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableLoadMore(boolean enabled) {
this.mManualLoadMore = true;
this.mEnableLoadMore = enabled;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableRefresh(boolean enabled) {
this.mEnableRefresh = enabled;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableHeaderTranslationContent(boolean enabled) {
this.mEnableHeaderTranslationContent = enabled;
this.mManualHeaderTranslationContent = true;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableFooterTranslationContent(boolean enabled) {
this.mEnableFooterTranslationContent = enabled;
this.mManualFooterTranslationContent = true;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableAutoLoadMore(boolean enabled) {
this.mEnableAutoLoadMore = enabled;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableOverScrollBounce(boolean enabled) {
this.mEnableOverScrollBounce = enabled;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnablePureScrollMode(boolean enabled) {
this.mEnablePureScrollMode = enabled;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableScrollContentWhenLoaded(boolean enabled) {
this.mEnableScrollContentWhenLoaded = enabled;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableScrollContentWhenRefreshed(boolean enabled) {
this.mEnableScrollContentWhenRefreshed = enabled;
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableLoadMoreWhenContentNotFull(boolean enabled) {
this.mEnableLoadMoreWhenContentNotFull = enabled;
if (mRefreshContent != null) {
mRefreshContent.setEnableLoadMoreWhenContentNotFull(enabled);
}
return this;
}
/**
*
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableOverScrollDrag(boolean enabled) {
this.mEnableOverScrollDrag = enabled;
return this;
}
/**
* Footer
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableFooterFollowWhenLoadFinished(boolean enabled) {
this.mEnableFooterFollowWhenLoadFinished = enabled;
return this;
}
/**
* Header FixedBehind Header
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableClipHeaderWhenFixedBehind(boolean enabled) {
this.mEnableClipHeaderWhenFixedBehind = enabled;
return this;
}
/**
* Footer FixedBehind Footer
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setEnableClipFooterWhenFixedBehind(boolean enabled) {
this.mEnableClipFooterWhenFixedBehind = enabled;
return this;
}
/**
* +
* @param enabled
* @return SmartRefreshLayout
*/
@Override
public RefreshLayout setEnableNestedScroll(boolean enabled) {
setNestedScrollingEnabled(enabled);
return this;
}
/**
*
* @param disable
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setDisableContentWhenRefresh(boolean disable) {
this.mDisableContentWhenRefresh = disable;
return this;
}
/**
*
* @param disable
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setDisableContentWhenLoading(boolean disable) {
this.mDisableContentWhenLoading = disable;
return this;
}
/**
* Header
* @param header
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setRefreshHeader(@NonNull RefreshHeader header) {
return setRefreshHeader(header, MATCH_PARENT, WRAP_CONTENT);
}
/**
* Header
* @param header
* @param width MATCH_PARENT, WRAP_CONTENT
* @param height MATCH_PARENT, WRAP_CONTENT
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setRefreshHeader(@NonNull RefreshHeader header, int width, int height) {
if (mRefreshHeader != null) {
super.removeView(mRefreshHeader.getView());
}
this.mRefreshHeader = header;
this.mHeaderBackgroundColor = 0;
this.mHeaderNeedTouchEventWhenRefreshing = false;
this.mHeaderHeightStatus = mHeaderHeightStatus.unNotify();
if (header.getSpinnerStyle() == SpinnerStyle.FixedBehind) {
super.addView(mRefreshHeader.getView(), 0, new LayoutParams(width, height));
} else {
super.addView(mRefreshHeader.getView(), width, height);
}
return this;
}
/**
* Footer
* @param footer
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setRefreshFooter(@NonNull RefreshFooter footer) {
return setRefreshFooter(footer, MATCH_PARENT, WRAP_CONTENT);
}
/**
* Footer
* @param footer
* @param width MATCH_PARENT, WRAP_CONTENT
* @param height MATCH_PARENT, WRAP_CONTENT
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setRefreshFooter(@NonNull RefreshFooter footer, int width, int height) {
if (mRefreshFooter != null) {
super.removeView(mRefreshFooter.getView());
}
this.mRefreshFooter = footer;
this.mFooterBackgroundColor = 0;
this.mFooterNeedTouchEventWhenLoading = false;
this.mFooterHeightStatus = mFooterHeightStatus.unNotify();
this.mEnableLoadMore = !mManualLoadMore || mEnableLoadMore;
if (mRefreshFooter.getSpinnerStyle() == SpinnerStyle.FixedBehind) {
super.addView(mRefreshFooter.getView(), 0, new LayoutParams(width, height));
} else {
super.addView(mRefreshFooter.getView(), width, height);
}
return this;
}
/**
* Content
* @param content
* @return SmartRefreshLayout
*/
@Override
public RefreshLayout setRefreshContent(@NonNull View content) {
return setRefreshContent(content, MATCH_PARENT, MATCH_PARENT);
}
/**
* Content
* @param content
* @param width MATCH_PARENT, WRAP_CONTENT
* @param height MATCH_PARENT, WRAP_CONTENT
* @return SmartRefreshLayout
*/
@Override
public RefreshLayout setRefreshContent(@NonNull View content, int width, int height) {
final View thisView = this;
if (mRefreshContent != null) {
super.removeView(mRefreshContent.getView());
}
super.addView(content, 0, new LayoutParams(width, height));
if (mRefreshHeader != null && mRefreshHeader.getSpinnerStyle() == SpinnerStyle.FixedBehind) {
super.bringChildToFront(content);
if (mRefreshFooter != null && mRefreshFooter.getSpinnerStyle() != SpinnerStyle.FixedBehind) {
super.bringChildToFront(mRefreshFooter.getView());
}
} else if (mRefreshFooter != null && mRefreshFooter.getSpinnerStyle() == SpinnerStyle.FixedBehind) {
super.bringChildToFront(content);
if (mRefreshHeader != null && mRefreshHeader.getSpinnerStyle() == SpinnerStyle.FixedBehind) {
super.bringChildToFront(mRefreshHeader.getView());
}
}
mRefreshContent = new RefreshContentWrapper(content);
if (mHandler != null) {
View fixedHeaderView = mFixedHeaderViewId > 0 ? thisView.findViewById(mFixedHeaderViewId) : null;
View fixedFooterView = mFixedFooterViewId > 0 ? thisView.findViewById(mFixedFooterViewId) : null;
mRefreshContent.setScrollBoundaryDecider(mScrollBoundaryDecider);
mRefreshContent.setEnableLoadMoreWhenContentNotFull(mEnableLoadMoreWhenContentNotFull);
mRefreshContent.setUpComponent(mKernel, fixedHeaderView, fixedFooterView);
}
return this;
}
/**
*
* @return RefreshFooter
*/
@Nullable
@Override
public RefreshFooter getRefreshFooter() {
return mRefreshFooter instanceof RefreshFooter ? (RefreshFooter) mRefreshFooter : null;
}
/**
*
* @return RefreshHeader
*/
@Nullable
@Override
public RefreshHeader getRefreshHeader() {
return mRefreshHeader instanceof RefreshHeader ? (RefreshHeader) mRefreshHeader : null;
}
/**
*
* @return RefreshState
*/
@Override
public RefreshState getState() {
return mState;
}
/**
*
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout getLayout() {
return this;
}
/**
*
* @param listener
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setOnRefreshListener(OnRefreshListener listener) {
this.mRefreshListener = listener;
return this;
}
/**
*
* @param listener
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setOnLoadMoreListener(OnLoadMoreListener listener) {
this.mLoadMoreListener = listener;
this.mEnableLoadMore = mEnableLoadMore || (!mManualLoadMore && listener != null);
return this;
}
/**
*
* @param listener
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setOnRefreshLoadMoreListener(OnRefreshLoadMoreListener listener) {
this.mRefreshListener = listener;
this.mLoadMoreListener = listener;
this.mEnableLoadMore = mEnableLoadMore || (!mManualLoadMore && listener != null);
return this;
}
/**
*
* @param listener {@link com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener}
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setOnMultiPurposeListener(OnMultiPurposeListener listener) {
this.mOnMultiPurposeListener = listener;
return this;
}
/**
*
* @param primaryColors
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setPrimaryColors(@ColorInt int... primaryColors) {
if (mRefreshHeader != null) {
mRefreshHeader.setPrimaryColors(primaryColors);
}
if (mRefreshFooter != null) {
mRefreshFooter.setPrimaryColors(primaryColors);
}
mPrimaryColors = primaryColors;
return this;
}
/**
*
* @param primaryColorId ID
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setPrimaryColorsId(@ColorRes int... primaryColorId) {
final View thisView = this;
final int[] colors = new int[primaryColorId.length];
for (int i = 0; i < primaryColorId.length; i++) {
colors[i] = getColor(thisView.getContext(), primaryColorId[i]);
}
setPrimaryColors(colors);
return this;
}
/**
*
* @param boundary {@link com.scwang.smartrefresh.layout.impl.ScrollBoundaryDeciderAdapter}
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setScrollBoundaryDecider(ScrollBoundaryDecider boundary) {
mScrollBoundaryDecider = boundary;
if (mRefreshContent != null) {
mRefreshContent.setScrollBoundaryDecider(boundary);
}
return this;
}
/**
*
* @param noMoreData
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout setNoMoreData(boolean noMoreData) {
mFooterNoMoreData = noMoreData;
if (mRefreshFooter instanceof RefreshFooter && !((RefreshFooter)mRefreshFooter).setNoMoreData(noMoreData)) {
System.out.println("Footer:" + mRefreshFooter + " NoMoreData is not supported.(NoMoreData)");
}
return this;
}
/**
*
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishRefresh() {
long passTime = System.currentTimeMillis() - mLastOpenTime;
return finishRefresh(Math.min(Math.max(0, 300 - (int) passTime), 300));//300
}
/**
*
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishLoadMore() {
long passTime = System.currentTimeMillis() - mLastOpenTime;
return finishLoadMore(Math.min(Math.max(0, 300 - (int) passTime), 300));//300
}
/**
*
* @param delayed
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishRefresh(int delayed) {
return finishRefresh(delayed, true);
}
/**
*
* @param success
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishRefresh(boolean success) {
long passTime = System.currentTimeMillis() - mLastOpenTime;
return finishRefresh(success ? Math.min(Math.max(0, 300 - (int) passTime), 300) : 0, success);//300
}
/**
*
* @param delayed
* @param success
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishRefresh(int delayed, final boolean success) {
postDelayed(new Runnable() {
@Override
public void run() {
if (mState == RefreshState.Refreshing && mRefreshHeader != null && mRefreshContent != null) {
if (success) {
setNoMoreData(false);
}
notifyStateChanged(RefreshState.RefreshFinish);
int startDelay = mRefreshHeader.onFinish(SmartRefreshLayout.this, success);
if (mOnMultiPurposeListener != null && mRefreshHeader instanceof RefreshHeader) {
mOnMultiPurposeListener.onHeaderFinish((RefreshHeader) mRefreshHeader, success);
}
if (startDelay < Integer.MAX_VALUE) {
if (mIsBeingDragged || mNestedInProgress) {
if (mIsBeingDragged) {
mTouchY = mLastTouchY;
mTouchSpinner = 0;
mIsBeingDragged = false;
}
long time = System.currentTimeMillis();
SmartRefreshLayout.super.dispatchTouchEvent(obtain(time, time, MotionEvent.ACTION_DOWN, mLastTouchX, mLastTouchY + mSpinner - mTouchSlop*2, 0));
SmartRefreshLayout.super.dispatchTouchEvent(obtain(time, time, MotionEvent.ACTION_MOVE, mLastTouchX, mLastTouchY + mSpinner, 0));
if (mNestedInProgress) {
mTotalUnconsumed = 0;
}
}
if (mSpinner > 0) {
AnimatorUpdateListener updateListener = null;
ValueAnimator valueAnimator = animSpinner(0, startDelay, mReboundInterpolator, mReboundDuration);
if (mEnableScrollContentWhenRefreshed) {
updateListener = mRefreshContent.scrollContentWhenFinished(mSpinner);
}
if (valueAnimator != null && updateListener != null) {
valueAnimator.addUpdateListener(updateListener);
}
} else if (mSpinner < 0) {
animSpinner(0, startDelay, mReboundInterpolator, mReboundDuration);
} else {
mKernel.moveSpinner(0, false);
resetStatus();
}
}
}
}
}, delayed <= 0 ? 1 : delayed);
return this;
}
/**
*
* @param delayed
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishLoadMore(int delayed) {
return finishLoadMore(delayed, true, false);
}
/**
*
* @param success
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishLoadMore(boolean success) {
long passTime = System.currentTimeMillis() - mLastOpenTime;
return finishLoadMore(success ? Math.min(Math.max(0, 300 - (int) passTime), 300) : 0, success, false);
}
/**
*
* @param delayed
* @param success
* @param noMoreData
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishLoadMore(int delayed, final boolean success, final boolean noMoreData) {
postDelayed(new Runnable() {
@Override
public void run() {
if (mState == RefreshState.Loading && mRefreshFooter != null && mRefreshContent != null) {
notifyStateChanged(RefreshState.LoadFinish);
final int startDelay = mRefreshFooter.onFinish(SmartRefreshLayout.this, success);
if (mOnMultiPurposeListener != null && mRefreshFooter instanceof RefreshFooter) {
mOnMultiPurposeListener.onFooterFinish((RefreshFooter) mRefreshFooter, success);
}
if (startDelay < Integer.MAX_VALUE) {
final boolean needHoldFooter = noMoreData && mEnableFooterFollowWhenLoadFinished && mSpinner < 0 && mRefreshContent.canLoadMore();
final int offset = mSpinner - (needHoldFooter ? Math.max(mSpinner,-mFooterHeight) : 0);
if (mIsBeingDragged || mNestedInProgress) {
if (mIsBeingDragged) {
mTouchY = mLastTouchY;
mIsBeingDragged = false;
mTouchSpinner = mSpinner - offset;
}
final long time = System.currentTimeMillis();
SmartRefreshLayout.super.dispatchTouchEvent(obtain(time, time, MotionEvent.ACTION_DOWN, mLastTouchX, mLastTouchY + offset + mTouchSlop * 2, 0));
SmartRefreshLayout.super.dispatchTouchEvent(obtain(time, time, MotionEvent.ACTION_MOVE, mLastTouchX, mLastTouchY + offset, 0));
if (mNestedInProgress) {
mTotalUnconsumed = 0;
}
}
postDelayed(new Runnable() {
@Override
public void run() {
AnimatorUpdateListener updateListener = null;
if (mEnableScrollContentWhenLoaded && offset < 0) {
updateListener = mRefreshContent.scrollContentWhenFinished(mSpinner);
}
if (updateListener != null) {
updateListener.onAnimationUpdate(ValueAnimator.ofInt(0, 0));
}
ValueAnimator animator = null;
AnimatorListenerAdapter listenerAdapter = new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationEnd(animation);
}
@Override
public void onAnimationEnd(Animator animation) {
mFooterLocked = false;
if (noMoreData) {
setNoMoreData(true);
}
if (mState == RefreshState.LoadFinish) {
notifyStateChanged(RefreshState.None);
}
}
};
if (mSpinner > 0) {
animator = mKernel.animSpinner(0);
} else if (updateListener != null || mSpinner == 0) {
if (reboundAnimator != null) {
reboundAnimator.cancel();
reboundAnimator = null;
}
mKernel.moveSpinner(0, false);
resetStatus();
} else {
if (noMoreData && mEnableFooterFollowWhenLoadFinished) {
if (mSpinner >= -mFooterHeight) {
notifyStateChanged(RefreshState.None);
} else {
animator = mKernel.animSpinner(-mFooterHeight);
}
} else {
animator = mKernel.animSpinner(0);
}
}
if (animator != null) {
animator.addListener(listenerAdapter);
} else {
listenerAdapter.onAnimationEnd(null);
}
}
}, mSpinner < 0 ? startDelay : 0);
}
} else {
if (noMoreData) {
setNoMoreData(true);
}
}
}
}, delayed <= 0 ? 1 : delayed);
return this;
}
/**
*
* @return SmartRefreshLayout
*/
@Override
public SmartRefreshLayout finishLoadMoreWithNoMoreData() {
long passTime = System.currentTimeMillis() - mLastOpenTime;
return finishLoadMore(Math.min(Math.max(0, 300 - (int) passTime), 300), true, true);
}
/**
*
* @return
*/
@Override
public boolean autoRefresh() {
return autoRefresh(mHandler == null ? 400 : 0, mReboundDuration, 1f * ((mHeaderMaxDragRate/2 + 0.5f) * mHeaderHeight) / (mHeaderHeight == 0 ? 1 : mHeaderHeight));
}
/**
*
* @param delayed
* @return
*/
@Override
public boolean autoRefresh(int delayed) {
return autoRefresh(delayed, mReboundDuration, 1f * ((mHeaderMaxDragRate/2 + 0.5f) * mHeaderHeight) / (mHeaderHeight == 0 ? 1 : mHeaderHeight));
}
@Override
public boolean autoRefresh(int delayed, final int duration, final float dragRate) {
if (mState == RefreshState.None && isEnableRefreshOrLoadMore(mEnableRefresh)) {
if (reboundAnimator != null) {
reboundAnimator.cancel();
}
Runnable runnable = new Runnable() {
@Override
public void run() {
reboundAnimator = ValueAnimator.ofInt(mSpinner, (int) (mHeaderHeight * dragRate));
reboundAnimator.setDuration(duration);
reboundAnimator.setInterpolator(new DecelerateInterpolator());
reboundAnimator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mKernel.moveSpinner((int) animation.getAnimatedValue(), true);
}
});
reboundAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
final View thisView = SmartRefreshLayout.this;
mLastTouchX = thisView.getMeasuredWidth() / 2;
mKernel.setState(RefreshState.PullDownToRefresh);
}
@Override
public void onAnimationEnd(Animator animation) {
reboundAnimator = null;
if (mState != RefreshState.ReleaseToRefresh) {
mKernel.setState(RefreshState.ReleaseToRefresh);
}
overSpinner();
}
});
reboundAnimator.start();
}
};
if (delayed > 0) {
reboundAnimator = new ValueAnimator();
postDelayed(runnable, delayed);
} else {
runnable.run();
}
return true;
} else {
return false;
}
}
// /**
// *
// * @return
// */
// @Override
// public boolean autoLoadMore() {
// return autoLoadMore(0, mReboundDuration, 1f * (mFooterHeight * (mFooterMaxDragRate / 2 + 0.5f)) / (mFooterHeight == 0 ? 1 : mFooterHeight));
// /**
// *
// * @param delayed
// * @return
// */
// @Override
// public boolean autoLoadMore(int delayed) {
// return autoLoadMore(delayed, mReboundDuration, 1f * (mFooterHeight * (mFooterMaxDragRate / 2 + 0.5f)) / (mFooterHeight == 0 ? 1 : mFooterHeight));
// @Override
// public boolean autoLoadMore(int delayed, final int duration, final float dragRate) {
// if (mState == RefreshState.None && (isEnableRefreshOrLoadMore(mEnableLoadMore) && !mFooterNoMoreData)) {
// if (reboundAnimator != null) {
// reboundAnimator.cancel();
// Runnable runnable = new Runnable() {
// @Override
// public void run() {
// reboundAnimator = ValueAnimator.ofInt(mSpinner, -(int) (mFooterHeight * dragRate));
// reboundAnimator.setDuration(duration);
// reboundAnimator.setInterpolator(new DecelerateInterpolator());
// reboundAnimator.addUpdateListener(new AnimatorUpdateListener() {
// @Override
// public void onAnimationUpdate(ValueAnimator animation) {
// mKernel.moveSpinner((int) animation.getAnimatedValue(), true);
// reboundAnimator.addListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationStart(Animator animation) {
// final View thisView = SmartRefreshLayout.this;
// mLastTouchX = thisView.getMeasuredWidth() / 2;
// mKernel.setState(RefreshState.PullUpToLoad);
// @Override
// public void onAnimationEnd(Animator animation) {
// reboundAnimator = null;
// if (mState != RefreshState.ReleaseToLoad) {
// mKernel.setState(RefreshState.ReleaseToLoad);
// if (mEnableAutoLoadMore) {
// mEnableAutoLoadMore = false;
// overSpinner();
// mEnableAutoLoadMore = true;
// } else {
// overSpinner();
// reboundAnimator.start();
// if (delayed > 0) {
// reboundAnimator = new ValueAnimator();
// postDelayed(runnable, delayed);
// } else {
// runnable.run();
// return true;
// } else {
// return false;
/**
* Header
* @param creator Header
*/
public static void setDefaultRefreshHeaderCreator(@NonNull DefaultRefreshHeaderCreator creator) {
sHeaderCreator = creator;
}
/**
* Footer
* @param creator Footer
*/
public static void setDefaultRefreshFooterCreator(@NonNull DefaultRefreshFooterCreator creator) {
sFooterCreator = creator;
// sManualFooterCreator = true;
}
/**
* Refresh
* @param initializer
*/
public static void setDefaultRefreshInitializer(@NonNull DefaultRefreshInitializer initializer) {
sRefreshInitializer = initializer;
}
//<editor-fold desc="API">
// /**
// *
// * @return
// */
// @Override
// public boolean isRefreshing() {
// return mState == RefreshState.Refreshing;
// /**
// *
// * @return
// */
// @Override
// public boolean isLoading() {
// return mState == RefreshState.Loading;
// /**
// *
// * @deprecated {@link RefreshLayout#setNoMoreData(boolean)}
// * @return SmartRefreshLayout
// */
// @Override
// @Deprecated
// public SmartRefreshLayout resetNoMoreData() {
// return setNoMoreData(false);
//</editor-fold>
//</editor-fold>
//<editor-fold desc=" RefreshKernel">
public class RefreshKernelImpl implements RefreshKernel {
@NonNull
@Override
public RefreshLayout getRefreshLayout() {
return SmartRefreshLayout.this;
}
@NonNull
@Override
public RefreshContent getRefreshContent() {
return mRefreshContent;
}
@Override
public RefreshKernel setState(@NonNull RefreshState state) {
switch (state) {
case None:
resetStatus();
break;
case PullDownToRefresh:
if (!mState.isOpening && isEnableRefreshOrLoadMore(mEnableRefresh)) {
notifyStateChanged(RefreshState.PullDownToRefresh);
} else {
setViceState(RefreshState.PullDownToRefresh);
}
break;
case PullUpToLoad:
if (isEnableRefreshOrLoadMore(mEnableLoadMore) && !mState.isOpening && !mState.isFinishing && !(mFooterNoMoreData && mEnableFooterFollowWhenLoadFinished)) {
notifyStateChanged(RefreshState.PullUpToLoad);
} else {
setViceState(RefreshState.PullUpToLoad);
}
break;
case PullDownCanceled:
if (!mState.isOpening && isEnableRefreshOrLoadMore(mEnableRefresh)) {
notifyStateChanged(RefreshState.PullDownCanceled);
resetStatus();
} else {
setViceState(RefreshState.PullDownCanceled);
}
break;
case PullUpCanceled:
if (isEnableRefreshOrLoadMore(mEnableLoadMore) && !mState.isOpening && !(mFooterNoMoreData && mEnableFooterFollowWhenLoadFinished)) {
notifyStateChanged(RefreshState.PullUpCanceled);
resetStatus();
} else {
setViceState(RefreshState.PullUpCanceled);
}
break;
case ReleaseToRefresh:
if (!mState.isOpening && isEnableRefreshOrLoadMore(mEnableRefresh)) {
notifyStateChanged(RefreshState.ReleaseToRefresh);
} else {
setViceState(RefreshState.ReleaseToRefresh);
}
break;
case ReleaseToLoad:
if (isEnableRefreshOrLoadMore(mEnableLoadMore) && !mState.isOpening && !mState.isFinishing && !(mFooterNoMoreData && mEnableFooterFollowWhenLoadFinished)) {
notifyStateChanged(RefreshState.ReleaseToLoad);
} else {
setViceState(RefreshState.ReleaseToLoad);
}
break;
case ReleaseToTwoLevel: {
if (!mState.isOpening && isEnableRefreshOrLoadMore(mEnableRefresh)) {
notifyStateChanged(RefreshState.ReleaseToTwoLevel);
} else {
setViceState(RefreshState.ReleaseToTwoLevel);
}
break;
}
case RefreshReleased: {
if (!mState.isOpening && isEnableRefreshOrLoadMore(mEnableRefresh)) {
notifyStateChanged(RefreshState.RefreshReleased);
} else {
setViceState(RefreshState.RefreshReleased);
}
break;
}
case LoadReleased: {
if (!mState.isOpening && isEnableRefreshOrLoadMore(mEnableLoadMore)) {
notifyStateChanged(RefreshState.LoadReleased);
} else {
setViceState(RefreshState.LoadReleased);
}
break;
}
case Refreshing:
setStateRefreshing();
break;
case Loading:
setStateLoading();
break;
case RefreshFinish: {
if (mState == RefreshState.Refreshing) {
notifyStateChanged(RefreshState.RefreshFinish);
}
break;
}
case LoadFinish:{
if (mState == RefreshState.Loading) {
notifyStateChanged(RefreshState.LoadFinish);
}
break;
}
case TwoLevelReleased:
notifyStateChanged(RefreshState.TwoLevelReleased);
break;
case TwoLevelFinish:
notifyStateChanged(RefreshState.TwoLevelFinish);
break;
case TwoLevel:
notifyStateChanged(RefreshState.TwoLevel);
break;
}
return null;
}
@Override
public RefreshKernel startTwoLevel(boolean open) {
if (open) {
AnimatorListenerAdapter listener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mKernel.setState(RefreshState.TwoLevel);
}
};
final View thisView = SmartRefreshLayout.this;
ValueAnimator animator = animSpinner(thisView.getMeasuredHeight());
if (animator != null && animator == reboundAnimator) {
animator.setDuration(mFloorDuration);
animator.addListener(listener);
} else {
listener.onAnimationEnd(null);
}
} else {
if (animSpinner(0) == null) {
notifyStateChanged(RefreshState.None);
}
}
return this;
}
@Override
public RefreshKernel finishTwoLevel() {
if (mState == RefreshState.TwoLevel) {
mKernel.setState(RefreshState.TwoLevelFinish);
if (mSpinner == 0) {
moveSpinner(0, false);
notifyStateChanged(RefreshState.None);
} else {
animSpinner(0).setDuration(mFloorDuration);
}
}
return this;
}
//<editor-fold desc=" state changes">
//</editor-fold>
//<editor-fold desc=" Spinner">
/*
* Scroll
* moveSpinner {@link android.support.v4.widget.SwipeRefreshLayout#moveSpinner(float)}
*/
public RefreshKernel moveSpinner(int spinner, boolean isDragging) {
if (mSpinner == spinner
&& (mRefreshHeader == null || !mRefreshHeader.isSupportHorizontalDrag())
&& (mRefreshFooter == null || !mRefreshFooter.isSupportHorizontalDrag())) {
return this;
}
final View thisView = SmartRefreshLayout.this;
final int oldSpinner = mSpinner;
mSpinner = spinner;
if (isDragging && mViceState.isDragging) {
if (mSpinner > mHeaderHeight * mHeaderTriggerRate) {
if (mState != RefreshState.ReleaseToTwoLevel) {
mKernel.setState(RefreshState.ReleaseToRefresh);
}
} else if (-mSpinner > mFooterHeight * mFooterTriggerRate && !mFooterNoMoreData) {
mKernel.setState(RefreshState.ReleaseToLoad);
} else if (mSpinner < 0 && !mFooterNoMoreData) {
mKernel.setState(RefreshState.PullUpToLoad);
} else if (mSpinner > 0) {
mKernel.setState(RefreshState.PullDownToRefresh);
}
}
if (mRefreshContent != null) {
Integer tSpinner = null;
if (spinner >= 0 && mRefreshHeader != null) {
if (isEnableTranslationContent(mEnableHeaderTranslationContent, mRefreshHeader)) {
tSpinner = spinner;
} else if (oldSpinner < 0) {
tSpinner = 0;
}
}
if (spinner <= 0 && mRefreshFooter != null) {
if (isEnableTranslationContent(mEnableFooterTranslationContent, mRefreshFooter)) {
tSpinner = spinner;
} else if (oldSpinner > 0) {
tSpinner = 0;
}
}
if (tSpinner != null) {
mRefreshContent.moveSpinner(tSpinner, mHeaderTranslationViewId, mFooterTranslationViewId);
boolean header = mEnableClipHeaderWhenFixedBehind && mRefreshHeader != null && mRefreshHeader.getSpinnerStyle() == SpinnerStyle.FixedBehind;
header = header || mHeaderBackgroundColor != 0;
boolean footer = mEnableClipFooterWhenFixedBehind && mRefreshFooter != null && mRefreshFooter.getSpinnerStyle() == SpinnerStyle.FixedBehind;
footer = footer || mFooterBackgroundColor != 0;
if ((header && (tSpinner >= 0 || oldSpinner > 0)) || (footer && (tSpinner <= 0 || oldSpinner < 0))) {
thisView.invalidate();
}
}
}
if ((spinner >= 0 || oldSpinner > 0) && mRefreshHeader != null) {
final int offset = Math.max(spinner, 0);
final int headerHeight = mHeaderHeight;
final int maxDragHeight = (int) (mHeaderHeight * mHeaderMaxDragRate);
final float percent = 1f * offset / (mHeaderHeight == 0 ? 1 : mHeaderHeight);
if (isEnableRefreshOrLoadMore(mEnableRefresh) || (mState == RefreshState.RefreshFinish && !isDragging)) {
if (oldSpinner != mSpinner) {
if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.Translate) {
mRefreshHeader.getView().setTranslationY(mSpinner);
if (mHeaderBackgroundColor != 0 && mPaint != null && !isEnableTranslationContent(mEnableHeaderTranslationContent,mRefreshHeader)) {
thisView.invalidate();
}
} else if (mRefreshHeader.getSpinnerStyle() == SpinnerStyle.Scale){
mRefreshHeader.getView().requestLayout();
}
mRefreshHeader.onMoving(isDragging, percent, offset, headerHeight, maxDragHeight);
}
if (isDragging && mRefreshHeader.isSupportHorizontalDrag()) {
final int offsetX = (int) mLastTouchX;
final int offsetMax = thisView.getWidth();
final float percentX = mLastTouchX / (offsetMax == 0 ? 1 : offsetMax);
mRefreshHeader.onHorizontalDrag(percentX, offsetX, offsetMax);
}
}
if (oldSpinner != mSpinner && mOnMultiPurposeListener != null && mRefreshHeader instanceof RefreshHeader) {
mOnMultiPurposeListener.onHeaderMoving((RefreshHeader) mRefreshHeader, isDragging, percent, offset, headerHeight, maxDragHeight);
}
}
if ((spinner <= 0 || oldSpinner < 0) && mRefreshFooter != null) {
final int offset = -Math.min(spinner, 0);
final int footerHeight = mFooterHeight;
final int maxDragHeight = (int) (mFooterHeight * mFooterMaxDragRate);
final float percent = offset * 1f / (mFooterHeight == 0 ? 1 : mFooterHeight);
if (isEnableRefreshOrLoadMore(mEnableLoadMore) || (mState == RefreshState.LoadFinish && !isDragging)) {
if (oldSpinner != mSpinner) {
if (mRefreshFooter.getSpinnerStyle() == SpinnerStyle.Translate) {
mRefreshFooter.getView().setTranslationY(mSpinner);
if (mFooterBackgroundColor != 0 && mPaint != null && !isEnableTranslationContent(mEnableFooterTranslationContent, mRefreshFooter)) {
thisView.invalidate();
}
} else if (mRefreshFooter.getSpinnerStyle() == SpinnerStyle.Scale){
mRefreshFooter.getView().requestLayout();
}
mRefreshFooter.onMoving(isDragging, percent, offset, footerHeight, maxDragHeight);
}
if (isDragging && mRefreshFooter.isSupportHorizontalDrag()) {
final int offsetX = (int) mLastTouchX;
final int offsetMax = thisView.getWidth();
final float percentX = mLastTouchX / (offsetMax == 0 ? 1 : offsetMax);
mRefreshFooter.onHorizontalDrag(percentX, offsetX, offsetMax);
}
}
if (oldSpinner != mSpinner && mOnMultiPurposeListener != null && mRefreshFooter instanceof RefreshFooter) {
mOnMultiPurposeListener.onFooterMoving((RefreshFooter)mRefreshFooter, isDragging, percent, offset, footerHeight, maxDragHeight);
}
}
return this;
}
public ValueAnimator animSpinner(int endSpinner) {
return SmartRefreshLayout.this.animSpinner(endSpinner, 0, mReboundInterpolator, mReboundDuration);
}
//</editor-fold>
//<editor-fold desc="">
@Override
public RefreshKernel requestDrawBackgroundFor(@NonNull RefreshInternal internal, int backgroundColor) {
if (mPaint == null && backgroundColor != 0) {
mPaint = new Paint();
}
if (internal.equals(mRefreshHeader)) {
mHeaderBackgroundColor = backgroundColor;
} else if (internal.equals(mRefreshFooter)) {
mFooterBackgroundColor = backgroundColor;
}
return this;
}
@Override
public RefreshKernel requestNeedTouchEventFor(@NonNull RefreshInternal internal, boolean request) {
if (internal.equals(mRefreshHeader)) {
mHeaderNeedTouchEventWhenRefreshing = request;
} else if (internal.equals(mRefreshFooter)) {
mFooterNeedTouchEventWhenLoading = request;
}
return this;
}
@Override
public RefreshKernel requestDefaultTranslationContentFor(@NonNull RefreshInternal internal, boolean translation) {
if (internal.equals(mRefreshHeader)) {
if (!mManualHeaderTranslationContent) {
mManualHeaderTranslationContent = true;
mEnableHeaderTranslationContent = translation;
}
} else if (internal.equals(mRefreshFooter)) {
if (!mManualFooterTranslationContent) {
mManualFooterTranslationContent = true;
mEnableFooterTranslationContent = translation;
}
}
return this;
}
@Override
public RefreshKernel requestRemeasureHeightFor(@NonNull RefreshInternal internal) {
if (internal.equals(mRefreshHeader)) {
if (mHeaderHeightStatus.notified) {
mHeaderHeightStatus = mHeaderHeightStatus.unNotify();
}
} else if (internal.equals(mRefreshFooter)) {
if (mFooterHeightStatus.notified) {
mFooterHeightStatus = mFooterHeightStatus.unNotify();
}
}
return this;
}
@Override
public RefreshKernel requestFloorDuration(int duration) {
mFloorDuration = duration;
return this;
}
//</editor-fold>
}
//</editor-fold>
//<editor-fold desc=" postDelayed">
@Override
public boolean post(@NonNull Runnable action) {
if (mHandler == null) {
mListDelayedRunnable = mListDelayedRunnable == null ? new ArrayList<DelayedRunnable>() : mListDelayedRunnable;
mListDelayedRunnable.add(new DelayedRunnable(action,0));
return false;
}
return mHandler.post(new DelayedRunnable(action,0));
}
@Override
public boolean postDelayed(@NonNull Runnable action, long delayMillis) {
if (delayMillis == 0) {
new DelayedRunnable(action,0).run();
return true;
}
if (mHandler == null) {
mListDelayedRunnable = mListDelayedRunnable == null ? new ArrayList<DelayedRunnable>() : mListDelayedRunnable;
mListDelayedRunnable.add(new DelayedRunnable(action, delayMillis));
return false;
}
return mHandler.postDelayed(new DelayedRunnable(action, 0), delayMillis);
}
//</editor-fold>
} |
package uk.gov.dvla.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.annotations.Property;
@Entity(value = "drivers", noClassnameStored = true)
public class Driver extends Person {
private List<DriverNumber> dlnHistory;
private List<DriverFlag> flag;
private List<Licence> licence;
private List<Integer> stopMarker;
private List<Integer> restrictionKey;
private List<String> caseType;
private List<String> errorCode;
private Boolean endorsementAmountExcess;
private Boolean carHireEnqPmt = null;
private String statusCode = null;
private Date photoExpiryDate;
private List<String> disqualificationStatusCodes;
private boolean nslInCorruptedRange;
@Property("dln")
@Indexed(unique = true)
private String currentDriverNumber = null;
public void addLicence(Licence lic) {
if (null == licence) {
licence = new ArrayList<Licence>();
}
licence.add(lic);
}
public void addStopMarker(Integer marker) {
if (null == stopMarker) {
stopMarker = new ArrayList<Integer>();
}
stopMarker.add(marker);
}
public void addRestrictionKey(Integer key) {
if (null == restrictionKey) {
restrictionKey = new ArrayList<Integer>();
}
restrictionKey.add(key);
}
public void addCaseType(String key) {
if (null == caseType) {
caseType = new ArrayList<String>();
}
caseType.add(key);
}
public void addErrorCode(String code) {
if (null == errorCode) {
errorCode = new ArrayList<String>();
}
errorCode.add(code);
}
public void setLicence(List<Licence> lics) {
licence = lics;
}
public List<Licence> getLicence() {
return this.licence;
}
public List<Integer> getStopMarker() {
return stopMarker;
}
public void setStopMarker(List<Integer> markers) {
this.stopMarker = markers;
}
public List<Integer> getRestrictionKey() {
return restrictionKey;
}
public void setRestrictionKey(List<Integer> keys) {
this.restrictionKey = keys;
}
public List<String> getCaseType() {
return this.caseType;
}
public void setCaseType(List<String> caseTypes) {
this.caseType = caseTypes;
}
public List<String> getErrorCode() {
return this.errorCode;
}
public void setErrorCode(List<String> errorCodes) {
this.errorCode = errorCodes;
}
public void setCurrentDriverNumber(String dln) {
this.currentDriverNumber = dln;
}
public String getCurrentDriverNumber() {
return this.currentDriverNumber;
}
public List<DriverNumber> getDriverNumberHistory() {
return dlnHistory;
}
public void setDriverNumberHistory(List<DriverNumber> driverNumber) {
this.dlnHistory = driverNumber;
}
public List<DriverFlag> getFlag() {
return flag;
}
public void setFlag(List<DriverFlag> flag) {
this.flag = flag;
}
public Boolean getCarHireEnqPmt() {
return carHireEnqPmt;
}
public void setCarHireEnqPmt(Boolean carHireEnqPmt) {
this.carHireEnqPmt = carHireEnqPmt;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public Date getPhotoExpiryDate() {
return photoExpiryDate;
}
public void setPhotoExpiryDate(Date photoExpiryDate) {
this.photoExpiryDate = photoExpiryDate;
}
public List<String> getDisqualificationStatusCodes() {
return disqualificationStatusCodes;
}
public void setDisqualificationStatusCodes(List<String> disqualificationStatusCodes) {
this.disqualificationStatusCodes = disqualificationStatusCodes;
}
public Boolean getNslInCorruptedRange() {
return nslInCorruptedRange;
}
public void setNslInCorruptedRange(Boolean nslInCorruptedRange) {
this.nslInCorruptedRange = nslInCorruptedRange;
}
public Boolean getEndorsementAmountExcess() {
return endorsementAmountExcess;
}
public void setEndorsementAmountExcess(Boolean endorsmentAmountExcess) {
this.endorsementAmountExcess = endorsmentAmountExcess;
}
} |
package org.wiztools.restclient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.wiztools.commons.Implementation;
import org.wiztools.commons.MultiValueMap;
import org.wiztools.commons.StreamUtil;
import org.wiztools.commons.StringUtil;
/**
*
* @author subwiz
*/
public class HTTPClientRequestExecuter implements RequestExecuter {
private static final Logger LOG = Logger.getLogger(HTTPClientRequestExecuter.class.getName());
private DefaultHttpClient httpclient;
private boolean interruptedShutdown = false;
private boolean isRequestCompleted = false;
/*
* This instance variable is for avoiding multiple execution of requests
* on the same RequestExecuter object. We know it is not the perfect solution
* (as it does not synchronize access to shared variable), but is
* fine for finding this type of error during development phase.
*/
private boolean isRequestStarted = false;
@Override
public void execute(Request request, View... views) {
// Verify if this is the first call to this object:
if(isRequestStarted){
throw new MultipleRequestInSameRequestExecuterException(
"A RequestExecuter object can be used only once!");
}
isRequestStarted = true;
// Proceed with execution:
for(View view: views){
view.doStart(request);
}
final URL url = request.getUrl();
final String urlHost = url.getHost();
final int urlPort = url.getPort()==-1?url.getDefaultPort():url.getPort();
final String urlProtocol = url.getProtocol();
final String urlStr = url.toString();
// Needed for specifying HTTP pre-emptive authentication
HttpContext httpContext = null;
httpclient = new DefaultHttpClient();
// Set HTTP version
HTTPVersion httpVersion = request.getHttpVersion();
ProtocolVersion protocolVersion =
httpVersion==HTTPVersion.HTTP_1_1? new ProtocolVersion("HTTP", 1, 1):
new ProtocolVersion("HTTP", 1, 0);
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
protocolVersion);
// Set request timeout (default 1 minute--60000 milliseconds)
IGlobalOptions options = Implementation.of(IGlobalOptions.class);
options.acquire();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),
Integer.parseInt(options.getProperty("request-timeout-in-millis")));
options.release();
// Set proxy
ProxyConfig proxy = ProxyConfig.getInstance();
proxy.acquire();
if (proxy.isEnabled()) {
final HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), "http");
if (proxy.isAuthEnabled()) {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proxy.getHost(), proxy.getPort()),
new UsernamePasswordCredentials(proxy.getUsername(), new String(proxy.getPassword())));
}
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
}
proxy.release();
// HTTP Authentication
boolean authEnabled = request.getAuthMethods().size() > 0 ? true : false;
if (authEnabled) {
String uid = request.getAuthUsername();
String pwd = new String(request.getAuthPassword());
String host = StringUtil.isStrEmpty(request.getAuthHost()) ? urlHost : request.getAuthHost();
String realm = StringUtil.isStrEmpty(request.getAuthRealm()) ? AuthScope.ANY_REALM : request.getAuthRealm();
// Type of authentication
List<String> authPrefs = new ArrayList<String>(2);
List<HTTPAuthMethod> authMethods = request.getAuthMethods();
for(HTTPAuthMethod authMethod: authMethods){
switch(authMethod){
case BASIC:
authPrefs.add(AuthPolicy.BASIC);
break;
case DIGEST:
authPrefs.add(AuthPolicy.DIGEST);
break;
}
}
httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, urlPort, realm),
new UsernamePasswordCredentials(uid, pwd));
// preemptive mode
if (request.isAuthPreemptive()) {
BasicHttpContext localcontext = new BasicHttpContext();
BasicScheme basicAuth = new BasicScheme();
localcontext.setAttribute("preemptive-auth", basicAuth);
httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
httpContext = localcontext;
}
}
AbstractHttpMessage method = null;
final HTTPMethod httpMethod = request.getMethod();
try {
switch(httpMethod){
case GET:
method = new HttpGet(urlStr);
break;
case POST:
method = new HttpPost(urlStr);
break;
case PUT:
method = new HttpPut(urlStr);
break;
case DELETE:
method = new HttpDelete(urlStr);
break;
case HEAD:
method = new HttpHead(urlStr);
break;
case OPTIONS:
method = new HttpOptions(urlStr);
break;
case TRACE:
method = new HttpTrace(urlStr);
break;
}
method.setParams(new BasicHttpParams().setParameter(urlStr, url));
// Get request headers
MultiValueMap<String, String> header_data = request.getHeaders();
for (String key : header_data.keySet()) {
for(String value: header_data.get(key)) {
Header header = new BasicHeader(key, value);
method.addHeader(header);
}
}
// POST/PUT method specific logic
if (method instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest eeMethod = (HttpEntityEnclosingRequest) method;
// Create and set RequestEntity
ReqEntity bean = request.getBody();
if (bean != null) {
try {
AbstractHttpEntity entity = new ByteArrayEntity(bean.getBody().getBytes(bean.getCharSet()));
entity.setContentType(bean.getContentTypeCharsetFormatted());
eeMethod.setEntity(entity);
} catch (UnsupportedEncodingException ex) {
for(View view: views){
view.doError(Util.getStackTrace(ex));
view.doEnd();
}
return;
}
}
}
// SSL
// Set the hostname verifier:
SSLHostnameVerifier verifier = request.getSslHostNameVerifier();
final X509HostnameVerifier hcVerifier;
switch(verifier){
case STRICT:
hcVerifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
break;
case BROWSER_COMPATIBLE:
hcVerifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
break;
case ALLOW_ALL:
hcVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
break;
default:
hcVerifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
break;
}
// Register the SSL Scheme:
if(urlProtocol.equalsIgnoreCase("https")){
final String trustStorePath = request.getSslTrustStore();
final KeyStore trustStore = StringUtil.isStrEmpty(trustStorePath)?
null:
getTrustStore(trustStorePath, request.getSslTrustStorePassword());
SSLSocketFactory socketFactory = new SSLSocketFactory(
"TLS", // Algorithm
null, // Keystore
null, // Keystore password
trustStore,
null, // Secure Random
hcVerifier);
Scheme sch = new Scheme(urlProtocol, urlPort, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
}
// How to handle retries and redirects:
httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());
httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
request.isFollowRedirect());
// Now Execute:
long startTime = System.currentTimeMillis();
HttpResponse http_res = httpclient.execute((HttpUriRequest) method,
httpContext);
long endTime = System.currentTimeMillis();
ResponseBean response = new ResponseBean();
response.setExecutionTime(endTime - startTime);
response.setStatusCode(http_res.getStatusLine().getStatusCode());
response.setStatusLine(http_res.getStatusLine().toString());
final Header[] responseHeaders = http_res.getAllHeaders();
String contentType = null;
for (Header header : responseHeaders) {
response.addHeader(header.getName(), header.getValue());
if(header.getName().equalsIgnoreCase("content-type")) {
contentType = header.getValue();
}
}
// find out the charset:
final Charset charset;
{
Charset c;
if(contentType != null) {
final String charsetStr = Util.getCharsetFromContentType(contentType);
try{
c = Charset.forName(charsetStr);
}
catch(IllegalCharsetNameException ex) {
LOG.log(Level.WARNING, "Charset name is illegal: {0}", charsetStr);
c = Charset.defaultCharset();
}
catch(UnsupportedCharsetException ex) {
LOG.log(Level.WARNING, "Charset {0} is not supported in this JVM.", charsetStr);
c = Charset.defaultCharset();
}
catch(IllegalArgumentException ex) {
LOG.log(Level.WARNING, "Charset parameter is not available in Content-Type header!");
c = Charset.defaultCharset();
}
}
else {
c = Charset.defaultCharset();
LOG.log(Level.WARNING, "Content-Type header not available in response. Using platform default encoding: {0}", c.name());
}
charset = c;
}
final HttpEntity entity = http_res.getEntity();
if(entity != null){
InputStream is = entity.getContent();
try{
String responseBody = StreamUtil.inputStream2String(is, charset);
if (responseBody != null) {
response.setResponseBody(responseBody);
}
}
catch(IOException ex) {
final String msg = "Response body conversion to string using "
+ charset.displayName()
+ " encoding failed. Response body not set!";
for(View view: views) {
view.doError(msg);
}
LOG.log(Level.WARNING, msg);
}
}
// Now execute tests:
try {
junit.framework.TestSuite suite = TestUtil.getTestSuite(request, response);
if (suite != null) { // suite will be null if there is no associated script
TestResult testResult = TestUtil.execute(suite);
response.setTestResult(testResult);
}
} catch (TestException ex) {
for(View view: views){
view.doError(Util.getStackTrace(ex));
}
}
for(View view: views){
view.doResponse(response);
}
}
catch (IOException ex) {
if(!interruptedShutdown){
for(View view: views){
view.doError(Util.getStackTrace(ex));
}
}
else{
for(View view: views){
view.doCancelled();
}
}
} catch (Exception ex) {
if(!interruptedShutdown){
for(View view: views){
view.doError(Util.getStackTrace(ex));
}
}
else{
for(View view: views){
view.doCancelled();
}
}
} finally {
if (method != null && !interruptedShutdown) {
httpclient.getConnectionManager().shutdown();
}
for(View view: views){
view.doEnd();
}
isRequestCompleted = true;
}
}
private KeyStore getTrustStore(String trustStorePath, char[] trustStorePassword)
throws KeyStoreException, IOException,
NoSuchAlgorithmException, CertificateException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
if(!StringUtil.isStrEmpty(trustStorePath)) {
FileInputStream instream = new FileInputStream(new File(trustStorePath));
try{
trustStore.load(instream, trustStorePassword);
}
finally{
instream.close();
}
}
return trustStore;
}
@Override
public void abortExecution(){
if(!isRequestCompleted){
ClientConnectionManager conMgr = httpclient.getConnectionManager();
interruptedShutdown = true;
conMgr.shutdown();
}
else{
LOG.info("Request already completed. Doing nothing.");
}
}
private static final class PreemptiveAuth implements HttpRequestInterceptor {
@Override
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(
ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute(
"preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(
new AuthScope(
targetHost.getHostName(),
targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
}
} // if ends
} // process() method ends
} // Inner class ends
} |
package com.github.underscore.lodash;
import com.github.underscore.BiFunction;
import com.github.underscore.Function;
import java.util.*;
public final class Xml {
private static final String NULL = "null";
private static final String ELEMENT_TEXT = "element";
private static final String CDATA = "#cdata-section";
private static final String COMMENT = "#comment";
private static final String ENCODING = "#encoding";
private static final String STANDALONE = "#standalone";
private static final String OMITXMLDECLARATION = "#omit-xml-declaration";
private static final String YES = "yes";
private static final String TEXT = "#text";
private static final String NUMBER = "-number";
private static final String ELEMENT = "<" + ELEMENT_TEXT + ">";
private static final String CLOSED_ELEMENT = "</" + ELEMENT_TEXT + ">";
private static final String EMPTY_ELEMENT = ELEMENT + CLOSED_ELEMENT;
private static final String NULL_TRUE = " " + NULL + "=\"true\"/>";
private static final String NUMBER_TEXT = " number=\"true\"";
private static final String NUMBER_TRUE = NUMBER_TEXT + ">";
private static final String ARRAY = "-array";
private static final String ARRAY_TRUE = " array=\"true\"";
private static final String NULL_ELEMENT = "<" + ELEMENT_TEXT + NULL_TRUE;
private static final String BOOLEAN = "-boolean";
private static final String TRUE = "true";
private static final String SELF_CLOSING = "-self-closing";
private static final String STRING = "-string";
private static final String NULL_ATTR = "-null";
private static final String EMPTY_ARRAY = "-empty-array";
private static final String QUOT = """;
private static final String XML_HEADER = "<?xml ";
private static final java.nio.charset.Charset UTF_8 = java.nio.charset.Charset.forName("UTF-8");
private static final java.util.regex.Pattern ATTRS = java.util.regex.Pattern.compile(
"((?:(?!\\s|=).)*)\\s*?=\\s*?[\"']?((?:(?<=\")(?:(?<=\\\\)\"|[^\"])*|(?<=')"
+ "(?:(?<=\\\\)'|[^'])*)|(?:(?!\"|')(?:(?!\\/>|>|\\s).)+))");
private static final Map<String, String> XML_UNESCAPE = new HashMap<String, String>();
static {
XML_UNESCAPE.put(QUOT, "\"");
XML_UNESCAPE.put("&", "&");
XML_UNESCAPE.put("<", "<");
XML_UNESCAPE.put(">", ">");
XML_UNESCAPE.put("'", "'");
}
public static class XmlStringBuilder {
public enum Step {
TWO_SPACES(2), THREE_SPACES(3), FOUR_SPACES(4), COMPACT(0), TABS(1);
private int ident;
Step(int ident) {
this.ident = ident;
}
public int getIdent() {
return ident;
}
}
protected final StringBuilder builder;
private final Step identStep;
private int ident;
public XmlStringBuilder() {
builder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n");
identStep = Step.TWO_SPACES;
ident = 2;
}
public XmlStringBuilder(StringBuilder builder, Step identStep, int ident) {
this.builder = builder;
this.identStep = identStep;
this.ident = ident;
}
public XmlStringBuilder append(final String string) {
builder.append(string);
return this;
}
public XmlStringBuilder fillSpaces() {
for (int index = 0; index < ident; index += 1) {
builder.append(identStep == Step.TABS ? '\t' : ' ');
}
return this;
}
public XmlStringBuilder incIdent() {
ident += identStep.getIdent();
return this;
}
public XmlStringBuilder decIdent() {
ident -= identStep.getIdent();
return this;
}
public XmlStringBuilder newLine() {
if (identStep != Step.COMPACT) {
builder.append("\n");
}
return this;
}
public int getIdent() {
return ident;
}
public Step getIdentStep() {
return identStep;
}
public String toString() {
return builder.toString() + "\n</root>";
}
}
public static class XmlStringBuilderWithoutRoot extends XmlStringBuilder {
public XmlStringBuilderWithoutRoot(XmlStringBuilder.Step identStep, String encoding,
String standalone) {
super(new StringBuilder("<?xml version=\"1.0\" encoding=\""
+ XmlValue.escape(encoding).replace("\"", QUOT) + "\"" + standalone + "?>"
+ (identStep == Step.COMPACT ? "" : "\n")), identStep, 0);
}
public String toString() {
return builder.toString();
}
}
public static class XmlStringBuilderWithoutHeader extends XmlStringBuilder {
public XmlStringBuilderWithoutHeader(XmlStringBuilder.Step identStep, int ident) {
super(new StringBuilder(), identStep, ident);
}
public String toString() {
return builder.toString();
}
}
public static class XmlStringBuilderText extends XmlStringBuilderWithoutHeader {
public XmlStringBuilderText(XmlStringBuilder.Step identStep, int ident) {
super(identStep, ident);
}
}
public static class XmlArray {
public static void writeXml(Collection collection, String name, XmlStringBuilder builder,
boolean parentTextFound, Set<String> namespaces, boolean addArray) {
if (collection == null) {
builder.append(NULL);
return;
}
if (name != null) {
builder.fillSpaces().append("<").append(XmlValue.escapeName(name, namespaces));
if (addArray) {
builder.append(ARRAY_TRUE);
}
if (collection.isEmpty()) {
builder.append(" empty-array=\"true\"");
}
builder.append(">").incIdent();
if (!collection.isEmpty()) {
builder.newLine();
}
}
writeXml(collection, builder, name, parentTextFound, namespaces);
if (name != null) {
builder.decIdent();
if (!collection.isEmpty()) {
builder.newLine().fillSpaces();
}
builder.append("</").append(XmlValue.escapeName(name, namespaces)).append(">");
}
}
@SuppressWarnings("unchecked")
private static void writeXml(Collection collection, XmlStringBuilder builder, String name,
final boolean parentTextFound, Set<String> namespaces) {
boolean localParentTextFound = parentTextFound;
final List entries = U.newArrayList(collection);
for (int index = 0; index < entries.size(); index += 1) {
final Object value = entries.get(index);
final boolean addNewLine = index < entries.size() - 1
&& !XmlValue.getMapKey(XmlValue.getMapValue(entries.get(index + 1))).startsWith(TEXT);
if (value == null) {
builder.fillSpaces()
.append("<" + (name == null ? ELEMENT_TEXT : XmlValue.escapeName(name, namespaces))
+ (collection.size() == 1 ? ARRAY_TRUE : "") + NULL_TRUE);
} else {
if (value instanceof Map && ((Map) value).size() == 1
&& XmlValue.getMapKey(value).equals("#item")
&& XmlValue.getMapValue(value) instanceof Map) {
XmlObject.writeXml((Map) XmlValue.getMapValue(value), null, builder,
localParentTextFound, namespaces, true);
if (XmlValue.getMapKey(XmlValue.getMapValue(value)).startsWith(TEXT)) {
localParentTextFound = true;
continue;
}
} else {
XmlValue.writeXml(value, name == null ? ELEMENT_TEXT : name, builder, localParentTextFound,
namespaces, collection.size() == 1 || value instanceof Collection);
}
localParentTextFound = false;
}
if (addNewLine) {
builder.newLine();
}
}
}
public static void writeXml(byte[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(short[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(int[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(long[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(float[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(double[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(boolean[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(char[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(Object[] array, String name, XmlStringBuilder builder, boolean parentTextFound,
Set<String> namespaces) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
XmlValue.writeXml(array[i], name == null ? ELEMENT_TEXT : name, builder,
parentTextFound, namespaces, false);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
}
public static class XmlObject {
@SuppressWarnings("unchecked")
public static void writeXml(final Map map, final String name, final XmlStringBuilder builder,
final boolean parentTextFound, final Set<String> namespaces, final boolean addArray) {
if (map == null) {
XmlValue.writeXml(NULL, name, builder, false, namespaces, addArray);
return;
}
final List<XmlStringBuilder> elems = U.newArrayList();
final List<String> attrs = U.newArrayList();
final XmlStringBuilder.Step identStep = builder.getIdentStep();
final int ident = builder.getIdent() + (name == null ? 0 : builder.getIdentStep().getIdent());
final List<Map.Entry> entries = U.newArrayList(map.entrySet());
final Set<String> attrKeys = U.newLinkedHashSet();
fillNamespacesAndAttrs(map, namespaces, attrKeys);
for (int index = 0; index < entries.size(); index += 1) {
final Map.Entry entry = entries.get(index);
final boolean addNewLine = index < entries.size() - 1
&& !String.valueOf(entries.get(index + 1).getKey()).startsWith(TEXT);
if (String.valueOf(entry.getKey()).startsWith("-") && (entry.getValue() instanceof String)) {
attrs.add(" " + XmlValue.escapeName(String.valueOf(entry.getKey()).substring(1), namespaces)
+ "=\"" + XmlValue.escape(String.valueOf(entry.getValue())).replace("\"", QUOT) + "\"");
} else if (String.valueOf(entry.getKey()).startsWith(TEXT)) {
addText(entry, elems, identStep, ident, attrKeys, attrs);
} else {
boolean localParentTextFound = (!elems.isEmpty()
&& elems.get(elems.size() - 1) instanceof XmlStringBuilderText) || parentTextFound;
processElements(entry, identStep, ident, addNewLine, elems, namespaces, localParentTextFound);
}
}
if (addArray && !attrKeys.contains(ARRAY)) {
attrs.add(ARRAY_TRUE);
}
addToBuilder(name, parentTextFound, builder, namespaces, attrs, elems);
}
@SuppressWarnings("unchecked")
private static void fillNamespacesAndAttrs(final Map map, final Set<String> namespaces,
final Set<String> attrKeys) {
for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
if (String.valueOf(entry.getKey()).startsWith("-") && !(entry.getValue() instanceof Map)
&& !(entry.getValue() instanceof List)) {
if (String.valueOf(entry.getKey()).startsWith("-xmlns:")) {
namespaces.add(String.valueOf(entry.getKey()).substring(7));
}
attrKeys.add(String.valueOf(entry.getKey()));
}
}
}
private static void addToBuilder(final String name, final boolean parentTextFound,
final XmlStringBuilder builder, final Set<String> namespaces, final List<String> attrs,
final List<XmlStringBuilder> elems) {
final boolean selfClosing = attrs.remove(" self-closing=\"true\"");
addOpenElement(name, parentTextFound, builder, namespaces, selfClosing, attrs, elems);
if (!selfClosing) {
for (XmlStringBuilder localBuilder1 : elems) {
builder.append(localBuilder1.toString());
}
}
if (name != null) {
builder.decIdent();
if (!elems.isEmpty() && !(elems.get(elems.size() - 1) instanceof XmlStringBuilderText)) {
builder.newLine().fillSpaces();
}
if (!selfClosing) {
builder.append("</").append(XmlValue.escapeName(name, namespaces)).append(">");
}
}
}
private static void addOpenElement(final String name, final boolean parentTextFound,
final XmlStringBuilder builder, final Set<String> namespaces, final boolean selfClosing,
final List<String> attrs, final List<XmlStringBuilder> elems) {
if (name != null) {
if (!parentTextFound) {
builder.fillSpaces();
}
builder.append("<").append(XmlValue.escapeName(name, namespaces)).append(U.join(attrs, ""));
if (selfClosing) {
builder.append("/");
}
builder.append(">").incIdent();
if (!elems.isEmpty() && !(elems.get(0) instanceof XmlStringBuilderText)) {
builder.newLine();
}
}
}
private static void processElements(final Map.Entry entry, final XmlStringBuilder.Step identStep,
final int ident, final boolean addNewLine, final List<XmlStringBuilder> elems,
final Set<String> namespaces, final boolean parentTextFound) {
if (String.valueOf(entry.getKey()).startsWith(COMMENT)) {
addComment(entry, identStep, ident, parentTextFound, addNewLine, elems);
} else if (String.valueOf(entry.getKey()).startsWith(CDATA)) {
addCdata(entry, identStep, ident, addNewLine, elems);
} else if (entry.getValue() instanceof List && !((List) entry.getValue()).isEmpty()) {
addElements(identStep, ident, entry, namespaces, elems, addNewLine);
} else {
addElement(identStep, ident, entry, namespaces, elems, addNewLine);
}
}
private static void addText(final Map.Entry entry, final List<XmlStringBuilder> elems,
final XmlStringBuilder.Step identStep, final int ident, final Set<String> attrKeys,
final List<String> attrs) {
if (entry.getValue() instanceof List) {
for (Object value : (List) entry.getValue()) {
elems.add(new XmlStringBuilderText(identStep, ident).append(
XmlValue.escape(String.valueOf(value))));
}
} else {
if (entry.getValue() instanceof Number && !attrKeys.contains(NUMBER)) {
attrs.add(NUMBER_TEXT);
} else if (entry.getValue() instanceof Boolean && !attrKeys.contains(BOOLEAN)) {
attrs.add(" boolean=\"true\"");
} else if (entry.getValue() == null && !attrKeys.contains(NULL_ATTR)) {
attrs.add(" null=\"true\"");
return;
} else if ("".equals(entry.getValue()) && !attrKeys.contains(STRING)) {
attrs.add(" string=\"true\"");
return;
}
elems.add(new XmlStringBuilderText(identStep, ident).append(
XmlValue.escape(String.valueOf(entry.getValue()))));
}
}
private static void addElements(final XmlStringBuilder.Step identStep, final int ident, Map.Entry entry,
Set<String> namespaces, final List<XmlStringBuilder> elems, final boolean addNewLine) {
boolean parentTextFound = !elems.isEmpty() && elems.get(elems.size() - 1) instanceof XmlStringBuilderText;
final XmlStringBuilder localBuilder = new XmlStringBuilderWithoutHeader(identStep, ident);
XmlArray.writeXml((List) entry.getValue(), localBuilder,
String.valueOf(entry.getKey()), parentTextFound, namespaces);
if (addNewLine) {
localBuilder.newLine();
}
elems.add(localBuilder);
}
private static void addElement(final XmlStringBuilder.Step identStep, final int ident, Map.Entry entry,
Set<String> namespaces, final List<XmlStringBuilder> elems, final boolean addNewLine) {
boolean parentTextFound = !elems.isEmpty() && elems.get(elems.size() - 1) instanceof XmlStringBuilderText;
XmlStringBuilder localBuilder = new XmlStringBuilderWithoutHeader(identStep, ident);
XmlValue.writeXml(entry.getValue(), String.valueOf(entry.getKey()),
localBuilder, parentTextFound, namespaces, false);
if (addNewLine) {
localBuilder.newLine();
}
elems.add(localBuilder);
}
private static void addComment(Map.Entry entry, XmlStringBuilder.Step identStep, int ident,
boolean parentTextFound, boolean addNewLine, List<XmlStringBuilder> elems) {
if (entry.getValue() instanceof List) {
for (Iterator iterator = ((List) entry.getValue()).iterator(); iterator.hasNext(); ) {
elems.add(addCommentValue(identStep, ident, String.valueOf(iterator.next()), parentTextFound,
iterator.hasNext() || addNewLine));
}
} else {
elems.add(addCommentValue(identStep, ident, String.valueOf(entry.getValue()), parentTextFound,
addNewLine));
}
}
private static XmlStringBuilder addCommentValue(XmlStringBuilder.Step identStep, int ident, String value,
boolean parentTextFound, boolean addNewLine) {
XmlStringBuilder localBuilder = new XmlStringBuilderWithoutHeader(identStep, ident);
if (!parentTextFound) {
localBuilder.fillSpaces();
}
localBuilder.append("<!--").append(value).append("-->");
if (addNewLine) {
localBuilder.newLine();
}
return localBuilder;
}
private static void addCdata(Map.Entry entry, XmlStringBuilder.Step identStep, int ident,
boolean addNewLine, List<XmlStringBuilder> elems) {
if (entry.getValue() instanceof List) {
for (Iterator iterator = ((List) entry.getValue()).iterator(); iterator.hasNext(); ) {
elems.add(addCdataValue(identStep, ident, String.valueOf(iterator.next()),
iterator.hasNext() || addNewLine));
}
} else {
elems.add(addCdataValue(identStep, ident, String.valueOf(entry.getValue()), addNewLine));
}
}
private static XmlStringBuilder addCdataValue(XmlStringBuilder.Step identStep, int ident, String value,
boolean addNewLine) {
XmlStringBuilder localBuilder = new XmlStringBuilderText(identStep, ident);
localBuilder.append("<![CDATA[").append(value).append("]]>");
if (addNewLine) {
localBuilder.newLine();
}
return localBuilder;
}
}
public static class XmlValue {
public static void writeXml(Object value, String name, XmlStringBuilder builder, boolean parentTextFound,
Set<String> namespaces, boolean addArray) {
if (value instanceof Map) {
XmlObject.writeXml((Map) value, name, builder, parentTextFound, namespaces, addArray);
return;
}
if (value instanceof Collection) {
XmlArray.writeXml((Collection) value, name, builder, parentTextFound, namespaces, addArray);
return;
}
if (!parentTextFound) {
builder.fillSpaces();
}
if (value == null) {
builder.append("<" + XmlValue.escapeName(name, namespaces) + NULL_TRUE);
} else if (value instanceof String) {
if (((String) value).isEmpty()) {
builder.append("<" + XmlValue.escapeName(name, namespaces)
+ (addArray ? ARRAY_TRUE : "") + " string=\"true\"/>");
} else {
builder.append("<" + XmlValue.escapeName(name, namespaces)
+ (addArray ? ARRAY_TRUE : "") + (name.startsWith("?") ? " " : ">"));
builder.append(escape((String) value));
if (name.startsWith("?")) {
builder.append("?>");
} else {
builder.append("</" + XmlValue.escapeName(name, namespaces) + ">");
}
}
} else {
processArrays(value, builder, name, parentTextFound, namespaces, addArray);
}
}
private static void processArrays(Object value, XmlStringBuilder builder, String name,
boolean parentTextFound, Set<String> namespaces, boolean addArray) {
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN()) {
builder.append(NULL_ELEMENT);
} else {
builder.append("<" + XmlValue.escapeName(name, namespaces)
+ (addArray ? ARRAY_TRUE : "") + NUMBER_TRUE);
builder.append(value.toString());
builder.append("</" + XmlValue.escapeName(name, namespaces) + ">");
}
} else if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN()) {
builder.append(NULL_ELEMENT);
} else {
builder.append("<" + XmlValue.escapeName(name, namespaces) + NUMBER_TRUE);
builder.append(value.toString());
builder.append("</" + XmlValue.escapeName(name, namespaces) + ">");
}
} else if (value instanceof Number) {
builder.append("<" + XmlValue.escapeName(name, namespaces)
+ (addArray ? ARRAY_TRUE : "") + NUMBER_TRUE);
builder.append(value.toString());
builder.append("</" + XmlValue.escapeName(name, namespaces) + ">");
} else if (value instanceof Boolean) {
builder.append("<" + XmlValue.escapeName(name, namespaces)
+ (addArray ? ARRAY_TRUE : "") + " boolean=\"true\">");
builder.append(value.toString());
builder.append("</" + XmlValue.escapeName(name, namespaces) + ">");
} else {
builder.append("<" + XmlValue.escapeName(name, namespaces) + ">");
if (value instanceof byte[]) {
builder.newLine().incIdent();
XmlArray.writeXml((byte[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof short[]) {
builder.newLine().incIdent();
XmlArray.writeXml((short[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else {
processArrays2(value, builder, name, parentTextFound, namespaces);
}
builder.append("</" + XmlValue.escapeName(name, namespaces) + ">");
}
}
private static void processArrays2(Object value, XmlStringBuilder builder, String name,
boolean parentTextFound, Set<String> namespaces) {
if (value instanceof int[]) {
builder.newLine().incIdent();
XmlArray.writeXml((int[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof long[]) {
builder.newLine().incIdent();
XmlArray.writeXml((long[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof float[]) {
builder.newLine().incIdent();
XmlArray.writeXml((float[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof double[]) {
builder.newLine().incIdent();
XmlArray.writeXml((double[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof boolean[]) {
builder.newLine().incIdent();
XmlArray.writeXml((boolean[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof char[]) {
builder.newLine().incIdent();
XmlArray.writeXml((char[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof Object[]) {
builder.newLine().incIdent();
XmlArray.writeXml((Object[]) value, name, builder, parentTextFound, namespaces);
builder.decIdent().newLine().fillSpaces();
} else {
builder.append(value.toString());
}
}
public static String escapeName(String name, Set<String> namespaces) {
final int length = name.length();
if (length == 0) {
return "__EE__EMPTY__EE__";
}
final StringBuilder result = new StringBuilder();
char ch = name.charAt(0);
if (com.sun.org.apache.xerces.internal.util.XMLChar.isNameStart(ch) && ch != ':' || ch == '?') {
result.append(ch);
} else {
result.append("__").append(Base32.encode(Character.toString(ch))).append("__");
}
for (int i = 1; i < length; ++i) {
ch = name.charAt(i);
if (ch == ':' && ("xmlns".equals(name.substring(0, i))
|| namespaces.contains(name.substring(0, i)))) {
result.append(ch);
} else if (com.sun.org.apache.xerces.internal.util.XMLChar.isName(ch) && ch != ':') {
result.append(ch);
} else {
result.append("__").append(Base32.encode(Character.toString(ch))).append("__");
}
}
return result.toString();
}
public static String escape(String s) {
if (s == null) {
return "";
}
StringBuilder sb = new StringBuilder();
escape(s, sb);
return sb.toString();
}
private static void escape(String s, StringBuilder sb) {
final int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '\'':
sb.append("'");
break;
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\t");
break;
case '€':
sb.append("€");
break;
default:
if (ch <= '\u001F' || ch >= '\u007F' && ch <= '\u009F'
|| ch >= '\u2000' && ch <= '\u20FF') {
String ss = Integer.toHexString(ch);
sb.append("&
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase()).append(";");
} else {
sb.append(ch);
}
break;
}
}
}
public static String unescape(String s) {
if (s == null) {
return "";
}
StringBuilder sb = new StringBuilder();
unescape(s, sb);
return sb.toString();
}
private static void unescape(String s, StringBuilder sb) {
final int len = s.length();
final StringBuilder localSb = new StringBuilder();
int index = 0;
while (index < len) {
final int skipChars = translate(s, index, localSb);
if (skipChars > 0) {
sb.append(localSb);
localSb.setLength(0);
index += skipChars;
} else {
sb.append(s.charAt(index));
index += 1;
}
}
}
private static int translate(final CharSequence input, final int index, final StringBuilder builder) {
final int shortest = 4;
final int longest = 6;
if ('&' == input.charAt(index)) {
int max = longest;
if (index + longest > input.length()) {
max = input.length() - index;
}
for (int i = max; i >= shortest; i
final CharSequence subSeq = input.subSequence(index, index + i);
final String result = XML_UNESCAPE.get(subSeq.toString());
if (result != null) {
builder.append(result);
return i;
}
}
}
return 0;
}
public static String getMapKey(Object map) {
return map instanceof Map && !((Map) map).isEmpty() ? String.valueOf(
((Map.Entry) ((Map) map).entrySet().iterator().next()).getKey()) : "";
}
public static Object getMapValue(Object map) {
return map instanceof Map && !((Map) map).isEmpty()
? ((Map.Entry) ((Map) map).entrySet().iterator().next()).getValue() : null;
}
}
public static String toXml(Collection collection, XmlStringBuilder.Step identStep) {
final XmlStringBuilder builder = new XmlStringBuilderWithoutRoot(identStep, UTF_8.name(), "");
writeArray(collection, builder);
return builder.toString();
}
public static String toXml(Collection collection) {
return toXml(collection, XmlStringBuilder.Step.TWO_SPACES);
}
public static String toXml(Map map, XmlStringBuilder.Step identStep) {
final XmlStringBuilder builder;
final Map localMap;
if (map != null && map.containsKey(ENCODING)) {
localMap = (Map) U.clone(map);
builder = checkStandalone(String.valueOf(localMap.remove(ENCODING)), identStep, localMap);
} else if (map != null && map.containsKey(STANDALONE)) {
localMap = (Map) U.clone(map);
builder = new XmlStringBuilderWithoutRoot(identStep, UTF_8.name(),
" standalone=\"" + (YES.equals(map.get(STANDALONE)) ? YES : "no") + "\"");
localMap.remove(STANDALONE);
} else if (map != null && map.containsKey(OMITXMLDECLARATION)) {
localMap = (Map) U.clone(map);
builder = new XmlStringBuilderWithoutHeader(identStep, 0);
localMap.remove(OMITXMLDECLARATION);
} else {
builder = new XmlStringBuilderWithoutRoot(identStep, UTF_8.name(), "");
localMap = map;
}
checkLocalMap(builder, localMap);
return builder.toString();
}
private static void checkLocalMap(final XmlStringBuilder builder, final Map localMap) {
if (localMap == null || localMap.size() != 1
|| XmlValue.getMapKey(localMap).startsWith("-")
|| XmlValue.getMapValue(localMap) instanceof List) {
if ("root".equals(XmlValue.getMapKey(localMap))) {
writeArray((List) XmlValue.getMapValue(localMap), builder);
} else {
XmlObject.writeXml(localMap, getRootName(localMap), builder, false,
U.<String>newLinkedHashSet(), false);
}
} else {
XmlObject.writeXml(localMap, null, builder, false, U.<String>newLinkedHashSet(), false);
}
}
private static void writeArray(final Collection collection, final XmlStringBuilder builder) {
builder.append("<root");
if (collection != null && collection.isEmpty()) {
builder.append(" empty-array=\"true\"");
}
builder.append(">").incIdent();
if (collection != null && !collection.isEmpty()) {
builder.newLine();
}
XmlArray.writeXml(collection, null, builder, false, U.<String>newLinkedHashSet(), false);
if (collection != null && !collection.isEmpty()) {
builder.newLine();
}
builder.append("</root>");
}
private static XmlStringBuilder checkStandalone(String encoding, XmlStringBuilder.Step identStep,
final Map localMap) {
final XmlStringBuilder builder;
if (localMap.containsKey(STANDALONE)) {
builder = new XmlStringBuilderWithoutRoot(identStep, encoding,
" standalone=\"" + (YES.equals(localMap.get(STANDALONE)) ? YES : "no") + "\"");
localMap.remove(STANDALONE);
} else {
builder = new XmlStringBuilderWithoutRoot(identStep, encoding, "");
}
return builder;
}
@SuppressWarnings("unchecked")
private static String getRootName(final Map localMap) {
int foundAttrs = 0;
int foundElements = 0;
if (localMap != null) {
for (Map.Entry entry : (Set<Map.Entry>) localMap.entrySet()) {
if (String.valueOf(entry.getKey()).startsWith("-")) {
foundAttrs += 1;
} else if (!String.valueOf(entry.getKey()).startsWith(COMMENT)
&& !String.valueOf(entry.getKey()).startsWith("?")
&& (!(entry.getValue() instanceof List) || ((List) entry.getValue()).size() <= 1)) {
foundElements += 1;
}
}
}
return foundAttrs == 0 && foundElements == 1 ? null : "root";
}
public static String toXml(Map map) {
return toXml(map, XmlStringBuilder.Step.TWO_SPACES);
}
@SuppressWarnings("unchecked")
private static Object getValue(final Object value) {
final Object localValue;
if (value instanceof Map && ((Map<String, Object>) value).entrySet().size() == 1) {
final Map.Entry<String, Object> entry = ((Map<String, Object>) value).entrySet().iterator().next();
if (TEXT.equals(entry.getKey()) || entry.getKey().equals(ELEMENT_TEXT)) {
localValue = entry.getValue();
} else {
localValue = value;
}
} else {
localValue = value;
}
return localValue instanceof String ? XmlValue.unescape((String) localValue) : localValue;
}
private static Object stringToNumber(String number) {
final Object localValue;
if (number.contains(".") || number.contains("e") || number.contains("E")) {
if (number.length() > 9) {
localValue = new java.math.BigDecimal(number);
} else {
localValue = Double.valueOf(number);
}
} else {
if (number.length() > 20) {
localValue = new java.math.BigInteger(number);
} else {
localValue = Long.valueOf(number);
}
}
return localValue;
}
@SuppressWarnings("unchecked")
private static Object createMap(final org.w3c.dom.Node node,
final BiFunction<Object, Set<String>, String> elementMapper,
final Function<Object, Object> nodeMapper, final Map<String, Object> attrMap,
final int[] uniqueIds, final String source, final int[] sourceIndex, final Set<String> namespaces) {
final Map<String, Object> map = U.newLinkedHashMap();
map.putAll(attrMap);
final org.w3c.dom.NodeList nodeList = node.getChildNodes();
for (int index = 0; index < nodeList.getLength(); index++) {
final org.w3c.dom.Node currentNode = nodeList.item(index);
final String name;
if (currentNode.getNodeType() == org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE) {
name = "?" + currentNode.getNodeName();
} else {
name = currentNode.getNodeName();
}
final Object value;
if (currentNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
sourceIndex[0] = source.indexOf("<" + name, sourceIndex[0]) + name.length() + 1;
value = addElement(sourceIndex, source, elementMapper, nodeMapper,
uniqueIds, currentNode, namespaces);
} else {
if (COMMENT.equals(name)) {
sourceIndex[0] = source.indexOf("-->", sourceIndex[0]) + 3;
} else if (CDATA.equals(name)) {
sourceIndex[0] = source.indexOf("]]>", sourceIndex[0]) + 3;
}
value = currentNode.getTextContent();
}
if (TEXT.equals(name) && node.getChildNodes().getLength() > 1
&& String.valueOf(value).trim().isEmpty()
|| currentNode.getNodeType() == org.w3c.dom.Node.DOCUMENT_TYPE_NODE) {
continue;
}
addNodeValue(map, name, value, elementMapper, nodeMapper, uniqueIds, namespaces);
}
return checkNumberAndBoolean(map, node.getNodeName());
}
@SuppressWarnings("unchecked")
private static Object checkNumberAndBoolean(final Map<String, Object> map, final String name) {
final Map<String, Object> localMap;
if (map.containsKey(NUMBER) && TRUE.equals(map.get(NUMBER)) && map.containsKey(TEXT)) {
localMap = (Map) ((LinkedHashMap) map).clone();
localMap.remove(NUMBER);
localMap.put(TEXT, stringToNumber(String.valueOf(localMap.get(TEXT))));
} else {
localMap = map;
}
final Map<String, Object> localMap2;
if (map.containsKey(BOOLEAN) && TRUE.equals(map.get(BOOLEAN)) && map.containsKey(TEXT)) {
localMap2 = (Map) ((LinkedHashMap) localMap).clone();
localMap2.remove(BOOLEAN);
localMap2.put(TEXT, Boolean.valueOf(String.valueOf(localMap.get(TEXT))));
} else {
localMap2 = localMap;
}
return checkArray(localMap2, name);
}
@SuppressWarnings("unchecked")
private static Object checkArray(final Map<String, Object> map, final String name) {
final Map<String, Object> localMap = checkNullAndString(map);
final Object object;
if (map.containsKey(ARRAY) && TRUE.equals(map.get(ARRAY))) {
final Map<String, Object> localMap4 = (Map) ((LinkedHashMap) localMap).clone();
localMap4.remove(ARRAY);
object = name.equals(XmlValue.getMapKey(localMap4))
? U.newArrayList(Arrays.asList(getValue(XmlValue.getMapValue(localMap4))))
: U.newArrayList(Arrays.asList(getValue(localMap4)));
} else {
object = localMap;
}
final Object object2;
if (map.containsKey(EMPTY_ARRAY) && TRUE.equals(map.get(EMPTY_ARRAY))) {
final Map<String, Object> localMap4 = (Map) ((LinkedHashMap) map).clone();
localMap4.remove(EMPTY_ARRAY);
if (localMap4.containsKey(ARRAY) && TRUE.equals(localMap4.get(ARRAY))
&& localMap4.size() == 1) {
object2 = U.newArrayList();
((List) object2).add(U.newArrayList());
} else {
object2 = localMap4.isEmpty() ? U.newArrayList() : localMap4;
}
} else {
object2 = object;
}
return object2;
}
@SuppressWarnings("unchecked")
private static Map<String, Object> checkNullAndString(final Map<String, Object> map) {
final Map<String, Object> localMap;
if (map.containsKey(NULL_ATTR) && TRUE.equals(map.get(NULL_ATTR))) {
localMap = (Map) ((LinkedHashMap) map).clone();
localMap.remove(NULL_ATTR);
if (!map.containsKey(TEXT)) {
localMap.put(TEXT, null);
}
} else {
localMap = map;
}
final Map<String, Object> localMap2;
if (map.containsKey(STRING) && TRUE.equals(map.get(STRING))) {
localMap2 = (Map) ((LinkedHashMap) localMap).clone();
localMap2.remove(STRING);
if (!map.containsKey(TEXT)) {
localMap2.put(TEXT, "");
}
} else {
localMap2 = localMap;
}
return localMap2;
}
private static Object addElement(final int[] sourceIndex, final String source,
final BiFunction<Object, Set<String>, String> elementMapper,
final Function<Object, Object> nodeMapper, final int[] uniqueIds,
final org.w3c.dom.Node currentNode, final Set<String> namespaces) {
final Map<String, Object> attrMapLocal = U.newLinkedHashMap();
if (currentNode.getAttributes().getLength() > 0) {
final java.util.regex.Matcher matcher = ATTRS.matcher(getAttributes(sourceIndex[0], source));
while (matcher.find()) {
if (matcher.group(1).startsWith("xmlns:")) {
namespaces.add(matcher.group(1).substring(6));
}
}
matcher.reset();
while (matcher.find()) {
addNodeValue(attrMapLocal, '-' + matcher.group(1), matcher.group(2),
elementMapper, nodeMapper, uniqueIds, namespaces);
}
}
if (getAttributes(sourceIndex[0], source).endsWith("/")
&& !attrMapLocal.containsKey(SELF_CLOSING) && (attrMapLocal.size() != 1
|| ((!attrMapLocal.containsKey(STRING) || !TRUE.equals(attrMapLocal.get(STRING)))
&& (!attrMapLocal.containsKey(NULL_ATTR) || !TRUE.equals(attrMapLocal.get(NULL_ATTR)))))) {
attrMapLocal.put(SELF_CLOSING, TRUE);
}
return createMap(currentNode, elementMapper, nodeMapper, attrMapLocal, uniqueIds, source,
sourceIndex, namespaces);
}
static String getAttributes(final int sourceIndex, final String source) {
boolean scanQuote = false;
for (int index = sourceIndex; index < source.length(); index += 1) {
if (source.charAt(index) == '"') {
scanQuote = !scanQuote;
continue;
}
if (!scanQuote && source.charAt(index) == '>') {
return source.substring(sourceIndex, index);
}
}
return "";
}
private static String unescapeName(final String name) {
if (name == null) {
return name;
}
final int length = name.length();
if ("__EE__EMPTY__EE__".equals(name)) {
return "";
}
if ("-__EE__EMPTY__EE__".equals(name)) {
return "-";
}
if (!name.contains("__")) {
return name;
}
StringBuilder result = new StringBuilder();
int underlineCount = 0;
StringBuilder lastChars = new StringBuilder();
outer:
for (int i = 0; i < length; ++i) {
char ch = name.charAt(i);
if (ch == '_') {
lastChars.append(ch);
} else {
if (lastChars.length() == 2) {
StringBuilder nameToDecode = new StringBuilder();
for (int j = i; j < length; ++j) {
if (name.charAt(j) == '_') {
underlineCount += 1;
if (underlineCount == 2) {
try {
result.append(Base32.decode(nameToDecode.toString()));
} catch (Base32.DecodingException ex) {
result.append("__").append(nameToDecode.toString())
.append(lastChars);
}
i = j;
underlineCount = 0;
lastChars.setLength(0);
continue outer;
}
} else {
nameToDecode.append(name.charAt(j));
underlineCount = 0;
}
}
}
result.append(lastChars).append(ch);
lastChars.setLength(0);
}
}
return result.append(lastChars).toString();
}
@SuppressWarnings("unchecked")
private static void addNodeValue(final Map<String, Object> map, final String name, final Object value,
final BiFunction<Object, Set<String>, String> elementMapper, final Function<Object, Object> nodeMapper,
final int[] uniqueIds, final Set<String> namespaces) {
final String elementName = unescapeName(elementMapper.apply(name, namespaces));
if (map.containsKey(elementName)) {
if (TEXT.equals(elementName)) {
map.put(elementName + uniqueIds[0], nodeMapper.apply(getValue(value)));
uniqueIds[0] += 1;
} else if (COMMENT.equals(elementName)) {
map.put(elementName + uniqueIds[1], nodeMapper.apply(getValue(value)));
uniqueIds[1] += 1;
} else if (CDATA.equals(elementName)) {
map.put(elementName + uniqueIds[2], nodeMapper.apply(getValue(value)));
uniqueIds[2] += 1;
} else {
final Object object = map.get(elementName);
if (object instanceof List) {
addText(map, elementName, (List<Object>) object, value);
} else {
final List<Object> objects = U.newArrayList();
objects.add(object);
addText(map, elementName, objects, value);
map.put(elementName, objects);
}
}
} else {
if (elementName != null) {
map.put(elementName, nodeMapper.apply(getValue(value)));
}
}
}
@SuppressWarnings("unchecked")
private static void addText(final Map<String, Object> map, final String name, final List<Object> objects,
final Object value) {
int lastIndex = map.size() - 1;
final int index = objects.size();
while (true) {
final Map.Entry lastElement = (Map.Entry) map.entrySet().toArray()[lastIndex];
if (name.equals(String.valueOf(lastElement.getKey()))) {
break;
}
final Map<String, Object> item = U.newLinkedHashMap();
final Map<String, Object> text = U.newLinkedHashMap();
text.put(String.valueOf(lastElement.getKey()), map.remove(lastElement.getKey()));
item.put("#item", text);
objects.add(index, item);
lastIndex -= 1;
}
final Object newValue = getValue(value);
if (newValue instanceof List) {
objects.add(((List) newValue).get(0));
} else {
objects.add(newValue);
}
}
@SuppressWarnings("unchecked")
public static Object fromXml(final String xml) {
if (xml == null) {
return null;
}
try {
org.w3c.dom.Document document = createDocument(xml);
final Object result = createMap(document, new BiFunction<Object, Set<String>, String>() {
public String apply(Object object, Set<String> namespaces) {
return String.valueOf(object);
}
}, new Function<Object, Object>() {
public Object apply(Object object) {
return object;
}
}, Collections.<String, Object>emptyMap(), new int[] {1, 1, 1}, xml, new int[] {0},
U.<String>newLinkedHashSet());
if (checkResult(xml, document, result)) {
return ((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue();
}
return result;
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
@SuppressWarnings("unchecked")
private static boolean checkResult(final String xml, org.w3c.dom.Document document, final Object result) {
final Map<String, String> headerAttributes = getHeaderAttributes(xml);
if (document.getXmlEncoding() != null && !"UTF-8".equalsIgnoreCase(document.getXmlEncoding())) {
((Map) result).put(ENCODING, document.getXmlEncoding());
if (headerAttributes.containsKey(STANDALONE.substring(1))) {
((Map) result).put(STANDALONE, headerAttributes.get(STANDALONE.substring(1)));
}
} else if (headerAttributes.containsKey(STANDALONE.substring(1))) {
((Map) result).put(STANDALONE, headerAttributes.get(STANDALONE.substring(1)));
} else if (((Map.Entry) ((Map) result).entrySet().iterator().next()).getKey().equals("root")
&& (((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue() instanceof List
|| ((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue() instanceof Map)) {
if (xml.startsWith(XML_HEADER)) {
return true;
} else {
((Map) result).put(OMITXMLDECLARATION, YES);
}
} else if (!xml.startsWith(XML_HEADER)) {
((Map) result).put(OMITXMLDECLARATION, YES);
}
return false;
}
private static Map<String, String> getHeaderAttributes(final String xml) {
final Map<String, String> result = U.newLinkedHashMap();
if (xml.startsWith(XML_HEADER)) {
final String xmlLocal = xml.substring(XML_HEADER.length(),
Math.max(XML_HEADER.length(), xml.indexOf("?>", XML_HEADER.length())));
final java.util.regex.Matcher matcher = ATTRS.matcher(xmlLocal);
while (matcher.find()) {
result.put(matcher.group(1), matcher.group(2));
}
}
return result;
}
private static class MyEntityResolver implements org.xml.sax.EntityResolver {
public org.xml.sax.InputSource resolveEntity(String publicId, String systemId) {
return new org.xml.sax.InputSource(new java.io.StringReader(""));
}
}
private static org.w3c.dom.Document createDocument(final String xml)
throws java.io.IOException, javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException {
final javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
final javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler());
builder.setEntityResolver(new MyEntityResolver());
return builder.parse(new org.xml.sax.InputSource(new java.io.StringReader(xml)));
}
public static Object fromXmlMakeArrays(final String xml) {
try {
org.w3c.dom.Document document = createDocument(xml);
final Object result = createMap(document, new BiFunction<Object, Set<String>, String>() {
public String apply(Object object, Set<String> namespaces) {
return String.valueOf(object);
}
}, new Function<Object, Object>() {
public Object apply(Object object) {
return object instanceof List ? object : U.newArrayList(Arrays.asList(object));
}
}, Collections.<String, Object>emptyMap(), new int[] {1, 1, 1}, xml, new int[] {0},
U.<String>newLinkedHashSet());
if (checkResult(xml, document, result)) {
return ((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue();
}
return result;
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
public static Object fromXmlWithElementMapper(final String xml,
final BiFunction<Object, Set<String>, String> elementMapper) {
try {
org.w3c.dom.Document document = createDocument(xml);
final Object result = createMap(document, elementMapper, new Function<Object, Object>() {
public Object apply(Object object) {
return object;
}
}, Collections.<String, Object>emptyMap(), new int[]{1, 1, 1}, xml, new int[]{0},
U.<String>newLinkedHashSet());
if (checkResult(xml, document, result)) {
return ((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue();
}
return result;
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
public static Object fromXmlWithoutNamespaces(final String xml) {
return fromXmlWithElementMapper(xml, new BiFunction<Object, Set<String>, String>() {
public String apply(Object object, Set<String> namespaces) {
final String localString = String.valueOf(object);
final String result;
if (localString.startsWith("-") && namespaces.contains(localString
.substring(1, Math.max(1, localString.indexOf(':'))))) {
result = "-" + localString.substring(Math.max(0, localString.indexOf(':') + 1));
} else if (namespaces.contains(localString
.substring(0, Math.max(0, localString.indexOf(':'))))) {
result = localString.substring(Math.max(0, localString.indexOf(':') + 1));
} else {
result = String.valueOf(object);
}
return result;
}
});
}
public static Object fromXmlWithoutAttributes(final String xml) {
return fromXmlWithElementMapper(xml, new BiFunction<Object, Set<String>, String>() {
public String apply(Object object, Set<String> namespaces) {
return String.valueOf(object).startsWith("-") ? null : String.valueOf(object);
}
});
}
public static Object fromXmlWithoutNamespacesAndAttributes(final String xml) {
return fromXmlWithElementMapper(xml, new BiFunction<Object, Set<String>, String>() {
public String apply(Object object, Set<String> namespaces) {
final String localString = String.valueOf(object);
final String result;
if (localString.startsWith("-")) {
result = null;
} else if (namespaces.contains(localString
.substring(0, Math.max(0, localString.indexOf(':'))))) {
result = localString.substring(Math.max(0, localString.indexOf(':') + 1));
} else {
result = String.valueOf(object);
}
return result;
}
});
}
@SuppressWarnings("unchecked")
public static String formatXml(String xml, XmlStringBuilder.Step identStep) {
Object result = fromXml(xml);
if (result instanceof Map) {
return toXml((Map) result, identStep);
}
return toXml((List) result, identStep);
}
public static String formatXml(String xml) {
return formatXml(xml, XmlStringBuilder.Step.THREE_SPACES);
}
} |
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package com.google.sps.data;
import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.cloud.language.v1.AnalyzeEntitiesRequest;
import com.google.cloud.language.v1.AnalyzeEntitiesResponse;
import com.google.cloud.language.v1.ClassificationCategory;
import com.google.cloud.language.v1.ClassifyTextRequest;
import com.google.cloud.language.v1.ClassifyTextResponse;
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.Document.Type;
import com.google.cloud.language.v1.EncodingType;
import com.google.cloud.language.v1.Entity;
import com.google.cloud.language.v1.EntityMention;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.LanguageServiceSettings;
import com.google.cloud.language.v1.Sentiment;
import com.google.cloud.language.v1.Token;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* This class creates objects that analyse text by
* extracting the categories, the mood, the events.
* The scope is to get a final set of the key words
* from the text.
**/
public final class TextAnalyser {
private final String message;
private static final double EPSILON = 0.00001;
public TextAnalyser(String message) {
this.message = message.toLowerCase();
}
public final LanguageServiceSettings getSettings() throws IOException {
HeaderProvider headerProvider =
FixedHeaderProvider.create("X-Goog-User-Project","google.com:gpostcard");
return LanguageServiceSettings.newBuilder()
.setHeaderProvider(headerProvider)
.build();
}
public float getSentimentScore() throws IOException {
try (LanguageServiceClient languageService = LanguageServiceClient.create(getSettings())) {
Document doc =
Document.newBuilder().setContent(message).setType(Document.Type.PLAIN_TEXT).build();
Sentiment sentiment = languageService.analyzeSentiment(doc).getDocumentSentiment();
return sentiment.getScore();
}
}
public String getMood() throws IOException {
float score = getSentimentScore();
if (Math.abs(score - 1) < EPSILON) {
return "very happy";
}
if (Math.abs(score + 1) < EPSILON) {
return "so pessimistic";
}
/**
* From (-1, 1) the words are displayed on the x axis based on the sentiment score like this:
*
* pessimistic (-0.9), fatigued (-0.8), bored, depressed, sad, upset, stressed, nervous, tense (-0.1),
* neutral(0.0), calm (0.1), relaxed, serene, contented, joyful, happy, delighted, excited, thrilled (0.9)
*
* If the score is >= 0 then the mood is at position (int) (score * 10) => first 10 moods are ordered
* based on the sentiment score of the text from 0.0 to 0.9 (0.1 incrementation)
*
* If the score is negative, return the mood at position (int) (score * 10) * (-1) + 9 => next 9 moods are ordered
* based on the sentiment score of the text from -0.1 to -0.9 (-0.1 incrementation)
**/
int position = 0;
String[] moods = new String[] {"neutral", "calm", "relaxed", "serene", "contented",
"joyful", "happy", "delighted", "excited", "happy",
"tense", "nervous", "stressed", "upset", "sad",
"depressed", "bored", "fatigued", "pessimistic"};
assert moods.length == 19 : "There can only be 19 moods.";
position = (int) (score * 10);
if (position < 0) {
position = position * (-1) + 9;
}
return moods[position];
}
private ClassifyTextResponse classify() throws InvalidArgumentException, IOException {
try (LanguageServiceClient language = LanguageServiceClient.create(getSettings())) {
Document document =
Document.newBuilder().setContent(message).setType(Type.PLAIN_TEXT).build();
ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(document).build();
return language.classifyText(request);
}
}
// list of all the categories that text is about
public Set<String> getCategories() throws IOException {
try {
Set<String> categories = new LinkedHashSet<String>();
for (ClassificationCategory category : classify().getCategoriesList()) {
String[] listCategories = category.getName().split("/");
categories.add(listCategories[listCategories.length - 1].toLowerCase());
}
return categories;
} catch (InvalidArgumentException e) {
e.printStackTrace();
return Collections.emptySet();
}
}
public Set<String> getEvents() {
Set<String> events = new LinkedHashSet<String>();
String[] allEvents = new String[] {"wedding", "travel", "promotion", "graduation",
"funeral", "party"};
for (int i = 0; i < allEvents.length; i++) {
if (message.indexOf(allEvents[i]) != -1) {
events.add(allEvents[i]);
}
}
return events;
}
public Set<String> getGreetings() {
Set<String> greetings = new LinkedHashSet<String>();
String[] allGreetings = new String[] {"good morning", "welcome", "good evening",
"good night", "good afternoon", "hello", "hey",
"happy birthday", "love you"};
for (int i = 0; i < allGreetings.length; i++) {
if (message.indexOf(allGreetings[i]) != -1) {
greetings.add(allGreetings[i]);
}
}
return greetings;
}
/** Identifies entities in the string */
private AnalyzeEntitiesResponse analyzeEntitiesText() throws IOException {
try (LanguageServiceClient language = LanguageServiceClient.create(getSettings())) {
Document doc = Document.newBuilder().setContent(message).setType(Type.PLAIN_TEXT).build();
AnalyzeEntitiesRequest request =
AnalyzeEntitiesRequest.newBuilder()
.setDocument(doc)
.setEncodingType(EncodingType.UTF16)
.build();
return language.analyzeEntities(request);
}
}
public Set<String> getEntities() throws IOException {
AnalyzeEntitiesResponse response = analyzeEntitiesText();
Set<String> entities = new LinkedHashSet<String>();
for (Entity entity : response.getEntitiesList()) {
entities.add(entity.getName());
}
return entities;
}
public boolean isInjection() {
if (message.indexOf("<script>") != -1 || message.indexOf("</script>") != -1 ||
message.indexOf("<html>") != -1 || message.indexOf("</html>") != -1) {
return true;
}
return false;
}
// Put all the key words together
// Use a LinkedHashSet to remove duplicates but maintain order
public Set<String> getKeyWords() {
try {
Set<String> keyWords = new LinkedHashSet<String>();
keyWords.addAll(getGreetings());
keyWords.addAll(getEvents());
keyWords.addAll(getEntities());
keyWords.addAll(getCategories());
keyWords.add(getMood());
return keyWords;
} catch (IOException e) {
// No key words
System.err.println("There are no key words.");
e.printStackTrace();
return Collections.emptySet();
}
}
public Set<String[]> getSetsOfKeyWords() {
Set< String[] > setsOfKeyWords = new LinkedHashSet<>();
List<String> keyWords = new ArrayList<String>(getKeyWords());
// Only returns one key word when only a sentiment is found
if (keyWords.size() == 1) {
setsOfKeyWords.add(new String[] {keyWords.get(0)});
return setsOfKeyWords;
}
for (int i = 0; i < keyWords.size(); i++) {
for (int j = i + 1; j < keyWords.size(); j++) {
setsOfKeyWords.add(new String[] {keyWords.get(i), keyWords.get(j)});
}
}
return setsOfKeyWords;
}
} |
package com.graphicsengine.sprite;
import com.nucleus.vecmath.VecMath;
import com.nucleus.vecmath.Vector2D;
/**
* Base sprite class, a sprite is a 2D geometry object
* Has data needed for movement, animation and graphics - increase size of data storage and use together
* with logic. This is to avoid a very large number of Sprite subclasses for logic.
*
* @author Richard Sahlin
*
*/
public abstract class Sprite {
public interface Logic {
/**
* Do the processing of the sprite, this shall be called at intervals to do the logic processing.
* The sprite data containing data is decoupled from the behavior
*
* @param sprite The sprite to perform behavior for.
* @param deltaTime Time in millis since last call.
*/
public void process(Sprite sprite, float deltaTime);
/**
* Returns the name of the logic, ie the name of the implementing logic class.
* This name is the same for all logic object of the same class, it is not instance name.
* This shall be the same name that was used when the sprite logic was resolved.
*
* @return The name of the implementing logic class
*/
public String getLogicId();
}
public final static String INVALID_DATACOUNT_ERROR = "Invalid datacount";
/**
* Store the data used by subclasses into this class to prepare for rendering.
* For some implementations this may do nothing, others may need to copy data from this class.
*/
public abstract void prepare();
/**
* Index to x position.
*/
public final static int X_POS = 0;
/**
* Index to y position.
*/
public final static int Y_POS = 1;
/**
* Index to z position.
*/
public final static int Z_POS = 2;
public final static int MOVE_VECTOR_X = 3;
public final static int MOVE_VECTOR_Y = 4;
public final static int MOVE_VECTOR_Z = 5;
public final static int FRAME = 6;
public final static int ROTATION = 7; // z axis rotation angle
/**
* Number of float data values reserved for sprite, first free index is SPRITE_FLOAT_COUNT
*/
public final static int SPRITE_FLOAT_COUNT = ROTATION + 1;
/**
* The sprite logic implementation
*/
public Logic logic;
/**
* All sprites can move using a vector
*/
public Vector2D moveVector = new Vector2D();
public float[] floatData;
public int[] intData;
public final static int MIN_FLOAT_COUNT = 16;
public final static int MIN_INT_COUNT = 8;
/**
* Creates a new sprite with storage for MIN_FLOAT_COUNT floats and MIN_INT_COUNT ints
*/
public Sprite() {
createArrays(MIN_FLOAT_COUNT, MIN_INT_COUNT);
}
/**
* Creates a new sprite with storage for the specified number of float and ints.
*
* @param floatCount
* @param intCount
*/
public Sprite(int floatCount, int intCount) {
createArrays(floatCount, intCount);
}
private void createArrays(int floatCount, int intCount) {
if (floatCount < MIN_FLOAT_COUNT || intCount < MIN_INT_COUNT) {
throw new IllegalArgumentException(INVALID_DATACOUNT_ERROR);
}
floatData = new float[floatCount];
intData = new int[intCount];
}
/**
* Applies movement and gravity to position, then prepare() is called to let subclasses update
*
* @param deltaTime
*/
public void move(float deltaTime) {
floatData[X_POS] += deltaTime * moveVector.vector[VecMath.X] * moveVector.vector[Vector2D.MAGNITUDE] +
floatData[MOVE_VECTOR_X] * deltaTime;
floatData[Y_POS] += deltaTime * moveVector.vector[VecMath.Y] * moveVector.vector[Vector2D.MAGNITUDE] +
floatData[MOVE_VECTOR_Y] * deltaTime;
}
/**
* Sets the x, y position and frame of this sprite.
*
* @param x
* @param y
*/
public void setPosition(float x, float y) {
floatData[X_POS] = x;
floatData[Y_POS] = y;
}
public void setFrame(int frame) {
floatData[FRAME] = frame;
}
public void setRotation(float rotation) {
floatData[ROTATION] = rotation;
}
/**
* Sets the movement vector for x, y and z axis. Use this to for instance clear the current movement, or to change
* movement / direction
*
* @param x X axis movement
* @param y Y axis movement
* @paran z Z axis movement
*/
public void setMoveVector(float x, float y, float z) {
floatData[MOVE_VECTOR_X] = x;
floatData[MOVE_VECTOR_Y] = y;
floatData[MOVE_VECTOR_Z] = z;
}
/**
* Updates the movement according to the specified acceleration (x and y axis) and time
*
* @param x Acceleration on x axis
* @param y Acceleration on y axis
* @param deltaTime Time since last time movement was updated, ie elapsed time.
*/
public void accelerate(float x, float y, float deltaTime) {
floatData[MOVE_VECTOR_X] += x * deltaTime;
floatData[MOVE_VECTOR_Y] += y * deltaTime;
}
} |
package com.hearthsim.card.minion;
import com.hearthsim.card.*;
import com.hearthsim.event.attack.AttackAction;
import com.hearthsim.event.effect.EffectCharacter;
import com.hearthsim.event.effect.EffectCharacterSummon;
import com.hearthsim.event.effect.EffectOnResolveTargetable;
import com.hearthsim.event.filter.FilterCharacter;
import com.hearthsim.event.filter.FilterCharacterSummon;
import com.hearthsim.exception.HSException;
import com.hearthsim.exception.HSInvalidPlayerIndexException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.HearthAction;
import com.hearthsim.util.HearthAction.Verb;
import com.hearthsim.util.factory.BoardStateFactoryBase;
import com.hearthsim.util.tree.HearthTreeNode;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
public class Minion extends Card implements EffectOnResolveTargetable<Card>, CardEndTurnInterface, CardStartTurnInterface {
private static final Logger log = LoggerFactory.getLogger(Card.class);
public static enum MinionTribe {
NONE,
BEAST,
MECH,
MURLOC,
PIRATE,
DEMON,
DRAGON,
TOTEM
}
public static MinionTribe StringToMinionTribe(String race) {
race = race == null ? "" : race.toLowerCase();
switch (race) {
case "beast":
return MinionTribe.BEAST;
case "mech":
return MinionTribe.MECH;
case "murloc":
return MinionTribe.MURLOC;
case "pirate":
return MinionTribe.PIRATE;
case "demon":
return MinionTribe.DEMON;
case "dragon":
return MinionTribe.DRAGON;
case "totem":
return MinionTribe.TOTEM;
default:
return MinionTribe.NONE;
}
}
private boolean taunt_;
private boolean divineShield_;
protected boolean windFury_;
private boolean charge_;
private boolean immune_ = false; // Ignores damage
protected boolean hasAttacked_;
protected boolean hasWindFuryAttacked_;
private boolean frozen_;
protected boolean silenced_;
private boolean stealthedUntilRevealed;
private boolean stealthedUntilNextTurn = false;
protected boolean heroTargetable_ = true;
protected byte health_;
protected byte maxHealth_;
private byte auraHealth_;
protected byte attack_;
private byte extraAttackUntilTurnEnd_;
private byte auraAttack_;
private boolean destroyOnTurnStart_;
private boolean destroyOnTurnEnd_;
protected byte spellDamage_;
protected boolean cantAttack;
public Minion() {
super();
}
@Override
protected void initFromImplementedCard(ImplementedCardList.ImplementedCard implementedCard) {
super.initFromImplementedCard(implementedCard);
if (implementedCard != null) {
// only 'Minion' class is not implemented
this.attack_ = implementedCard.attack_ > 0 ? (byte) implementedCard.attack_ : 0;
this.health_ = (byte) implementedCard.health_;
this.maxHealth_ = health_;
this.taunt_ = implementedCard.taunt_;
this.divineShield_ = implementedCard.divineShield_;
this.windFury_ = implementedCard.windfury_;
this.charge_ = implementedCard.charge_;
this.stealthedUntilRevealed = implementedCard.stealth_;
this.spellDamage_ = (byte) implementedCard.spellDamage;
this.cantAttack = implementedCard.cantAttack;
}
}
public boolean getTaunt() {
return taunt_;
}
public void setTaunt(boolean taunt) {
taunt_ = taunt;
}
public byte getHealth() {
return health_;
}
public void setHealth(byte health) {
health_ = health;
}
public final void addHealth(byte value) {
this.setHealth((byte) (this.getHealth() + value));
}
public byte getMaxHealth() {
return maxHealth_;
}
public void setMaxHealth(byte health) {
maxHealth_ = health;
}
public final void addMaxHealth(byte value) {
this.setMaxHealth((byte) (this.getMaxHealth() + value));
}
public byte getBaseHealth() {
if (this.implementedCard == null) {
return this.getMaxHealth();
}
return (byte) this.implementedCard.health_;
}
public byte getAttack() {
return attack_;
}
public void setAttack(byte attack) {
attack_ = attack;
}
public void addAttack(byte value) {
attack_ += value;
}
public byte getBaseAttack() {
if (this.implementedCard == null) {
return this.attack_;
}
return (byte) this.implementedCard.attack_;
}
public boolean getDivineShield() {
return divineShield_;
}
public void setDivineShield(boolean divineShield) {
divineShield_ = divineShield;
}
public boolean canAttack() {
return !this.hasAttacked_ && this.getTotalAttack() > 0 && !this.frozen_ && !cantAttack;
}
public void hasAttacked(boolean hasAttacked) {
hasAttacked_ = hasAttacked;
}
public boolean hasWindFuryAttacked() {
return hasWindFuryAttacked_;
}
public void hasWindFuryAttacked(boolean hasAttacked) {
hasWindFuryAttacked_ = hasAttacked;
}
public boolean getCharge() {
return charge_;
}
public void setCharge(boolean value) {
charge_ = value;
}
public boolean getFrozen() {
return frozen_;
}
public void setFrozen(boolean value) {
frozen_ = value;
}
public boolean getWindfury() {
return windFury_;
}
public void setWindfury(boolean value) {
windFury_ = value;
if (hasAttacked_) {
hasAttacked_ = false;
hasWindFuryAttacked_ = true;
}
}
public void addExtraAttackUntilTurnEnd(byte value) {
extraAttackUntilTurnEnd_ += value;
}
public byte getExtraAttackUntilTurnEnd() {
return extraAttackUntilTurnEnd_;
}
public void setExtraAttackUntilTurnEnd(byte value) {
extraAttackUntilTurnEnd_ = value;
}
public boolean getDestroyOnTurnStart() {
return destroyOnTurnStart_;
}
public void setDestroyOnTurnStart(boolean value) {
destroyOnTurnStart_ = value;
}
public boolean getDestroyOnTurnEnd() {
return destroyOnTurnEnd_;
}
public void setDestroyOnTurnEnd(boolean value) {
destroyOnTurnEnd_ = value;
}
public boolean isSilenced() {
return silenced_;
}
protected void setSilenced(boolean silenced) {
silenced_ = silenced;
}
public byte getAuraAttack() {
return auraAttack_;
}
public void setAuraAttack(byte value) {
auraAttack_ = value;
}
public byte getAuraHealth() {
return auraHealth_;
}
public void setAuraHealth(byte value) {
auraHealth_ = value;
}
public byte getTotalAttack() {
return (byte) (attack_ + auraAttack_ + extraAttackUntilTurnEnd_);
}
public byte getTotalHealth() {
return (byte) (health_ + auraHealth_);
}
public byte getTotalMaxHealth() {
return (byte) (maxHealth_ + auraHealth_);
}
public MinionTribe getTribe() {
if (this.implementedCard == null) {
return MinionTribe.NONE;
}
return Minion.StringToMinionTribe(this.implementedCard.race);
}
public void addAuraHealth(byte value) {
auraHealth_ += value;
}
public void removeAuraHealth(byte value) {
health_ += value;
if (health_ > maxHealth_)
health_ = maxHealth_;
auraHealth_ -= value;
}
public boolean isStealthed() {
return stealthedUntilRevealed || stealthedUntilNextTurn;
}
public boolean getStealthedUntilRevealed() {
return this.stealthedUntilRevealed;
}
public void setStealthedUntilRevealed(boolean value) {
stealthedUntilRevealed = value;
}
public boolean getStealthedUntilNextTurn() {
return this.stealthedUntilNextTurn;
}
public void setStealthedUntilNextTurn(boolean stealthedUntilNextTurn) {
this.stealthedUntilNextTurn = stealthedUntilNextTurn;
}
public boolean getImmune() {
return immune_;
}
public void setImmune(boolean immune) {
immune_ = immune;
}
// This is a flag to tell the BoardState that it can't cheat on the placement of this minion
public boolean getPlacementImportant() {
return false;
}
public boolean isHeroTargetable() {
return heroTargetable_;
}
public void setHeroTargetable(boolean value) {
heroTargetable_ = value;
}
public byte getSpellDamage() {
return spellDamage_;
}
public void setSpellDamage(byte value) {
spellDamage_ = value;
}
public void addSpellDamage(byte value) {
spellDamage_ += value;
}
public void subtractSpellDamage(byte value) {
spellDamage_ -= value;
}
public boolean isAlive() {
return getTotalHealth() > 0;
}
public boolean isHero() {
return false;
}
/**
* Called at the start of the turn
* <p>
* This function is called at the start of the turn. Any derived class must override it to implement whatever "start of the turn" effect the card has.
*/
@Override
public HearthTreeNode startTurn(PlayerSide thisMinionPlayerIndex, HearthTreeNode boardModel) throws HSException {
if (destroyOnTurnStart_) {
// toRet = this.destroyAndNotify(thisMinionPlayerIndex, toRet, deckPlayer0, deckPlayer1);
this.setHealth((byte) -99);
}
if (stealthedUntilNextTurn && thisMinionPlayerIndex == PlayerSide.CURRENT_PLAYER)
this.setStealthedUntilNextTurn(false);
return boardModel;
}
/**
* End the turn and resets the card state
* <p>
* This function is called at the end of the turn. Any derived class must override it and remove any temporary buffs that it has.
* <p>
* This is not the most efficient implementation... luckily, endTurn only happens once per turn
*/
@Override
public HearthTreeNode endTurn(PlayerSide thisMinionPlayerIndex, HearthTreeNode boardModel) throws HSException {
extraAttackUntilTurnEnd_ = 0;
if (destroyOnTurnEnd_) {
// toRet = this.destroyAndNotify(thisMinionPlayerIndex, toRet, deckPlayer0, deckPlayer1);
this.setHealth((byte) -99);
}
return boardModel;
}
/**
* Called when this minion takes damage
* <p>
* Always use this function to take damage... it properly notifies all others of its damage and possibly of its death
*
* @param damage The amount of damage to take
* @param attackPlayerSide The player index of the attacker. This is needed to do things like +spell damage.
* @param thisPlayerSide
* @param boardState
* @param isSpellDamage True if this is a spell damage
* @param handleMinionDeath Set this to True if you want the death event to trigger when (if) the minion dies from this damage. Setting this flag to True will also trigger deathrattle immediately.
* @throws HSInvalidPlayerIndexException
*/
public HearthTreeNode takeDamageAndNotify(byte damage, PlayerSide attackPlayerSide, PlayerSide thisPlayerSide, HearthTreeNode boardState, boolean isSpellDamage, boolean handleMinionDeath) {
byte damageDealt = this.takeDamage(damage, attackPlayerSide, thisPlayerSide, boardState.data_, isSpellDamage);
if (damageDealt > 0) {
return boardState.notifyMinionDamaged(thisPlayerSide, this);
}
return boardState;
}
public byte takeDamage(byte damage, PlayerSide originSide, PlayerSide thisPlayerSide, BoardModel board, boolean isSpellDamage) {
if (this.divineShield_) {
if (damage > 0)
this.divineShield_ = false;
return 0;
}
if (this.immune_) {
return 0;
}
byte totalDamage = damage;
if (isSpellDamage) {
totalDamage += board.modelForSide(originSide).getSpellDamage();
}
this.health_ = (byte) (this.health_ - totalDamage);
return totalDamage;
}
/**
* Called when this minion dies (destroyAndNotify)
* <p>
* Always use this function to "kill" minions
*
* @param thisPlayerSide
* @param boardState
* @throws HSInvalidPlayerIndexException
*/
public HearthTreeNode destroyAndNotify(PlayerSide thisPlayerSide, HearthTreeNode boardState) {
health_ = 0;
HearthTreeNode toRet = boardState;
// perform the deathrattle action if there is one
if (deathrattleAction_ != null) {
toRet = deathrattleAction_.performAction(this, thisPlayerSide, toRet);
}
if (toRet != null)
toRet = toRet.notifyMinionDead(thisPlayerSide, this);
else
return boardState;
return toRet;
}
/**
* Called when this minion is silenced
* <p>
* Always use this function to "silence" minions
*
* @param thisPlayerSide
* @param boardState
* @throws HSInvalidPlayerIndexException
*/
public void silenced(PlayerSide thisPlayerSide, BoardModel boardState) {
spellDamage_ = 0;
divineShield_ = false;
taunt_ = false;
charge_ = false;
frozen_ = false;
windFury_ = false;
deathrattleAction_ = null;
stealthedUntilRevealed = false;
stealthedUntilNextTurn = false;
heroTargetable_ = true;
cantAttack = false;
int damageTaken = this.maxHealth_ - this.health_;
// Reset the attack and health to base
this.attack_ = this.getBaseAttack();
if (this.maxHealth_ > this.getBaseHealth()) {
this.maxHealth_ = this.getBaseHealth();
if (this.health_ > this.maxHealth_) {
this.health_ = this.maxHealth_;
}
} else if (this.maxHealth_ < this.getBaseHealth()) {
this.maxHealth_ = this.getBaseHealth();
this.health_ = (byte) (this.maxHealth_ - damageTaken);
}
//Ask the board to clear this minion's aura
boardState.removeAuraOfMinion(thisPlayerSide, this);
//Set the silenced flag at the end
silenced_ = true;
}
/**
* Called when this minion is healed
* <p>
* Always use this function to heal minions
* @param healAmount The amount of healing to take
* @param thisPlayerSide
* @param boardState
*/
public HearthTreeNode takeHealAndNotify(byte healAmount, PlayerSide thisPlayerSide, HearthTreeNode boardState) {
byte actual = this.takeHeal(healAmount, thisPlayerSide, boardState.data_);
if (actual > 0) {
return boardState.notifyMinionHealed(thisPlayerSide, this);
}
return boardState;
}
public byte takeHeal(byte healAmount, PlayerSide thisPlayerSide, BoardModel board) {
int missing = this.maxHealth_ - this.health_;
int actual = healAmount > missing ? missing : healAmount;
this.health_ += actual;
return (byte) actual;
}
@Override
public boolean canBeUsedOn(PlayerSide playerSide, Minion minion, BoardModel boardModel) {
if (!super.canBeUsedOn(playerSide, minion, boardModel)) {
return false;
}
return playerSide != PlayerSide.WAITING_PLAYER && !hasBeenUsed;
}
/**
* Use a targetable battlecry. This will add battlecry nodes to boardState as children.
*
* @param side
* @param targetCharacterIndex
* @param boardState
* @return
* @throws HSException
*/
public HearthTreeNode useTargetableBattlecry(PlayerSide side, CharacterIndex targetCharacterIndex, HearthTreeNode boardState) {
if (this instanceof MinionBattlecryInterface) {
boardState.data_.modelForSide(side);
EffectCharacter<Minion> battlecryEffect = ((MinionBattlecryInterface)this).getBattlecryEffect();
boardState = battlecryEffect.applyEffect(PlayerSide.CURRENT_PLAYER, this, side, targetCharacterIndex, boardState);
if (boardState != null) {
CharacterIndex originCharacterIndex = boardState.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getIndexForCharacter(this);
boardState = BoardStateFactoryBase.handleDeadMinions(boardState);
boardState.setAction(new HearthAction(Verb.TARGETABLE_BATTLECRY, PlayerSide.CURRENT_PLAYER, originCharacterIndex.getInt(), side, targetCharacterIndex));
}
}
return boardState;
}
/**
* Use an untargetable battlecry.
*
* @param minionPlacementIndex
* @param boardState
* @return
* @throws HSException
*/
@Deprecated
public HearthTreeNode useUntargetableBattlecry(CharacterIndex minionPlacementIndex, HearthTreeNode boardState) {
HearthTreeNode toRet = boardState;
if (this instanceof MinionUntargetableBattlecry) {
EffectCharacter<Minion> battlecryEffect = ((MinionUntargetableBattlecry)this).getBattlecryEffect();
toRet = battlecryEffect.applyEffect(PlayerSide.CURRENT_PLAYER, this, PlayerSide.CURRENT_PLAYER, minionPlacementIndex, toRet);
if (toRet != null) {
// Check for dead minions
toRet = BoardStateFactoryBase.handleDeadMinions(toRet);
}
}
return toRet;
}
/**
* Places a minion on the board by using the card in hand
*
* @param side
* @param targetMinion The target minion (can be a Hero). The new minion is always placed to the right of (higher index) the target minion. If the target minion is a hero, then it is placed at the left-most position.
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @return The boardState is manipulated and returned
* @throws HSException
*/
@Override
protected HearthTreeNode use_core(PlayerSide side, Minion targetMinion, HearthTreeNode boardState) throws HSException {
if (hasBeenUsed || side == PlayerSide.WAITING_PLAYER || boardState.data_.modelForSide(side).isBoardFull()) {
return null;
}
HearthTreeNode toRet = boardState;
toRet = super.use_core(side, targetMinion, toRet);
return toRet;
}
@Override
public EffectCharacter getTargetableEffect() {
return new EffectCharacterSummon(this);
}
@Override
public FilterCharacter getTargetableFilter() {
return FilterCharacterSummon.ALL_FRIENDLIES;
}
/**
* Places a minion on the board via a summon effect
* <p>
* This function is meant to be used when summoning minions through means other than a direct card usage.
*
* @param targetSide
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @return The boardState is manipulated and returned
*/
public HearthTreeNode summonMinion(PlayerSide targetSide, CharacterIndex targetMinionIndex, HearthTreeNode boardState, boolean wasPlayed) {
if (boardState.data_.modelForSide(targetSide).isBoardFull())
return null;
HearthTreeNode toRet = boardState;
toRet = this.summonMinion_core(targetSide, targetMinionIndex, toRet);
if (this instanceof MinionBattlecryInterface && wasPlayed) {
MinionBattlecryInterface battlecryOrigin = ((MinionBattlecryInterface) this);
HearthTreeNode child;
Minion origin;
CharacterIndex originCharacterIndex = toRet.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getIndexForCharacter(this);
// Find out if there are going to be more than one target match
int numTargets = 0;
CharacterIndex.CharacterLocation onlyTargetLocation = null;
for (CharacterIndex.CharacterLocation characterLocation : toRet.data_)
if (battlecryOrigin.getBattlecryFilter().targetMatches(PlayerSide.CURRENT_PLAYER, this, characterLocation.getPlayerSide(), characterLocation.getIndex(), toRet.data_)) {
++numTargets;
onlyTargetLocation = characterLocation;
}
if (numTargets > 1) {
ArrayList<HearthTreeNode> children = new ArrayList<>();
for (CharacterIndex.CharacterLocation characterLocation : toRet.data_) {
if (battlecryOrigin.getBattlecryFilter().targetMatches(PlayerSide.CURRENT_PLAYER, this, characterLocation.getPlayerSide(), characterLocation.getIndex(), toRet.data_)) {
child = new HearthTreeNode(toRet.data_.deepCopy());
origin = child.data_.getCharacter(PlayerSide.CURRENT_PLAYER, originCharacterIndex);
child = origin.useTargetableBattlecry(characterLocation.getPlayerSide(), characterLocation.getIndex(), child);
if (child != null) {
children.add(child);
}
}
}
toRet = this.createNodeWithChildren(toRet, children);
} else if (numTargets == 1) {
toRet = this.useTargetableBattlecry(onlyTargetLocation.getPlayerSide(), onlyTargetLocation.getIndex(), toRet);
}
}
if (toRet != null && wasPlayed) {
toRet = toRet.notifyMinionPlayed(targetSide, this);
}
if (toRet != null)
toRet = toRet.notifyMinionSummon(targetSide, this);
return toRet;
}
public HearthTreeNode summonMinion(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState, boolean wasPlayed) {
return this.summonMinion(targetSide, boardState.data_.modelForSide(targetSide).getIndexForCharacter(targetMinion), boardState, wasPlayed);
}
public HearthTreeNode summonMinionAtEnd(PlayerSide targetSide, HearthTreeNode boardState, boolean wasPlayed) {
PlayerModel player = boardState.data_.modelForSide(targetSide);
return this.summonMinion(targetSide, CharacterIndex.fromInteger(player.getNumMinions()), boardState, wasPlayed);
}
/**
*
* Places a minion on the board via a summon effect
*
* This function is meant to be used when summoning minions through means other than a direct card usage.
*
* @param targetSide
* @param targetIndex The target character (can be a Hero). The new minion is always placed to the right of (higher index) the target minion. If the target minion is a hero, then it is placed at the left-most position.
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @return The boardState is manipulated and returned
* @throws HSException
*/
protected HearthTreeNode summonMinion_core(PlayerSide targetSide, CharacterIndex targetIndex, HearthTreeNode boardState) {
// The minion summon placement target might have died during the previous chain of events.
// So, we need to check to see if the target position is still valid. If it is not, we
// will place the target on the right most position.
if (boardState.data_.modelForSide(targetSide).getNumMinions() < targetIndex.getInt()) {
targetIndex = CharacterIndex.fromInteger(boardState.data_.modelForSide(targetSide).getNumMinions());
}
boardState.data_.placeMinion(targetSide, this, targetIndex);
if (!charge_) {
hasAttacked_ = true;
}
hasBeenUsed = true;
return boardState;
}
/**
*
* Attack with the minion
*
*
*
* @param targetMinionPlayerSide
* @param targetMinion The target minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @return The boardState is manipulated and returned
*/
public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState) throws HSException {
// can't attack a stealthed target
if (targetMinion.isStealthed())
return null;
if (!this.canAttack()) {
return null;
}
if (targetMinionPlayerSide == PlayerSide.CURRENT_PLAYER) {
return null;
}
PlayerModel currentPlayer = boardState.data_.getCurrentPlayer();
PlayerModel targetPlayer = boardState.data_.modelForSide(targetMinionPlayerSide);
// Notify all that an attack is beginning
HearthTreeNode toRet;
CharacterIndex attackerIndex = currentPlayer.getIndexForCharacter(this);
CharacterIndex targetIndex = targetPlayer.getIndexForCharacter(targetMinion);
// Do the actual attack
toRet = this.attack_core(targetMinionPlayerSide, targetMinion, boardState);
// check for and remove dead minions
if (toRet != null) {
toRet.setAction(new HearthAction(Verb.ATTACK, PlayerSide.CURRENT_PLAYER, attackerIndex.getInt(),
targetMinionPlayerSide, targetIndex));
toRet = BoardStateFactoryBase.handleDeadMinions(toRet);
}
// Attacking means you lose stealth
if (toRet != null) {
this.stealthedUntilRevealed = false;
this.stealthedUntilNextTurn = false;
}
return toRet;
}
public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, CharacterIndex targetCharacterIndex, HearthTreeNode boardState) throws HSException {
Minion targetCharacter = boardState.data_.modelForSide(targetMinionPlayerSide).getCharacter(targetCharacterIndex);
return this.attack(targetMinionPlayerSide, targetCharacter, boardState);
}
/**
*
* Attack with the minion
*
*
*
* @param targetMinionPlayerSide
* @param targetMinion The target minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @return The boardState is manipulated and returned
*/
protected HearthTreeNode attack_core(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState) throws HSException {
HearthTreeNode toRet = boardState;
byte origAttack = targetMinion.getTotalAttack();
toRet = targetMinion.takeDamageAndNotify(this.getTotalAttack(), PlayerSide.CURRENT_PLAYER, targetMinionPlayerSide, toRet, false, false);
toRet = this.takeDamageAndNotify(origAttack, targetMinionPlayerSide, PlayerSide.CURRENT_PLAYER, toRet, false, false);
if (windFury_ && !hasWindFuryAttacked_)
hasWindFuryAttacked_ = true;
else
hasAttacked_ = true;
return toRet;
}
@Override
public JSONObject toJSON() {
JSONObject json = super.toJSON();
json.put("attack", attack_);
json.put("baseAttack", this.getBaseAttack());
if (health_ != maxHealth_) json.put("health", health_);
json.put("baseHealth", this.getBaseHealth());
json.put("maxHealth", maxHealth_);
if (taunt_) json.put("taunt", taunt_);
if (divineShield_) json.put("divineShield", divineShield_);
if (windFury_) json.put("windFury", windFury_);
if (charge_) json.put("charge", charge_);
if (frozen_) json.put("frozen", frozen_);
if (silenced_) json.put("silenced", silenced_);
if (hasAttacked_) json.put("hasAttacked", hasAttacked_);
if (spellDamage_ != 0) json.put("spellDamage", spellDamage_);
if (destroyOnTurnStart_) json.put("destroyOnTurnStart", true);
return json;
}
/**
* Deep copy of the object
*
* Note: the event actions are not actually deep copied.
*/
@Override
public Card deepCopy() {
Minion minion = (Minion)super.deepCopy();
minion.attack_ = attack_;
minion.health_ = health_;
minion.extraAttackUntilTurnEnd_ = extraAttackUntilTurnEnd_;
minion.auraAttack_ = auraAttack_;
minion.maxHealth_ = maxHealth_;
minion.auraHealth_ = auraHealth_;
minion.spellDamage_ = spellDamage_;
minion.taunt_ = taunt_;
minion.divineShield_ = divineShield_;
minion.windFury_ = windFury_;
minion.charge_ = charge_;
minion.hasAttacked_ = hasAttacked_;
minion.hasWindFuryAttacked_ = hasWindFuryAttacked_;
minion.frozen_ = frozen_;
minion.silenced_ = silenced_;
minion.stealthedUntilRevealed = stealthedUntilRevealed;
minion.stealthedUntilNextTurn = stealthedUntilNextTurn;
minion.heroTargetable_ = heroTargetable_;
minion.destroyOnTurnStart_ = destroyOnTurnStart_;
minion.destroyOnTurnEnd_ = destroyOnTurnEnd_;
minion.deathrattleAction_ = deathrattleAction_;
minion.inHand = inHand;
minion.hasBeenUsed = hasBeenUsed;
// TODO: continue here.
return minion;
}
@Override
public boolean equals(Object other) {
if (!super.equals(other)) {
return false;
}
Minion otherMinion = (Minion)other;
if (health_ != otherMinion.health_)
return false;
if (maxHealth_ != otherMinion.maxHealth_)
return false;
if (auraHealth_ != otherMinion.auraHealth_)
return false;
if (attack_ != otherMinion.attack_)
return false;
if (extraAttackUntilTurnEnd_ != otherMinion.extraAttackUntilTurnEnd_)
return false;
if (auraAttack_ != otherMinion.auraAttack_)
return false;
if (taunt_ != otherMinion.taunt_)
return false;
if (divineShield_ != otherMinion.divineShield_)
return false;
if (windFury_ != otherMinion.windFury_)
return false;
if (charge_ != otherMinion.charge_)
return false;
if (stealthedUntilRevealed != otherMinion.stealthedUntilRevealed)
return false;
if (stealthedUntilNextTurn != otherMinion.stealthedUntilNextTurn)
return false;
if (hasAttacked_ != otherMinion.hasAttacked_)
return false;
if (heroTargetable_ != otherMinion.heroTargetable_)
return false;
if (hasWindFuryAttacked_ != otherMinion.hasWindFuryAttacked_)
return false;
if (frozen_ != otherMinion.frozen_)
return false;
if (silenced_ != otherMinion.silenced_)
return false;
if (destroyOnTurnStart_ != otherMinion.destroyOnTurnStart_)
return false;
if (destroyOnTurnEnd_ != otherMinion.destroyOnTurnEnd_)
return false;
if (spellDamage_ != otherMinion.spellDamage_)
return false;
// This is checked for reference equality
if (deathrattleAction_ == null && ((Minion)other).deathrattleAction_ != null)
return false;
if (deathrattleAction_ != null && !deathrattleAction_.equals(((Minion)other).deathrattleAction_))
return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (taunt_ ? 1 : 0);
result = 31 * result + (divineShield_ ? 1 : 0);
result = 31 * result + (windFury_ ? 1 : 0);
result = 31 * result + (charge_ ? 1 : 0);
result = 31 * result + (hasAttacked_ ? 1 : 0);
result = 31 * result + (hasWindFuryAttacked_ ? 1 : 0);
result = 31 * result + (frozen_ ? 1 : 0);
result = 31 * result + (silenced_ ? 1 : 0);
result = 31 * result + (stealthedUntilRevealed ? 1 : 0);
result = 31 * result + (stealthedUntilNextTurn ? 1 : 0);
result = 31 * result + (heroTargetable_ ? 1 : 0);
result = 31 * result + health_;
result = 31 * result + maxHealth_;
result = 31 * result + this.getBaseHealth();
result = 31 * result + auraHealth_;
result = 31 * result + attack_;
result = 31 * result + this.getBaseAttack();
result = 31 * result + extraAttackUntilTurnEnd_;
result = 31 * result + auraAttack_;
result = 31 * result + (destroyOnTurnStart_ ? 1 : 0);
result = 31 * result + (destroyOnTurnEnd_ ? 1 : 0);
result = 31 * result + spellDamage_;
result = 31 * result + (deathrattleAction_ != null ? deathrattleAction_.hashCode() : 0);
result = 31 * result + (this.getPlacementImportant() ? 1 : 0);
return result;
}
@Deprecated
public Minion(String name, byte mana, byte attack, byte health, byte baseAttack, byte extraAttackUntilTurnEnd,
byte auraAttack, byte baseHealth, byte maxHealth, byte auraHealth, byte spellDamage, boolean taunt,
boolean divineShield, boolean windFury, boolean charge, boolean hasAttacked, boolean hasWindFuryAttacked,
boolean frozen, boolean silenced, boolean stealthed, boolean heroTargetable, boolean summoned,
boolean transformed, boolean destroyOnTurnStart, boolean destroyOnTurnEnd, AttackAction attackAction,
boolean isInHand, boolean hasBeenUsed) {
super(name, mana, hasBeenUsed, isInHand, (byte) 0);
attack_ = attack;
health_ = health;
taunt_ = taunt;
divineShield_ = divineShield;
windFury_ = windFury;
charge_ = charge;
hasAttacked_ = hasAttacked;
extraAttackUntilTurnEnd_ = extraAttackUntilTurnEnd;
hasWindFuryAttacked_ = hasWindFuryAttacked;
frozen_ = frozen;
silenced_ = silenced;
maxHealth_ = maxHealth;
destroyOnTurnStart_ = destroyOnTurnStart;
destroyOnTurnEnd_ = destroyOnTurnEnd;
auraAttack_ = auraAttack;
auraHealth_ = auraHealth;
spellDamage_ = spellDamage;
stealthedUntilRevealed = stealthed;
heroTargetable_ = heroTargetable;
}
@Deprecated
public boolean hasAttacked() {
return hasAttacked_;
}
@Deprecated
public void silenced(PlayerSide thisPlayerSide, HearthTreeNode boardState) throws HSInvalidPlayerIndexException {
this.silenced(thisPlayerSide, boardState.data_);
}
// Various notifications
@Deprecated
protected HearthTreeNode notifyMinionPlacement(HearthTreeNode boardState, PlayerSide targetSide) throws HSException {
return boardState.notifyMinionPlacement(targetSide, this);
}
} |
package com.jaamsim.Thresholds;
import java.util.ArrayList;
import com.jaamsim.events.ProcessTarget;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.math.Color4d;
import com.jaamsim.units.DimensionlessUnit;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.ColourInput;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.StringInput;
import com.sandwell.JavaSimulation3D.DisplayEntity;
import com.sandwell.JavaSimulation3D.DisplayModelCompat;
public abstract class Threshold extends DisplayEntity {
@Keyword(description = "The colour of the threshold graphic when the present time series value is less than or equal to the MaxOpenLimit and " +
"greater than or equal to the MinOpenLimit.",
example = "Threshold1 OpenColour { green }")
private final ColourInput openColour;
@Keyword(description = "The colour of the threshold graphic when the present time series value is greater than the MaxOpenLimit " +
" or less than the MinOpenLimit.",
example = "Threshold1 ClosedColour { red }")
private final ColourInput closedColour;
@Keyword(description = "A Boolean value. If TRUE, the threshold is displayed when it is open.",
example = "Threshold1 ShowWhenOpen { FALSE }")
private final BooleanInput showWhenOpen;
@Keyword(description = "A Boolean value. If TRUE, the threshold is displayed when it is closed.",
example = "Threshold1 ShowWhenClosed { FALSE }")
private final BooleanInput showWhenClosed;
@Keyword(description = "The string displayed by the Text output when the threshold is open.",
example = "Threshold1 OpenText { 'Open for Weather' }")
private final StringInput openText;
@Keyword(description = "The string displayed by the Text output when the threshold is closed.",
example = "Threshold1 ClosedText { 'Closed for Weather' }")
private final StringInput closedText;
protected final ArrayList<ThresholdUser> userList;
protected boolean closed;
protected double simTimeOfLastUpdate; // Simulation time in seconds of last update
protected double openSimTime; // Number of seconds open
protected double closedSimTime; // Number of seconds closed
{
openColour = new ColourInput( "OpenColour", "Graphics", ColourInput.GREEN );
this.addInput( openColour );
this.addSynonym( openColour, "OpenColor" );
closedColour = new ColourInput( "ClosedColour", "Graphics", ColourInput.RED );
this.addInput( closedColour );
this.addSynonym( closedColour, "ClosedColor" );
showWhenOpen = new BooleanInput("ShowWhenOpen", "Graphics", true);
this.addInput(showWhenOpen);
showWhenClosed = new BooleanInput("ShowWhenClosed", "Graphics", true);
this.addInput(showWhenClosed);
openText = new StringInput("OpenText", "Graphics", "Open");
this.addInput(openText);
closedText = new StringInput("ClosedText", "Graphics", "Closed");
this.addInput(closedText);
}
public Threshold() {
userList = new ArrayList<ThresholdUser>();
}
@Override
public void earlyInit() {
super.earlyInit();
userUpdate.users.clear();
closed = false;
userList.clear();
for (Entity each : Entity.getAll()) {
if (each instanceof ThresholdUser) {
ThresholdUser tu = (ThresholdUser)each;
if (tu.getThresholds().contains(this))
userList.add(tu);
}
}
}
@Override
public void startUp() {
super.startUp();
this.clearStatistics();
this.doOpenClose();
}
public abstract void doOpenClose();
protected static final DoThresholdChanged userUpdate = new DoThresholdChanged();
protected static class DoThresholdChanged extends ProcessTarget {
public final ArrayList<ThresholdUser> users = new ArrayList<ThresholdUser>();
public DoThresholdChanged() {}
@Override
public void process() {
for (ThresholdUser each : users)
each.thresholdChanged();
users.clear();
}
@Override
public String getDescription() {
return "UpdateAllThresholdUsers";
}
}
public boolean isClosed() {
return closed;
}
public abstract double calcClosedTimeFromTime( double startTime );
@Override
public void updateGraphics( double time ) {
super.updateGraphics(time);
// Determine the colour for the square
Color4d col;
if( closed )
col = closedColour.getValue();
else
col = openColour.getValue();
if (closed) {
setTagVisibility(DisplayModelCompat.TAG_CONTENTS, showWhenClosed.getValue());
setTagVisibility(DisplayModelCompat.TAG_OUTLINES, showWhenClosed.getValue());
}
else {
setTagVisibility(DisplayModelCompat.TAG_CONTENTS, showWhenOpen.getValue());
setTagVisibility(DisplayModelCompat.TAG_OUTLINES, showWhenOpen.getValue());
}
setTagColour( DisplayModelCompat.TAG_CONTENTS, col );
setTagColour( DisplayModelCompat.TAG_OUTLINES, ColourInput.BLACK );
}
// Reporting
public void clearStatistics() {
openSimTime = 0.0;
closedSimTime = 0.0;
simTimeOfLastUpdate = getSimTime();
}
public void update() {
if( closed )
closedSimTime += getSimTime() - simTimeOfLastUpdate;
else
openSimTime += getSimTime() - simTimeOfLastUpdate;
simTimeOfLastUpdate = getSimTime();
}
/**
* Prints the header for the statistics
*/
public void printUtilizationHeaderOn( FileEntity anOut ) {
anOut.format( "Name\t" );
anOut.format( "Open\t" );
anOut.format( "Closed\t" );
}
/**
* Print the threshold name and percentage of time open and closed
*/
public void printUtilizationOn( FileEntity anOut ) {
this.update();
double totalSimTime = openSimTime + closedSimTime;
if (totalSimTime == 0.0d)
return;
anOut.format( "%s\t", getName() );
// Print percentage of time open
double fraction = openSimTime/totalSimTime;
anOut.format("%.1f%%\t", fraction * 100.0d);
// Print percentage of time closed
fraction = closedSimTime/totalSimTime;
anOut.format("%.1f%%\t", fraction * 100.0d);
}
@Output(name = "Text",
description = "If open, then return OpenText. If closed, then return ClosedText.",
unitType = DimensionlessUnit.class)
public String getText(double simTime) {
if( closed )
return closedText.getValue();
else
return openText.getValue();
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAnalyticsService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaEntryServerNodeService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduleEventService;
import com.kaltura.client.services.KalturaScheduleResourceService;
import com.kaltura.client.services.KalturaScheduleEventResourceService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:16-10-28");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAnalyticsService analyticsService;
public KalturaAnalyticsService getAnalyticsService() {
if(this.analyticsService == null)
this.analyticsService = new KalturaAnalyticsService(this);
return this.analyticsService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaEntryServerNodeService entryServerNodeService;
public KalturaEntryServerNodeService getEntryServerNodeService() {
if(this.entryServerNodeService == null)
this.entryServerNodeService = new KalturaEntryServerNodeService(this);
return this.entryServerNodeService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduleEventService scheduleEventService;
public KalturaScheduleEventService getScheduleEventService() {
if(this.scheduleEventService == null)
this.scheduleEventService = new KalturaScheduleEventService(this);
return this.scheduleEventService;
}
protected KalturaScheduleResourceService scheduleResourceService;
public KalturaScheduleResourceService getScheduleResourceService() {
if(this.scheduleResourceService == null)
this.scheduleResourceService = new KalturaScheduleResourceService(this);
return this.scheduleResourceService;
}
protected KalturaScheduleEventResourceService scheduleEventResourceService;
public KalturaScheduleEventResourceService getScheduleEventResourceService() {
if(this.scheduleEventResourceService == null)
this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this);
return this.scheduleEventResourceService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAnalyticsService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaEntryServerNodeService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduleEventService;
import com.kaltura.client.services.KalturaScheduleResourceService;
import com.kaltura.client.services.KalturaScheduleEventResourceService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:16-11-11");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAnalyticsService analyticsService;
public KalturaAnalyticsService getAnalyticsService() {
if(this.analyticsService == null)
this.analyticsService = new KalturaAnalyticsService(this);
return this.analyticsService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaEntryServerNodeService entryServerNodeService;
public KalturaEntryServerNodeService getEntryServerNodeService() {
if(this.entryServerNodeService == null)
this.entryServerNodeService = new KalturaEntryServerNodeService(this);
return this.entryServerNodeService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduleEventService scheduleEventService;
public KalturaScheduleEventService getScheduleEventService() {
if(this.scheduleEventService == null)
this.scheduleEventService = new KalturaScheduleEventService(this);
return this.scheduleEventService;
}
protected KalturaScheduleResourceService scheduleResourceService;
public KalturaScheduleResourceService getScheduleResourceService() {
if(this.scheduleResourceService == null)
this.scheduleResourceService = new KalturaScheduleResourceService(this);
return this.scheduleResourceService;
}
protected KalturaScheduleEventResourceService scheduleEventResourceService;
public KalturaScheduleEventResourceService getScheduleEventResourceService() {
if(this.scheduleEventResourceService == null)
this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this);
return this.scheduleEventResourceService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
package org.spine3.server.aggregate;
import com.google.common.base.Optional;
import com.google.protobuf.Message;
import org.spine3.server.BoundedContext;
import static java.lang.String.format;
/**
* A helper class for finding and checking {@code AggregatePartRepository}.
*
* <p>This class is used by {@link AggregateRoot} to find repositories for its parts.
*
* @param <I> the type of the IDs of the repository to find
* @param <S> the type of the state of aggregate parts of managed by the target repository
* @author Alexander Yevsyukov
*/
class AggregatePartRepositoryLookup<I, S extends Message> {
private final BoundedContext boundedContext;
private final Class<I> idClass;
private final Class<S> stateClass;
/**
* Creates the lookup object for finding the repository that
* manages aggregate parts with the passed state class.
*/
static <I, S extends Message> AggregatePartRepositoryLookup<I, S>
createLookup(BoundedContext boundedContext, Class<I> idClass, Class<S> stateClass) {
return new AggregatePartRepositoryLookup<>(boundedContext, idClass, stateClass);
}
private AggregatePartRepositoryLookup(BoundedContext boundedContext,
Class<I> idClass,
Class<S> stateClass) {
this.boundedContext = boundedContext;
this.idClass = idClass;
this.stateClass = stateClass;
}
<A extends AggregatePart<I, S, ?, ?>> AggregatePartRepository<I, A, ?> find() {
final AggregateRepository<?, ?> repo =
checkFound(boundedContext.getAggregateRepository(stateClass));
checkIsAggregatePartRepository(repo);
final AggregatePartRepository<I, A, ?> result =
checkIdClass((AggregatePartRepository<?, ?, ?>) repo);
return result;
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") // as this is the purpose of the method
private AggregateRepository<?, ?>
checkFound(Optional<? extends AggregateRepository<?, ?>> rawRepo) {
if (!rawRepo.isPresent()) {
final String errMsg = format("Unable to find repository for the state class: %s",
stateClass);
throw new IllegalStateException(errMsg);
} else {
return rawRepo.get();
}
}
/**
* Ensures that the passed repository is instance of {@code AggregatePartRepository}.
*
* <p>We check this to make sure that expectations of this {@code AggregateRoot} are supported
* by correct configuration of the {@code BoundedContext}.
*/
private static void checkIsAggregatePartRepository(AggregateRepository<?, ?> repo) {
if (!(repo instanceof AggregatePartRepository)) {
final String errMsg = format("The repository `%s` is not an instance of `%s`",
repo,
AggregatePartRepository.class);
throw new IllegalStateException(errMsg);
}
}
/**
* Ensures the type of the IDs of the passed repository.
*/
private <A extends AggregatePart<I, S, ?, ?>>
AggregatePartRepository<I, A, ?> checkIdClass(AggregatePartRepository<?, ?, ?> repo) {
final Class<?> repoIdClass = repo.getIdClass();
if (!idClass.equals(repoIdClass)) {
final String errMsg = format("The ID class of the aggregate part repository (%s) " +
"does not match the ID class of the AggregateRoot (%s)",
repoIdClass,
idClass);
throw new IllegalStateException(errMsg);
}
@SuppressWarnings("unchecked") // we checked by previous check methods and the code above.
final AggregatePartRepository<I, A, ?> result = (AggregatePartRepository<I, A, ?>) repo;
return result;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaDocumentService;
import com.kaltura.client.services.KalturaEdgeServerService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaServerService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaXInternalService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaSystemPartnerService;
import com.kaltura.client.services.KalturaEntryAdminService;
import com.kaltura.client.services.KalturaUiConfAdminService;
import com.kaltura.client.services.KalturaReportAdminService;
import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:15-10-24");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaDocumentService documentService;
public KalturaDocumentService getDocumentService() {
if(this.documentService == null)
this.documentService = new KalturaDocumentService(this);
return this.documentService;
}
protected KalturaEdgeServerService edgeServerService;
public KalturaEdgeServerService getEdgeServerService() {
if(this.edgeServerService == null)
this.edgeServerService = new KalturaEdgeServerService(this);
return this.edgeServerService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaServerService mediaServerService;
public KalturaMediaServerService getMediaServerService() {
if(this.mediaServerService == null)
this.mediaServerService = new KalturaMediaServerService(this);
return this.mediaServerService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaXInternalService xInternalService;
public KalturaXInternalService getXInternalService() {
if(this.xInternalService == null)
this.xInternalService = new KalturaXInternalService(this);
return this.xInternalService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaSystemPartnerService systemPartnerService;
public KalturaSystemPartnerService getSystemPartnerService() {
if(this.systemPartnerService == null)
this.systemPartnerService = new KalturaSystemPartnerService(this);
return this.systemPartnerService;
}
protected KalturaEntryAdminService entryAdminService;
public KalturaEntryAdminService getEntryAdminService() {
if(this.entryAdminService == null)
this.entryAdminService = new KalturaEntryAdminService(this);
return this.entryAdminService;
}
protected KalturaUiConfAdminService uiConfAdminService;
public KalturaUiConfAdminService getUiConfAdminService() {
if(this.uiConfAdminService == null)
this.uiConfAdminService = new KalturaUiConfAdminService(this);
return this.uiConfAdminService;
}
protected KalturaReportAdminService reportAdminService;
public KalturaReportAdminService getReportAdminService() {
if(this.reportAdminService == null)
this.reportAdminService = new KalturaReportAdminService(this);
return this.reportAdminService;
}
protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService;
public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() {
if(this.kalturaInternalToolsSystemHelperService == null)
this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this);
return this.kalturaInternalToolsSystemHelperService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
package com.microsoft.sqlserver.jdbc;
import static java.nio.charset.StandardCharsets.UTF_16LE;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.util.Calendar;
import java.util.EnumMap;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.UUID;
import com.microsoft.sqlserver.jdbc.JavaType.SetterConversionAE;
/**
* Defines an abstraction for execution of type-specific operations on DTV values.
*
* This abstract design keeps the logic of determining how to handle particular DTV value and jdbcType combinations in a single place
* (DTV.executeOp()) and forces new operations to be able to handle *all* the required combinations.
*
* Current operations and their locations are:
*
* Parameter.GetTypeDefinitionOp Determines the specific parameter type definition according to the current value.
*
* DTV.SendByRPCOp (below) Marshals the value onto the binary (RPC) buffer for sending to the server.
*/
abstract class DTVExecuteOp {
abstract void execute(DTV dtv,
String strValue) throws SQLServerException;
abstract void execute(DTV dtv,
Clob clobValue) throws SQLServerException;
abstract void execute(DTV dtv,
Byte byteValue) throws SQLServerException;
abstract void execute(DTV dtv,
Integer intValue) throws SQLServerException;
abstract void execute(DTV dtv,
java.sql.Time timeValue) throws SQLServerException;
abstract void execute(DTV dtv,
java.sql.Date dateValue) throws SQLServerException;
abstract void execute(DTV dtv,
java.sql.Timestamp timestampValue) throws SQLServerException;
abstract void execute(DTV dtv,
java.util.Date utilDateValue) throws SQLServerException;
abstract void execute(DTV dtv,
java.util.Calendar calendarValue) throws SQLServerException;
abstract void execute(DTV dtv,
LocalDate localDateValue) throws SQLServerException;
abstract void execute(DTV dtv,
LocalTime localTimeValue) throws SQLServerException;
abstract void execute(DTV dtv,
LocalDateTime localDateTimeValue) throws SQLServerException;
abstract void execute(DTV dtv,
OffsetTime offsetTimeValue) throws SQLServerException;
abstract void execute(DTV dtv,
OffsetDateTime offsetDateTimeValue) throws SQLServerException;
abstract void execute(DTV dtv,
microsoft.sql.DateTimeOffset dtoValue) throws SQLServerException;
abstract void execute(DTV dtv,
Float floatValue) throws SQLServerException;
abstract void execute(DTV dtv,
Double doubleValue) throws SQLServerException;
abstract void execute(DTV dtv,
BigDecimal bigDecimalValue) throws SQLServerException;
abstract void execute(DTV dtv,
Long longValue) throws SQLServerException;
abstract void execute(DTV dtv,
BigInteger bigIntegerValue) throws SQLServerException;
abstract void execute(DTV dtv,
Short shortValue) throws SQLServerException;
abstract void execute(DTV dtv,
Boolean booleanValue) throws SQLServerException;
abstract void execute(DTV dtv,
byte[] byteArrayValue) throws SQLServerException;
abstract void execute(DTV dtv,
Blob blobValue) throws SQLServerException;
abstract void execute(DTV dtv,
InputStream inputStreamValue) throws SQLServerException;
abstract void execute(DTV dtv,
Reader readerValue) throws SQLServerException;
abstract void execute(DTV dtv,
SQLServerSQLXML xmlValue) throws SQLServerException;
abstract void execute(DTV dtv,
TVP tvpValue) throws SQLServerException;
}
/**
* Outer level DTV class.
*
* All DTV manipulation is done through this class.
*/
final class DTV {
static final private java.util.logging.Logger aeLogger = java.util.logging.Logger.getLogger("com.microsoft.sqlserver.jdbc.DTV");
/** The source (app or server) providing the data for this value. */
private DTVImpl impl;
CryptoMetadata cryptoMeta = null;
JDBCType jdbcTypeSetByUser = null;
int valueLength = 0;
boolean sendStringParametersAsUnicode = true;
/**
* Sets a DTV value from a Java object.
*
* The new value replaces any value (column or parameter return value) that was previously set via the TDS response. Doing this may change the
* DTV's internal implementation to an AppDTVImpl.
*/
void setValue(SQLCollation collation,
JDBCType jdbcType,
Object value,
JavaType javaType,
StreamSetterArgs streamSetterArgs,
Calendar calendar,
Integer scale,
SQLServerConnection con,
boolean forceEncrypt) throws SQLServerException {
if (null == impl)
impl = new AppDTVImpl();
impl.setValue(this, collation, jdbcType, value, javaType, streamSetterArgs, calendar, scale, con, forceEncrypt);
}
final void setValue(Object value,
JavaType javaType) {
impl.setValue(value, javaType);
}
final void clear() {
impl = null;
}
final void skipValue(TypeInfo type,
TDSReader tdsReader,
boolean isDiscard) throws SQLServerException {
if (null == impl)
impl = new ServerDTVImpl();
impl.skipValue(type, tdsReader, isDiscard);
}
final void initFromCompressedNull() {
if (null == impl)
impl = new ServerDTVImpl();
impl.initFromCompressedNull();
}
final void setStreamSetterArgs(StreamSetterArgs streamSetterArgs) {
impl.setStreamSetterArgs(streamSetterArgs);
}
final void setCalendar(Calendar calendar) {
impl.setCalendar(calendar);
}
final void setScale(Integer scale) {
impl.setScale(scale);
}
final void setForceEncrypt(boolean forceEncrypt) {
impl.setForceEncrypt(forceEncrypt);
}
StreamSetterArgs getStreamSetterArgs() {
return impl.getStreamSetterArgs();
}
Calendar getCalendar() {
return impl.getCalendar();
}
Integer getScale() {
return impl.getScale();
}
/**
* Returns whether the DTV's current value is null.
*/
boolean isNull() {
return null == impl || impl.isNull();
}
/**
* @return true if impl is not null
*/
final boolean isInitialized() {
return (null != impl);
}
final void setJdbcType(JDBCType jdbcType) {
if (null == impl)
impl = new AppDTVImpl();
impl.setJdbcType(jdbcType);
}
/**
* Returns the DTV's current JDBC type
*/
final JDBCType getJdbcType() {
assert null != impl;
return impl.getJdbcType();
}
/**
* Returns the DTV's current JDBC type
*/
final JavaType getJavaType() {
assert null != impl;
return impl.getJavaType();
}
/**
* Returns the DTV's current value as the specified type.
*
* This variant of getValue() takes an extra parameter to handle the few cases where extra arguments are needed to determine the value (e.g. a
* Calendar object for time-valued DTV values).
*/
Object getValue(JDBCType jdbcType,
int scale,
InputStreamGetterArgs streamGetterArgs,
Calendar cal,
TypeInfo typeInfo,
CryptoMetadata cryptoMetadata,
TDSReader tdsReader) throws SQLServerException {
if (null == impl)
impl = new ServerDTVImpl();
return impl.getValue(this, jdbcType, scale, streamGetterArgs, cal, typeInfo, cryptoMetadata, tdsReader);
}
Object getSetterValue() {
return impl.getSetterValue();
}
/**
* Called by DTV implementation instances to change to a different DTV implementation.
*/
void setImpl(DTVImpl impl) {
this.impl = impl;
}
final class SendByRPCOp extends DTVExecuteOp {
private final String name;
private final TypeInfo typeInfo;
private final SQLCollation collation;
private final int precision;
private final int outScale;
private final boolean isOutParam;
private final TDSWriter tdsWriter;
private final SQLServerConnection conn;
SendByRPCOp(String name,
TypeInfo typeInfo,
SQLCollation collation,
int precision,
int outScale,
boolean isOutParam,
TDSWriter tdsWriter,
SQLServerConnection conn) {
this.name = name;
this.typeInfo = typeInfo;
this.collation = collation;
this.precision = precision;
this.outScale = outScale;
this.isOutParam = isOutParam;
this.tdsWriter = tdsWriter;
this.conn = conn;
}
void execute(DTV dtv,
String strValue) throws SQLServerException {
tdsWriter.writeRPCStringUnicode(name, strValue, isOutParam, collation);
}
void execute(DTV dtv,
Clob clobValue) throws SQLServerException {
// executeOp should have handled null Clob as a String
assert null != clobValue;
long clobLength = 0;
Reader clobReader = null;
try {
clobLength = DataTypes.getCheckedLength(conn, dtv.getJdbcType(), clobValue.length(), false);
clobReader = clobValue.getCharacterStream();
}
catch (SQLException e) {
SQLServerException.makeFromDriverError(conn, null, e.getMessage(), null, false);
}
// If the Clob value is to be sent as MBCS, then convert the value to an MBCS InputStream
JDBCType jdbcType = dtv.getJdbcType();
if (null != collation
&& (JDBCType.CHAR == jdbcType || JDBCType.VARCHAR == jdbcType || JDBCType.LONGVARCHAR == jdbcType || JDBCType.CLOB == jdbcType)) {
if (null == clobReader) {
tdsWriter.writeRPCByteArray(name, null, isOutParam, jdbcType, collation);
}
else {
ReaderInputStream clobStream = new ReaderInputStream(clobReader, collation.getCharset(), clobLength);
tdsWriter.writeRPCInputStream(name, clobStream, DataTypes.UNKNOWN_STREAM_LENGTH, isOutParam, jdbcType, collation);
}
}
else // Send CLOB value as Unicode
{
if (null == clobReader) {
tdsWriter.writeRPCStringUnicode(name, null, isOutParam, collation);
}
else {
tdsWriter.writeRPCReaderUnicode(name, clobReader, clobLength, isOutParam, collation);
}
}
}
void execute(DTV dtv,
Byte byteValue) throws SQLServerException {
tdsWriter.writeRPCByte(name, byteValue, isOutParam);
}
void execute(DTV dtv,
Integer intValue) throws SQLServerException {
tdsWriter.writeRPCInt(name, intValue, isOutParam);
}
void execute(DTV dtv,
java.sql.Time timeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.TIME, timeValue);
}
void execute(DTV dtv,
java.sql.Date dateValue) throws SQLServerException {
sendTemporal(dtv, JavaType.DATE, dateValue);
}
void execute(DTV dtv,
java.sql.Timestamp timestampValue) throws SQLServerException {
sendTemporal(dtv, JavaType.TIMESTAMP, timestampValue);
}
void execute(DTV dtv,
java.util.Date utilDateValue) throws SQLServerException {
sendTemporal(dtv, JavaType.UTILDATE, utilDateValue);
}
void execute(DTV dtv,
java.util.Calendar calendarValue) throws SQLServerException {
sendTemporal(dtv, JavaType.CALENDAR, calendarValue);
}
void execute(DTV dtv,
LocalDate localDateValue) throws SQLServerException {
sendTemporal(dtv, JavaType.LOCALDATE, localDateValue);
}
void execute(DTV dtv,
LocalTime localTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.LOCALTIME, localTimeValue);
}
void execute(DTV dtv,
LocalDateTime localDateTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.LOCALDATETIME, localDateTimeValue);
}
void execute(DTV dtv,
OffsetTime offsetTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.OFFSETTIME, offsetTimeValue);
}
void execute(DTV dtv,
OffsetDateTime offsetDateTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.OFFSETDATETIME, offsetDateTimeValue);
}
void execute(DTV dtv,
microsoft.sql.DateTimeOffset dtoValue) throws SQLServerException {
sendTemporal(dtv, JavaType.DATETIMEOFFSET, dtoValue);
}
void execute(DTV dtv,
TVP tvpValue) throws SQLServerException {
// shouldn't be an output parameter
tdsWriter.writeTVP(tvpValue);
}
/**
* Clears the calendar and then sets only the fields passed in. Rest of the fields will have default values.
*/
private void clearSetCalendar(Calendar cal,
boolean lenient,
Integer year,
Integer month,
Integer day_of_month,
Integer hour_of_day,
Integer minute,
Integer second) {
cal.clear();
cal.setLenient(lenient);
if (null != year) {
cal.set(Calendar.YEAR, year);
}
if (null != month) {
cal.set(Calendar.MONTH, month);
}
if (null != day_of_month) {
cal.set(Calendar.DAY_OF_MONTH, day_of_month);
}
if (null != hour_of_day) {
cal.set(Calendar.HOUR_OF_DAY, hour_of_day);
}
if (null != minute) {
cal.set(Calendar.MINUTE, minute);
}
if (null != second) {
cal.set(Calendar.SECOND, second);
}
}
/**
* Sends the specified temporal type value to the server as the appropriate SQL Server type.
*
* To send the value to the server, this method does the following: 1) Converts its given temporal value argument into a common form
* encapsulated by a pure, lenient GregorianCalendar instance. 2) Normalizes that common form according to the target data type. 3) Sends the
* value to the server using the appropriate target data type method.
*
* @param dtv
* DTV with type info, etc.
* @param javaType
* the Java type of the Object that follows
* @param value
* the temporal value to send to the server. May be null.
*/
private void sendTemporal(DTV dtv,
JavaType javaType,
Object value) throws SQLServerException {
JDBCType jdbcType = dtv.getJdbcType();
GregorianCalendar calendar = null;
int subSecondNanos = 0;
int minutesOffset = 0;
/*
* Some precisions to consider: java.sql.Time is millisecond precision java.sql.Timestamp is nanosecond precision java.util.Date is
* millisecond precision java.util.Calendar is millisecond precision java.time.LocalTime is nanosecond precision java.time.LocalDateTime
* is nanosecond precision java.time.OffsetTime is nanosecond precision, with a zone offset java.time.OffsetDateTime is nanosecond
* precision, with a zone offset SQL Server Types: datetime2 is 7 digit precision, i.e 100 ns (default and max) datetime is 3 digit
* precision, i.e ms precision (default and max) time is 7 digit precision, i.e 100 ns (default and max) Note: sendTimeAsDatetime is true
* by default and it actually sends the time value as datetime, not datetime2 which looses precision values as datetime is only MS
* precision (1/300 of a second to be precise).
*
* Null values pass right on through to the typed writers below.
*
* For non-null values, load the value from its original Java object (java.sql.Time, java.sql.Date, java.sql.Timestamp, java.util.Date,
* java.time.LocalDate, java.time.LocalTime, java.time.LocalDateTime or microsoft.sql.DateTimeOffset) into a Gregorian calendar. Don't use
* the DTV's calendar directly, as it may not be Gregorian...
*/
if (null != value) {
TimeZone timeZone = TimeZone.getDefault(); // Time zone to associate with the value in the Gregorian calendar
long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
// Figure out the value components according to the type of the Java object passed in...
switch (javaType) {
case TIME: {
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone() : TimeZone.getDefault();
utcMillis = ((java.sql.Time) value).getTime();
subSecondNanos = Nanos.PER_MILLISECOND * (int) (utcMillis % 1000);
// The utcMillis value may be negative for morning times in time zones east of GMT.
// Since the date part of the java.sql.Time object is normalized to 1/1/1970
// in the local time zone, the date may still be 12/31/1969 UTC.
// If that is the case then adjust the sub-second nanos to the correct non-negative
// "wall clock" value. For example: -1 nanos (one nanosecond before midnight) becomes
// 999999999 nanos (999,999,999 nanoseconds after 11:59:59).
if (subSecondNanos < 0)
subSecondNanos += Nanos.PER_SECOND;
break;
}
case DATE: {
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone() : TimeZone.getDefault();
utcMillis = ((java.sql.Date) value).getTime();
break;
}
case TIMESTAMP: {
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone() : TimeZone.getDefault();
java.sql.Timestamp timestampValue = (java.sql.Timestamp) value;
utcMillis = timestampValue.getTime();
subSecondNanos = timestampValue.getNanos();
break;
}
case UTILDATE: {
// java.util.Date is mapped to JDBC type TIMESTAMP
// java.util.Date and java.sql.Date are both millisecond precision
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone() : TimeZone.getDefault();
utcMillis = ((java.util.Date) value).getTime();
// Need to use the subsecondnanoes part in UTILDATE besause it is mapped to JDBC TIMESTAMP. This is not
// needed in DATE because DATE is mapped to JDBC DATE (with time part normalized to midnight)
subSecondNanos = Nanos.PER_MILLISECOND * (int) (utcMillis % 1000);
// The utcMillis value may be negative for morning times in time zones east of GMT.
// Since the date part of the java.sql.Time object is normalized to 1/1/1970
// in the local time zone, the date may still be 12/31/1969 UTC.
// If that is the case then adjust the sub-second nanos to the correct non-negative
// "wall clock" value. For example: -1 nanos (one nanosecond before midnight) becomes
// 999999999 nanos (999,999,999 nanoseconds after 11:59:59).
if (subSecondNanos < 0)
subSecondNanos += Nanos.PER_SECOND;
break;
}
case CALENDAR: {
// java.util.Calendar is mapped to JDBC type TIMESTAMP
// java.util.Calendar is millisecond precision
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone() : TimeZone.getDefault();
utcMillis = ((java.util.Calendar) value).getTimeInMillis();
// Need to use the subsecondnanoes part in CALENDAR besause it is mapped to JDBC TIMESTAMP. This is not
// needed in DATE because DATE is mapped to JDBC DATE (with time part normalized to midnight)
subSecondNanos = Nanos.PER_MILLISECOND * (int) (utcMillis % 1000);
// The utcMillis value may be negative for morning times in time zones east of GMT.
// Since the date part of the java.sql.Time object is normalized to 1/1/1970
// in the local time zone, the date may still be 12/31/1969 UTC.
// If that is the case then adjust the sub-second nanos to the correct non-negative
// "wall clock" value. For example: -1 nanos (one nanosecond before midnight) becomes
// 999999999 nanos (999,999,999 nanoseconds after 11:59:59).
if (subSecondNanos < 0)
subSecondNanos += Nanos.PER_SECOND;
break;
}
case LOCALDATE:
// Mapped to JDBC type DATE
calendar = new GregorianCalendar(UTC.timeZone, Locale.US);
// All time fields are set to default
clearSetCalendar(calendar, true, ((LocalDate) value).getYear(), ((LocalDate) value).getMonthValue() - 1, // Calendar 'month'
// is 0-based, but
// LocalDate 'month'
// is 1-based
((LocalDate) value).getDayOfMonth(), null, null, null);
break;
case LOCALTIME:
// Nanoseconds precision, mapped to JDBC type TIME
calendar = new GregorianCalendar(UTC.timeZone, Locale.US);
// All date fields are set to default
LocalTime LocalTimeValue = ((LocalTime) value);
clearSetCalendar(calendar, true, conn.baseYear(), 1, 1, LocalTimeValue.getHour(), // Gets hour_of_day field
LocalTimeValue.getMinute(), LocalTimeValue.getSecond());
subSecondNanos = LocalTimeValue.getNano();
// Do not need to adjust subSecondNanos as in the case for TIME
// because LOCALTIME does not have time zone and is not using utcMillis
break;
case LOCALDATETIME:
// Nanoseconds precision, mapped to JDBC type TIMESTAMP
calendar = new GregorianCalendar(UTC.timeZone, Locale.US);
// Calendar 'month' is 0-based, but LocalDateTime 'month' is 1-based
LocalDateTime localDateTimeValue = (LocalDateTime) value;
clearSetCalendar(calendar, true, localDateTimeValue.getYear(), localDateTimeValue.getMonthValue() - 1,
localDateTimeValue.getDayOfMonth(), localDateTimeValue.getHour(), // Gets hour_of_day field
localDateTimeValue.getMinute(), localDateTimeValue.getSecond());
subSecondNanos = localDateTimeValue.getNano();
// Do not need to adjust subSecondNanos as in the case for TIME
// because LOCALDATETIME does not have time zone and is not using utcMillis
break;
case OFFSETTIME:
OffsetTime offsetTimeValue = (OffsetTime) value;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also supports
// offsets in minutes precision.
minutesOffset = offsetTimeValue.getOffset().getTotalSeconds() / 60;
}
catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error
// is generated in the driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetTimeValue.getNano();
// If the target data type is TIME_WITH_TIMEZONE, then use UTC for the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = (JDBCType.TIME_WITH_TIMEZONE == jdbcType && (null == typeInfo || SSType.DATETIMEOFFSET == typeInfo.getSSType())) ?
UTC.timeZone : new SimpleTimeZone(minutesOffset * 60 * 1000, "");
// The behavior is similar to microsoft.sql.DateTimeOffset
// In Timestamp format, leading zeros for the fields can be omitted.
String offsetTimeStr = conn.baseYear() + "-01-01" + ' ' + offsetTimeValue.getHour() + ':' + offsetTimeValue.getMinute() + ':'
+ offsetTimeValue.getSecond();
utcMillis = Timestamp.valueOf(offsetTimeStr).getTime();
break;
case OFFSETDATETIME:
OffsetDateTime offsetDateTimeValue = (OffsetDateTime) value;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also supports
// offsets in minutes precision.
minutesOffset = offsetDateTimeValue.getOffset().getTotalSeconds() / 60;
}
catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error
// is generated in the driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetDateTimeValue.getNano();
// If the target data type is TIME_WITH_TIMEZONE or TIMESTAMP_WITH_TIMEZONE, then use UTC for the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = ((JDBCType.TIMESTAMP_WITH_TIMEZONE == jdbcType || JDBCType.TIME_WITH_TIMEZONE == jdbcType)
&& (null == typeInfo || SSType.DATETIMEOFFSET == typeInfo.getSSType())) ? UTC.timeZone
: new SimpleTimeZone(minutesOffset * 60 * 1000, "");
// The behavior is similar to microsoft.sql.DateTimeOffset
// In Timestamp format, only YEAR needs to have 4 digits. The leading zeros for the rest of the fields can be omitted.
String offDateTimeStr = String.format("%04d", offsetDateTimeValue.getYear()) + '-' + offsetDateTimeValue.getMonthValue() + '-'
+ offsetDateTimeValue.getDayOfMonth() + ' ' + offsetDateTimeValue.getHour() + ':' + offsetDateTimeValue.getMinute()
+ ':' + offsetDateTimeValue.getSecond();
utcMillis = Timestamp.valueOf(offDateTimeStr).getTime();
break;
case DATETIMEOFFSET: {
microsoft.sql.DateTimeOffset dtoValue = (microsoft.sql.DateTimeOffset) value;
utcMillis = dtoValue.getTimestamp().getTime();
subSecondNanos = dtoValue.getTimestamp().getNanos();
minutesOffset = dtoValue.getMinutesOffset();
// microsoft.sql.DateTimeOffset values have a time zone offset that is internal
// to the value, so there should not be any DTV calendar for DateTimeOffset values.
assert null == dtv.getCalendar();
// If the target data type is DATETIMEOFFSET, then use UTC for the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = (JDBCType.DATETIMEOFFSET == jdbcType && (null == typeInfo || SSType.DATETIMEOFFSET == typeInfo.getSSType()
|| SSType.VARBINARY == typeInfo.getSSType() || SSType.VARBINARYMAX == typeInfo.getSSType())) ?
UTC.timeZone : new SimpleTimeZone(minutesOffset * 60 * 1000, "");
break;
}
default:
throw new AssertionError("Unexpected JavaType: " + javaType);
}
// For the LocalDate, LocalTime and LocalDateTime values, calendar should be set by now.
if (null == calendar) {
// Create the calendar that will hold the value. For DateTimeOffset values, the calendar's
// time zone is UTC. For other values, the calendar's time zone is a local time zone.
calendar = new GregorianCalendar(timeZone, Locale.US);
// Set the calendar lenient to allow setting the DAY_OF_YEAR and MILLISECOND fields
// to roll other fields to their correct values.
calendar.setLenient(true);
// Clear the calendar of any existing state. The state of a new Calendar object always
// reflects the current date, time, DST offset, etc.
calendar.clear();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
}
}
// With the value now stored in a Calendar object, determine the backend data type and
// write out the value to the server, after any necessarily normalization.
// typeInfo is null when called from PreparedStatement->Parameter->SendByRPC
if (null != typeInfo) // updater
{
switch (typeInfo.getSSType()) {
case DATETIME2:
// Default and max fractional precision is 7 digits (100ns)
tdsWriter.writeRPCDateTime2(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()), subSecondNanos,
typeInfo.getScale(), isOutParam);
break;
case DATE:
tdsWriter.writeRPCDate(name, calendar, isOutParam);
break;
case TIME:
// Default and max fractional precision is 7 digits (100ns)
tdsWriter.writeRPCTime(name, calendar, subSecondNanos, typeInfo.getScale(), isOutParam);
break;
case DATETIMEOFFSET:
// When converting from any other temporal Java type to DATETIMEOFFSET,
// deliberately interpret the "wall calendar" representation as expressing
// a date/time in UTC rather than the local time zone.
if (JavaType.DATETIMEOFFSET != javaType) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType, conn.baseYear());
minutesOffset = 0; // UTC
}
tdsWriter.writeRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos, typeInfo.getScale(), isOutParam);
break;
case DATETIME:
case SMALLDATETIME:
tdsWriter.writeRPCDateTime(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()), subSecondNanos,
isOutParam);
break;
case VARBINARY:
case VARBINARYMAX:
switch (jdbcType) {
case DATETIME:
case SMALLDATETIME:
tdsWriter.writeEncryptedRPCDateTime(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, isOutParam, jdbcType);
break;
case TIMESTAMP:
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCDateTime2(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, valueLength, isOutParam);
break;
case TIME:
// when colum is encrypted, always send time as time, ignore sendTimeAsDatetime setting
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCTime(name, calendar, subSecondNanos, valueLength, isOutParam);
break;
case DATE:
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCDate(name, calendar, isOutParam);
break;
case TIMESTAMP_WITH_TIMEZONE:
case DATETIMEOFFSET:
// When converting from any other temporal Java type to DATETIMEOFFSET/TIMESTAMP_WITH_TIMEZONE,
// deliberately reinterpret the value as local to UTC. This is to match
// SQL Server behavior for such conversions.
if ((JavaType.DATETIMEOFFSET != javaType) && (JavaType.OFFSETDATETIME != javaType)) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType, conn.baseYear());
minutesOffset = 0; // UTC
}
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos, valueLength, isOutParam);
break;
default:
assert false : "Unexpected JDBCType: " + jdbcType;
}
break;
default:
assert false : "Unexpected SSType: " + typeInfo.getSSType();
}
}
else // setter
{
// Katmai and later
// When sending as...
// - java.sql.Types.TIMESTAMP, use DATETIME2 SQL Server data type
// - java.sql.Types.TIME, use TIME or DATETIME SQL Server data type
// as determined by sendTimeAsDatetime setting
// - java.sql.Types.DATE, use DATE SQL Server data type
// - microsoft.sql.Types.DATETIMEOFFSET, use DATETIMEOFFSET SQL Server data type
if (conn.isKatmaiOrLater()) {
if (aeLogger.isLoggable(java.util.logging.Level.FINE) && (null != cryptoMeta)) {
aeLogger.fine("Encrypting temporal data type.");
}
switch (jdbcType) {
case DATETIME:
case SMALLDATETIME:
case TIMESTAMP:
if (null != cryptoMeta) {
if ((JDBCType.DATETIME == jdbcType) || (JDBCType.SMALLDATETIME == jdbcType)) {
tdsWriter.writeEncryptedRPCDateTime(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, isOutParam, jdbcType);
}
else if (0 == valueLength) {
tdsWriter.writeEncryptedRPCDateTime2(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, outScale, isOutParam);
}
else {
tdsWriter.writeEncryptedRPCDateTime2(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, (valueLength), isOutParam);
}
}
else
tdsWriter.writeRPCDateTime2(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()), subSecondNanos,
TDS.MAX_FRACTIONAL_SECONDS_SCALE, isOutParam);
break;
case TIME:
// if column is encrypted, always send as TIME
if (null != cryptoMeta) {
if (0 == valueLength) {
tdsWriter.writeEncryptedRPCTime(name, calendar, subSecondNanos, outScale, isOutParam);
}
else {
tdsWriter.writeEncryptedRPCTime(name, calendar, subSecondNanos, valueLength, isOutParam);
}
}
else {
// Send the java.sql.Types.TIME value as TIME or DATETIME SQL Server
// data type, based on sendTimeAsDatetime setting.
if (conn.getSendTimeAsDatetime()) {
tdsWriter.writeRPCDateTime(name, timestampNormalizedCalendar(calendar, JavaType.TIME, TDS.BASE_YEAR_1970),
subSecondNanos, isOutParam);
}
else {
tdsWriter.writeRPCTime(name, calendar, subSecondNanos, TDS.MAX_FRACTIONAL_SECONDS_SCALE, isOutParam);
}
}
break;
case DATE:
if (null != cryptoMeta)
tdsWriter.writeEncryptedRPCDate(name, calendar, isOutParam);
else
tdsWriter.writeRPCDate(name, calendar, isOutParam);
break;
case TIME_WITH_TIMEZONE:
// When converting from any other temporal Java type to TIME_WITH_TIMEZONE,
// deliberately reinterpret the value as local to UTC. This is to match
// SQL Server behavior for such conversions.
if ((JavaType.OFFSETDATETIME != javaType) && (JavaType.OFFSETTIME != javaType)) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType, conn.baseYear());
minutesOffset = 0; // UTC
}
tdsWriter.writeRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos, TDS.MAX_FRACTIONAL_SECONDS_SCALE,
isOutParam);
break;
case TIMESTAMP_WITH_TIMEZONE:
case DATETIMEOFFSET:
// When converting from any other temporal Java type to DATETIMEOFFSET/TIMESTAMP_WITH_TIMEZONE,
// deliberately reinterpret the value as local to UTC. This is to match
// SQL Server behavior for such conversions.
if ((JavaType.DATETIMEOFFSET != javaType) && (JavaType.OFFSETDATETIME != javaType)) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType, conn.baseYear());
minutesOffset = 0; // UTC
}
if (null != cryptoMeta) {
if (0 == valueLength) {
tdsWriter.writeEncryptedRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos, outScale, isOutParam);
}
else {
tdsWriter.writeEncryptedRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos,
(0 == valueLength ? TDS.MAX_FRACTIONAL_SECONDS_SCALE : valueLength), isOutParam);
}
}
else
tdsWriter.writeRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos, TDS.MAX_FRACTIONAL_SECONDS_SCALE,
isOutParam);
break;
default:
assert false : "Unexpected JDBCType: " + jdbcType;
}
}
// Yukon and earlier
// When sending as...
// - java.sql.Types.TIMESTAMP, use DATETIME SQL Server data type (all components)
// - java.sql.Types.TIME, use DATETIME SQL Server data type (with date = 1/1/1970)
// - java.sql.Types.DATE, use DATETIME SQL Server data type (with time = midnight)
// - microsoft.sql.Types.DATETIMEOFFSET (not supported - exception should have been thrown earlier)
else {
assert JDBCType.TIME == jdbcType || JDBCType.DATE == jdbcType || JDBCType.TIMESTAMP == jdbcType : "Unexpected JDBCType: "
+ jdbcType;
tdsWriter.writeRPCDateTime(name, timestampNormalizedCalendar(calendar, javaType, TDS.BASE_YEAR_1970), subSecondNanos, isOutParam);
}
} // setters
}
/**
* Normalizes a GregorianCalendar value appropriately for a DATETIME, SMALLDATETIME, DATETIME2, or DATETIMEOFFSET SQL Server data type.
*
* For DATE values, the time must be normalized to midnight. For TIME values, the date must be normalized to January of the specified base
* year (1970 or 1900) For other temporal types (DATETIME, SMALLDATETIME, DATETIME2, DATETIMEOFFSET), no normalization is needed - both date
* and time contribute to the final value.
*
* @param calendar
* the value to normalize. May be null.
* @param javaType
* the Java type that the calendar value represents.
* @param baseYear
* the base year (1970 or 1900) for use in normalizing TIME values.
*/
private GregorianCalendar timestampNormalizedCalendar(GregorianCalendar calendar,
JavaType javaType,
int baseYear) {
if (null != calendar) {
switch (javaType) {
case LOCALDATE:
case DATE:
// Note: Although UTILDATE is a Date object (java.util.Date) it cannot have normalized time values.
// This is because java.util.Date is mapped to JDBC TIMESTAMP according to the JDBC spec.
// java.util.Calendar is also mapped to JDBC TIMESTAMP and hence should have both date and time parts.
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
break;
case OFFSETTIME:
case LOCALTIME:
case TIME:
assert TDS.BASE_YEAR_1970 == baseYear || TDS.BASE_YEAR_1900 == baseYear;
calendar.set(baseYear, Calendar.JANUARY, 1);
break;
default:
break;
}
}
return calendar;
}
// Conversion from Date/Time/Timestamp to DATETIMEOFFSET reinterprets (changes)
// the "wall clock" value to be local to UTC rather than the local to the
// local Calendar's time zone. This behavior (ignoring the local time zone
// when converting to DATETIMEOFFSET, which is time zone-aware) may seem
// counterintuitive, but is necessary per the data types spec to match SQL
// Server's conversion behavior for both setters and updaters.
private GregorianCalendar localCalendarAsUTC(GregorianCalendar cal) {
if (null == cal)
return null;
// Interpret "wall clock" value of the local calendar as a date/time/timestamp in UTC
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int millis = cal.get(Calendar.MILLISECOND);
cal.setTimeZone(UTC.timeZone);
cal.set(year, month, date, hour, minute, second);
cal.set(Calendar.MILLISECOND, millis);
return cal;
}
void execute(DTV dtv,
Float floatValue) throws SQLServerException {
if (JDBCType.REAL == dtv.getJdbcType()) {
tdsWriter.writeRPCReal(name, floatValue, isOutParam);
}
else // all other jdbcTypes (not just JDBCType.FLOAT!)
{
/*
* 2.26 floating point data needs to go to the DB as 8 bytes or else rounding errors occur at the DB. The ODBC driver sends 4 byte
* floats as 8 bytes also. So tried assigning the float to a double with double d = float f but d now also shows rounding errors (from
* simply the assignment in the Java runtime). So the only way found is to convert the float to a string and init the double with that
* string
*/
Double doubleValue = (null == floatValue) ? null : new Double(floatValue.floatValue());
tdsWriter.writeRPCDouble(name, doubleValue, isOutParam);
}
}
void execute(DTV dtv,
Double doubleValue) throws SQLServerException {
tdsWriter.writeRPCDouble(name, doubleValue, isOutParam);
}
void execute(DTV dtv,
BigDecimal bigDecimalValue) throws SQLServerException {
if (DDC.exceedsMaxRPCDecimalPrecisionOrScale(bigDecimalValue)) {
String strValue = bigDecimalValue.toString();
tdsWriter.writeRPCStringUnicode(name, strValue, isOutParam, collation);
}
else {
tdsWriter.writeRPCBigDecimal(name, bigDecimalValue, outScale, isOutParam);
}
}
void execute(DTV dtv,
Long longValue) throws SQLServerException {
tdsWriter.writeRPCLong(name, longValue, isOutParam);
}
void execute(DTV dtv,
BigInteger bigIntegerValue) throws SQLServerException {
tdsWriter.writeRPCLong(name, bigIntegerValue.longValue(), isOutParam);
}
void execute(DTV dtv,
Short shortValue) throws SQLServerException {
tdsWriter.writeRPCShort(name, shortValue, isOutParam);
}
void execute(DTV dtv,
Boolean booleanValue) throws SQLServerException {
tdsWriter.writeRPCBit(name, booleanValue, isOutParam);
}
void execute(DTV dtv,
byte[] byteArrayValue) throws SQLServerException {
if (null != cryptoMeta) {
tdsWriter.writeRPCNameValType(name, isOutParam, TDSType.BIGVARBINARY);
if (null != byteArrayValue) {
byteArrayValue = SQLServerSecurityUtility.encryptWithKey(byteArrayValue, cryptoMeta, conn);
tdsWriter.writeEncryptedRPCByteArray(byteArrayValue);
writeEncryptData(dtv, false);
}
else {
// long and 8000/4000 types, and output parameter without input
// if there is no setter is called, javaType is null
if ((JDBCType.LONGVARCHAR == jdbcTypeSetByUser || JDBCType.LONGNVARCHAR == jdbcTypeSetByUser
|| JDBCType.LONGVARBINARY == jdbcTypeSetByUser
|| (DataTypes.SHORT_VARTYPE_MAX_BYTES == precision && JDBCType.VARCHAR == jdbcTypeSetByUser)
|| (DataTypes.SHORT_VARTYPE_MAX_CHARS == precision && JDBCType.NVARCHAR == jdbcTypeSetByUser)
|| (DataTypes.SHORT_VARTYPE_MAX_BYTES == precision && JDBCType.VARBINARY == jdbcTypeSetByUser))
&& null == dtv.getJavaType() && isOutParam) {
tdsWriter.writeEncryptedRPCPLP();
}
else {
tdsWriter.writeEncryptedRPCByteArray(byteArrayValue);
}
writeEncryptData(dtv, true);
}
}
else
tdsWriter.writeRPCByteArray(name, byteArrayValue, isOutParam, dtv.getJdbcType(), collation);
}
void writeEncryptData(DTV dtv,
boolean isNull) throws SQLServerException {
JDBCType destType = (null == jdbcTypeSetByUser) ? dtv.getJdbcType() : jdbcTypeSetByUser;
switch (destType.getIntValue()) {
case java.sql.Types.INTEGER: // 0x38
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x04);
break;
case java.sql.Types.BIGINT: // 0x7f
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x08);
break;
case java.sql.Types.BIT: // 0x32
tdsWriter.writeByte(TDSType.BITN.byteValue());
tdsWriter.writeByte((byte) 0x01);
break;
case java.sql.Types.SMALLINT: // 0x34
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x02);
break;
case java.sql.Types.TINYINT: // 0x30
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x01);
break;
case java.sql.Types.DOUBLE: // (FLT8TYPE) 0x3E
tdsWriter.writeByte(TDSType.FLOATN.byteValue());
tdsWriter.writeByte((byte) 0x08);
break;
case java.sql.Types.REAL: // (FLT4TYPE) 0x3B
tdsWriter.writeByte(TDSType.FLOATN.byteValue());
tdsWriter.writeByte((byte) 0x04);
break;
case microsoft.sql.Types.MONEY:
case microsoft.sql.Types.SMALLMONEY:
case java.sql.Types.NUMERIC:
case java.sql.Types.DECIMAL:
// money/smallmoney is mapped to JDBC types java.sql.Types.Decimal
if ((JDBCType.MONEY == destType) || (JDBCType.SMALLMONEY == destType)) {
tdsWriter.writeByte(TDSType.MONEYN.byteValue()); // 0x6E
tdsWriter.writeByte((byte) ((JDBCType.MONEY == destType) ? 8 : 4));
}
else {
tdsWriter.writeByte(TDSType.NUMERICN.byteValue()); // 0x6C
if (isNull) {
tdsWriter.writeByte((byte) 0x11); // maximum length
if (null != cryptoMeta && null != cryptoMeta.getBaseTypeInfo()) {
tdsWriter.writeByte((byte) ((0 != valueLength) ? valueLength : cryptoMeta.getBaseTypeInfo().getPrecision()));
}
else {
tdsWriter.writeByte((byte) ((0 != valueLength) ? valueLength : 0x12)); // default length, 0x12 equals to 18, which is
// the default length for decimal value
}
tdsWriter.writeByte((byte) ((0 != outScale) ? outScale : 0)); // send scale
}
else {
tdsWriter.writeByte((byte) 0x11); // maximum length
if (null != cryptoMeta && null != cryptoMeta.getBaseTypeInfo()) {
tdsWriter.writeByte((byte) cryptoMeta.getBaseTypeInfo().getPrecision());
}
else {
tdsWriter.writeByte((byte) ((0 != valueLength) ? valueLength : 0x12)); // default length, 0x12 equals to 18, which is
// the default length for decimal value
}
if (null != cryptoMeta && null != cryptoMeta.getBaseTypeInfo()) {
tdsWriter.writeByte((byte) cryptoMeta.getBaseTypeInfo().getScale());
}
else {
tdsWriter.writeByte((byte) ((null != dtv.getScale()) ? dtv.getScale() : 0)); // send scale
}
}
}
break;
case microsoft.sql.Types.GUID:
tdsWriter.writeByte(TDSType.GUID.byteValue());
if (isNull)
tdsWriter.writeByte((byte) ((0 != valueLength) ? valueLength : 1));
else
tdsWriter.writeByte((byte) 0x10);
break;
case java.sql.Types.CHAR: // 0xAF
// BIGCHARTYPE
tdsWriter.writeByte(TDSType.BIGCHAR.byteValue());
if (isNull)
tdsWriter.writeShort((short) ((0 != valueLength) ? valueLength : 1));
else
tdsWriter.writeShort((short) (valueLength));
if (null != collation)
collation.writeCollation(tdsWriter);
else
conn.getDatabaseCollation().writeCollation(tdsWriter);
break;
case java.sql.Types.NCHAR: // 0xEF
tdsWriter.writeByte(TDSType.NCHAR.byteValue());
if (isNull)
tdsWriter.writeShort((short) ((0 != valueLength) ? (valueLength * 2) : 1));
else {
if (isOutParam) {
tdsWriter.writeShort((short) (valueLength * 2));
}
else {
if (valueLength > DataTypes.SHORT_VARTYPE_MAX_BYTES) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_CHARS);
}
else {
tdsWriter.writeShort((short) valueLength);
}
}
}
if (null != collation)
collation.writeCollation(tdsWriter);
else
conn.getDatabaseCollation().writeCollation(tdsWriter);
break;
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.VARCHAR: // 0xA7
// BIGVARCHARTYPE
tdsWriter.writeByte(TDSType.BIGVARCHAR.byteValue());
if (isNull) {
if (dtv.jdbcTypeSetByUser.getIntValue() == java.sql.Types.LONGVARCHAR) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_CHARS);
}
else {
tdsWriter.writeShort((short) ((0 != valueLength) ? valueLength : 1));
}
}
else {
if (dtv.jdbcTypeSetByUser.getIntValue() == java.sql.Types.LONGVARCHAR) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_CHARS);
}
else if ((dtv.getJdbcType().getIntValue() == java.sql.Types.LONGVARCHAR)
|| (dtv.getJdbcType().getIntValue() == java.sql.Types.LONGNVARCHAR)) {
tdsWriter.writeShort((short) 1);
}
else {
if (valueLength > DataTypes.SHORT_VARTYPE_MAX_BYTES) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_CHARS);
}
else {
tdsWriter.writeShort((short) valueLength);
}
}
}
if (null != collation)
collation.writeCollation(tdsWriter);
else
conn.getDatabaseCollation().writeCollation(tdsWriter);
break;
case java.sql.Types.LONGNVARCHAR:
case java.sql.Types.NVARCHAR: // 0xE7
tdsWriter.writeByte(TDSType.NVARCHAR.byteValue());
if (isNull) {
if (dtv.jdbcTypeSetByUser.getIntValue() == java.sql.Types.LONGNVARCHAR) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_CHARS);
}
else {
tdsWriter.writeShort((short) ((0 != valueLength) ? (valueLength * 2) : 1));
}
}
else {
if (isOutParam) {
// for stored procedure output parameter, we need to
// double the length that is sent to SQL Server,
// Otherwise it gives Operand Clash exception.
if (dtv.jdbcTypeSetByUser.getIntValue() == java.sql.Types.LONGNVARCHAR) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_CHARS);
}
else {
tdsWriter.writeShort((short) (valueLength * 2));
}
}
else {
if (valueLength > DataTypes.SHORT_VARTYPE_MAX_BYTES) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_CHARS);
}
else {
tdsWriter.writeShort((short) valueLength);
}
}
}
if (null != collation)
collation.writeCollation(tdsWriter);
else
conn.getDatabaseCollation().writeCollation(tdsWriter);
break;
case java.sql.Types.BINARY: // 0xAD
tdsWriter.writeByte(TDSType.BIGBINARY.byteValue());
if (isNull)
tdsWriter.writeShort((short) ((0 != valueLength) ? valueLength : 1));
else
tdsWriter.writeShort((short) (valueLength));
break;
case java.sql.Types.LONGVARBINARY:
case java.sql.Types.VARBINARY: // 0xA5
// BIGVARBINARY
tdsWriter.writeByte(TDSType.BIGVARBINARY.byteValue());
if (isNull) {
if (dtv.jdbcTypeSetByUser.getIntValue() == java.sql.Types.LONGVARBINARY) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_BYTES);
}
else {
tdsWriter.writeShort((short) ((0 != valueLength) ? valueLength : 1));
}
}
else {
if (dtv.jdbcTypeSetByUser.getIntValue() == java.sql.Types.LONGVARBINARY) {
tdsWriter.writeShort((short) DataTypes.MAX_VARTYPE_MAX_BYTES);
}
else {
tdsWriter.writeShort((short) (valueLength));
}
}
break;
default:
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_UnsupportedDataTypeAE"));
throw new SQLServerException(form.format(new Object[] {destType}), null, 0, null);
}
tdsWriter.writeCryptoMetaData();
}
void execute(DTV dtv,
Blob blobValue) throws SQLServerException {
assert null != blobValue;
long blobLength = 0;
InputStream blobStream = null;
try {
blobLength = DataTypes.getCheckedLength(conn, dtv.getJdbcType(), blobValue.length(), false);
blobStream = blobValue.getBinaryStream();
}
catch (SQLException e) {
SQLServerException.makeFromDriverError(conn, null, e.getMessage(), null, false);
}
if (null == blobStream) {
tdsWriter.writeRPCByteArray(name, null, isOutParam, dtv.getJdbcType(), collation);
}
else {
tdsWriter.writeRPCInputStream(name, blobStream, blobLength, isOutParam, dtv.getJdbcType(), collation);
}
}
void execute(DTV dtv,
SQLServerSQLXML xmlValue) throws SQLServerException {
InputStream o = (null == xmlValue) ? null : xmlValue.getValue();
tdsWriter.writeRPCXML(name, o, null == o ? 0 : dtv.getStreamSetterArgs().getLength(), isOutParam);
}
void execute(DTV dtv,
InputStream inputStreamValue) throws SQLServerException {
tdsWriter.writeRPCInputStream(name, inputStreamValue, null == inputStreamValue ? 0 : dtv.getStreamSetterArgs().getLength(), isOutParam,
dtv.getJdbcType(), collation);
}
void execute(DTV dtv,
Reader readerValue) throws SQLServerException {
JDBCType jdbcType = dtv.getJdbcType();
// executeOp should have handled null Reader as a null String.
assert null != readerValue;
// Non-unicode JDBCType should have been handled before now
assert (JDBCType.NCHAR == jdbcType || JDBCType.NVARCHAR == jdbcType || JDBCType.LONGNVARCHAR == jdbcType
|| JDBCType.NCLOB == jdbcType) : "SendByRPCOp(Reader): Unexpected JDBC type " + jdbcType;
// Write the reader value as a stream of Unicode characters
tdsWriter.writeRPCReaderUnicode(name, readerValue, dtv.getStreamSetterArgs().getLength(), isOutParam, collation);
}
}
/**
* Execute a caller-defined, object type-specific operation on a DTV.
*
* See DTVExecuteOp
*/
final void executeOp(DTVExecuteOp op) throws SQLServerException {
JDBCType jdbcType = getJdbcType();
Object value = getSetterValue();
JavaType javaType = getJavaType();
boolean unsupportedConversion = false;
byte[] byteValue = null;
if (null != cryptoMeta && !SetterConversionAE.converts(javaType, jdbcType, sendStringParametersAsUnicode)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedConversionAE"));
Object[] msgArgs = {javaType.toString().toLowerCase(Locale.ENGLISH), jdbcType.toString().toLowerCase(Locale.ENGLISH)};
throw new SQLServerException(form.format(msgArgs), null);
}
if (null == value) {
switch (jdbcType) {
case NCHAR:
case NVARCHAR:
case LONGNVARCHAR:
case NCLOB:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (String) null);
break;
case INTEGER:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (Integer) null);
break;
case DATE:
op.execute(this, (java.sql.Date) null);
break;
case TIME:
op.execute(this, (java.sql.Time) null);
break;
case DATETIME:
case SMALLDATETIME:
case TIMESTAMP:
op.execute(this, (java.sql.Timestamp) null);
break;
case TIME_WITH_TIMEZONE:
case TIMESTAMP_WITH_TIMEZONE:
case DATETIMEOFFSET:
op.execute(this, (microsoft.sql.DateTimeOffset) null);
break;
case FLOAT:
case REAL:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (Float) null);
break;
case NUMERIC:
case DECIMAL:
case MONEY:
case SMALLMONEY:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (BigDecimal) null);
break;
case BINARY:
case VARBINARY:
case LONGVARBINARY:
case BLOB:
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case CLOB:
case GUID:
op.execute(this, (byte[]) null);
break;
case TINYINT:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (Byte) null);
break;
case BIGINT:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (Long) null);
break;
case DOUBLE:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (Double) null);
break;
case SMALLINT:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (Short) null);
break;
case BIT:
case BOOLEAN:
if (null != cryptoMeta)
op.execute(this, (byte[]) null);
else
op.execute(this, (Boolean) null);
break;
case SQLXML:
op.execute(this, (SQLServerSQLXML) null);
break;
case ARRAY:
case DATALINK:
case DISTINCT:
case JAVA_OBJECT:
case NULL:
case OTHER:
case REF:
case ROWID:
case STRUCT:
unsupportedConversion = true;
break;
case UNKNOWN:
default:
assert false : "Unexpected JDBCType: " + jdbcType;
unsupportedConversion = true;
break;
}
}
else // null != value
{
if (aeLogger.isLoggable(java.util.logging.Level.FINE) && (null != cryptoMeta)) {
aeLogger.fine("Encrypting java data type: " + javaType);
}
switch (javaType) {
case STRING:
if (JDBCType.GUID == jdbcType) {
if (value instanceof String)
value = UUID.fromString((String) value);
byte[] bArray = Util.asGuidByteArray((UUID) value);
op.execute(this, bArray);
}
else {
if (null != cryptoMeta) {
// if streaming types check for allowed data length in AE
// jdbcType is set to LONGNVARCHAR if input data length is > DataTypes.SHORT_VARTYPE_MAX_CHARS for string
if ((jdbcType == JDBCType.LONGNVARCHAR) && (JDBCType.VARCHAR == jdbcTypeSetByUser)
&& (DataTypes.MAX_VARTYPE_MAX_BYTES < valueLength)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_StreamingDataTypeAE"));
Object[] msgArgs = {DataTypes.MAX_VARTYPE_MAX_BYTES, JDBCType.LONGVARCHAR};
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
}
else if ((JDBCType.NVARCHAR == jdbcTypeSetByUser) && (DataTypes.MAX_VARTYPE_MAX_CHARS < valueLength)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_StreamingDataTypeAE"));
Object[] msgArgs = {DataTypes.MAX_VARTYPE_MAX_CHARS, JDBCType.LONGNVARCHAR};
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
}
// Each character is represented using 2 bytes in NVARCHAR
else if ((JDBCType.NVARCHAR == jdbcTypeSetByUser) || (JDBCType.NCHAR == jdbcTypeSetByUser)
|| (JDBCType.LONGNVARCHAR == jdbcTypeSetByUser)) {
byteValue = ((String) value).getBytes(UTF_16LE);
}
// Each character is represented using 1 bytes in VARCHAR
else if ((JDBCType.VARCHAR == jdbcTypeSetByUser) || (JDBCType.CHAR == jdbcTypeSetByUser)
|| (JDBCType.LONGVARCHAR == jdbcTypeSetByUser)) {
byteValue = ((String) value).getBytes();
}
op.execute(this, byteValue);
}
else
op.execute(this, (String) value);
}
break;
case INTEGER:
if (null != cryptoMeta) {
byteValue = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putLong(((Integer) value).longValue())
.array();
op.execute(this, byteValue);
}
else
op.execute(this, (Integer) value);
break;
case DATE:
op.execute(this, (java.sql.Date) value);
break;
case TIME:
op.execute(this, (java.sql.Time) value);
break;
case TIMESTAMP:
op.execute(this, (java.sql.Timestamp) value);
break;
case TVP:
op.execute(this, (TVP) value);
break;
case UTILDATE:
op.execute(this, (java.util.Date) value);
break;
case CALENDAR:
op.execute(this, (java.util.Calendar) value);
break;
case LOCALDATE:
op.execute(this, (LocalDate) value);
break;
case LOCALTIME:
op.execute(this, (LocalTime) value);
break;
case LOCALDATETIME:
op.execute(this, (LocalDateTime) value);
break;
case OFFSETTIME:
op.execute(this, (OffsetTime) value);
break;
case OFFSETDATETIME:
op.execute(this, (OffsetDateTime) value);
break;
case DATETIMEOFFSET:
op.execute(this, (microsoft.sql.DateTimeOffset) value);
break;
case FLOAT:
if (null != cryptoMeta) {
if (Float.isInfinite((Float) value)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
throw new SQLServerException(form.format(new Object[] {jdbcType}), null, 0, null);
}
byteValue = ByteBuffer.allocate((Float.SIZE / Byte.SIZE)).order(ByteOrder.LITTLE_ENDIAN).putFloat((Float) value).array();
op.execute(this, byteValue);
}
else
op.execute(this, (Float) value);
break;
case BIGDECIMAL:
if (null != cryptoMeta) {
// For AE, we need to use the setMoney/setSmallMoney methods to send encrypted data
// to money types. Also we need to use the TDS MONEYN rule for these.
// For these methods, the Java type is still BigDecimal, but the JDBCType
// would be JDBCType.MONEY or JDBCType.SMALLMONEY.
if ((JDBCType.MONEY == jdbcType) || (JDBCType.SMALLMONEY == jdbcType)) {
// For TDS we need to send the money value multiplied by 10^4 - this gives us the
// money value as integer. 4 is the default and only scale available with money.
// smallmoney is noralized to money.
BigDecimal bdValue = (BigDecimal) value;
// Need to validate range in the client side as we are converting BigDecimal to integers.
Util.validateMoneyRange(bdValue, jdbcType);
// Get the total number of digits after the multiplication. Scale is hardcoded to 4. This is needed to get the proper
// rounding.
// BigDecimal calculates precision a bit differently. For 0.000001, the precision is 1, but scale is 6 which makes the
// digit count -ve.
int digitCount = Math.max((bdValue.precision() - bdValue.scale()), 0) + 4;
long moneyVal = ((BigDecimal) value).multiply(new BigDecimal(10000), new MathContext(digitCount, RoundingMode.HALF_UP))
.longValue();
ByteBuffer bbuf = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
bbuf.putInt((int) (moneyVal >> 32)).array();
bbuf.putInt((int) moneyVal).array();
op.execute(this, bbuf.array());
}
else {
BigDecimal bigDecimalVal = (BigDecimal) value;
byte[] decimalToByte = DDC.convertBigDecimalToBytes(bigDecimalVal, bigDecimalVal.scale());
byteValue = new byte[16];
// removing the precision and scale information from the decimalToByte array
System.arraycopy(decimalToByte, 2, byteValue, 0, decimalToByte.length - 2);
this.setScale(bigDecimalVal.scale());
if (null != cryptoMeta.getBaseTypeInfo()) {
// if the precision of the column is smaller than the precision of the actual value,
// the driver throws exception
if (cryptoMeta.getBaseTypeInfo().getPrecision() < Util.getValueLengthBaseOnJavaType(bigDecimalVal, javaType, null,
null, jdbcType)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {cryptoMeta.getBaseTypeInfo().getSSTypeName()};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW,
DriverError.NOT_SET, null);
}
}
else {
// if the precision that user provides is smaller than the precision of the actual value,
// the driver assumes the precision that user provides is the correct precision, and throws
// exception
if (valueLength < Util.getValueLengthBaseOnJavaType(bigDecimalVal, javaType, null, null, jdbcType)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.DECIMAL};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW,
DriverError.NOT_SET, null);
}
}
op.execute(this, byteValue);
}
}
else
op.execute(this, (BigDecimal) value);
break;
case BYTEARRAY:
if ((null != cryptoMeta) && (DataTypes.MAX_VARTYPE_MAX_BYTES < valueLength)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_StreamingDataTypeAE"));
Object[] msgArgs = {DataTypes.MAX_VARTYPE_MAX_BYTES, JDBCType.BINARY};
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
}
else
op.execute(this, (byte[]) value);
break;
case BYTE:
// for tinyint
if (null != cryptoMeta) {
byteValue = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putLong((byte) value & 0xFF).array();
op.execute(this, byteValue);
}
else
op.execute(this, (Byte) value);
break;
case LONG:
if (null != cryptoMeta) {
byteValue = ByteBuffer.allocate((Long.SIZE / Byte.SIZE)).order(ByteOrder.LITTLE_ENDIAN).putLong((Long) value).array();
op.execute(this, byteValue);
}
else
op.execute(this, (Long) value);
break;
case BIGINTEGER:
op.execute(this, (java.math.BigInteger) value);
break;
case DOUBLE:
if (null != cryptoMeta) {
if (Double.isInfinite((Double) value)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
throw new SQLServerException(form.format(new Object[] {jdbcType}), null, 0, null);
}
byteValue = ByteBuffer.allocate((Double.SIZE / Byte.SIZE)).order(ByteOrder.LITTLE_ENDIAN).putDouble((Double) value).array();
op.execute(this, byteValue);
}
else
op.execute(this, (Double) value);
break;
case SHORT:
if (null != cryptoMeta) {
byteValue = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putLong((short) value).array();
op.execute(this, byteValue);
}
else
op.execute(this, (Short) value);
break;
case BOOLEAN:
if (null != cryptoMeta) {
byteValue = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putLong((Boolean) value ? 1 : 0)
.array();
op.execute(this, byteValue);
}
else
op.execute(this, (Boolean) value);
break;
case BLOB:
op.execute(this, (Blob) value);
break;
case CLOB:
case NCLOB:
op.execute(this, (Clob) value);
break;
case INPUTSTREAM:
op.execute(this, (InputStream) value);
break;
case READER:
op.execute(this, (Reader) value);
break;
case SQLXML:
op.execute(this, (SQLServerSQLXML) value);
break;
default:
assert false : "Unexpected JavaType: " + javaType;
unsupportedConversion = true;
break;
}
}
if (unsupportedConversion) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedConversionFromTo"));
Object[] msgArgs = {javaType, jdbcType};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET, null);
}
}
void sendCryptoMetaData(CryptoMetadata cryptoMeta,
TDSWriter tdsWriter) {
this.cryptoMeta = cryptoMeta;
tdsWriter.setCryptoMetaData(cryptoMeta);
}
void jdbcTypeSetByUser(JDBCType jdbcTypeSetByUser,
int valueLength) {
this.jdbcTypeSetByUser = jdbcTypeSetByUser;
this.valueLength = valueLength;
}
/**
* Serializes a value as the specified type for RPC.
*/
void sendByRPC(String name,
TypeInfo typeInfo,
SQLCollation collation,
int precision,
int outScale,
boolean isOutParam,
TDSWriter tdsWriter,
SQLServerConnection conn) throws SQLServerException {
// typeInfo is null when called from PreparedStatement->Parameter->SendByRPC
executeOp(new SendByRPCOp(name, typeInfo, collation, precision, outScale, isOutParam, tdsWriter, conn));
}
}
/**
* DTV implementation class interface.
*
* Currently there are two implementations: one for values which originate from Java values set by the app (AppDTVImpl) and one for values which
* originate from byte in the TDS response buffer (ServerDTVImpl).
*/
abstract class DTVImpl {
abstract void setValue(DTV dtv,
SQLCollation collation,
JDBCType jdbcType,
Object value,
JavaType javaType,
StreamSetterArgs streamSetterArgs,
Calendar cal,
Integer scale,
SQLServerConnection con,
boolean forceEncrypt) throws SQLServerException;
abstract void setValue(Object value,
JavaType javaType);
abstract void setStreamSetterArgs(StreamSetterArgs streamSetterArgs);
abstract void setCalendar(Calendar cal);
abstract void setScale(Integer scale);
abstract void setForceEncrypt(boolean forceEncrypt);
abstract StreamSetterArgs getStreamSetterArgs();
abstract Calendar getCalendar();
abstract Integer getScale();
abstract boolean isNull();
abstract void setJdbcType(JDBCType jdbcType);
abstract JDBCType getJdbcType();
abstract JavaType getJavaType();
abstract Object getValue(DTV dtv,
JDBCType jdbcType,
int scale,
InputStreamGetterArgs streamGetterArgs,
Calendar cal,
TypeInfo type,
CryptoMetadata cryptoMetadata,
TDSReader tdsReader) throws SQLServerException;
abstract Object getSetterValue();
abstract void skipValue(TypeInfo typeInfo,
TDSReader tdsReader,
boolean isDiscard) throws SQLServerException;
abstract void initFromCompressedNull();
}
/**
* DTV implementation for values set by the app from Java types.
*/
final class AppDTVImpl extends DTVImpl {
private JDBCType jdbcType = JDBCType.UNKNOWN;
private Object value;
private JavaType javaType;
private StreamSetterArgs streamSetterArgs;
private Calendar cal;
private Integer scale;
private boolean forceEncrypt;
final void skipValue(TypeInfo typeInfo,
TDSReader tdsReader,
boolean isDiscard) throws SQLServerException {
assert false;
}
final void initFromCompressedNull() {
assert false;
}
final class SetValueOp extends DTVExecuteOp {
private final SQLCollation collation;
private final SQLServerConnection con;
SetValueOp(SQLCollation collation,
SQLServerConnection con) {
this.collation = collation;
this.con = con;
}
void execute(DTV dtv,
String strValue) throws SQLServerException {
JDBCType jdbcType = dtv.getJdbcType();
// Normally we let the server convert the string to whatever backend
// type it is going into. However, if the app says that the string
// is a numeric/decimal value then convert the value to a BigDecimal
// now so that GetTypeDefinitionOp can generate a type definition
// with the correct scale.
if ((JDBCType.DECIMAL == jdbcType) || (JDBCType.NUMERIC == jdbcType) || (JDBCType.MONEY == jdbcType)
|| (JDBCType.SMALLMONEY == jdbcType)) {
assert null != strValue;
try {
dtv.setValue(new BigDecimal(strValue), JavaType.BIGDECIMAL);
}
catch (NumberFormatException e) {
DataTypes.throwConversionError("String", jdbcType.toString());
}
}
// If the backend column is a binary type, or we don't know the backend
// type, but we are being told that it is binary, then we need to convert
// the hexized text value to binary here because the server doesn't do
// this conversion for us.
else if (jdbcType.isBinary()) {
assert null != strValue;
dtv.setValue(ParameterUtils.HexToBin(strValue), JavaType.BYTEARRAY);
}
// If the (Unicode) string value is to be sent to the server as MBCS,
// then do the conversion now so that the decision to use a "short" or "long"
// SSType (i.e. VARCHAR vs. TEXT/VARCHAR(max)) is based on the exact length of
// the MBCS value (in bytes).
else if (null != collation
&& (JDBCType.CHAR == jdbcType || JDBCType.VARCHAR == jdbcType || JDBCType.LONGVARCHAR == jdbcType || JDBCType.CLOB == jdbcType)) {
byte[] nativeEncoding = null;
if (null != strValue) {
nativeEncoding = strValue.getBytes(collation.getCharset());
}
dtv.setValue(nativeEncoding, JavaType.BYTEARRAY);
}
}
void execute(DTV dtv,
Clob clobValue) throws SQLServerException {
// executeOp should have handled null Clob as a String
assert null != clobValue;
// Fail fast if the Clob's advertised length is not within bounds.
// The Clob's length or contents may still change before SendByRPCOp
// materializes the Clob at execution time if the app fails to treat
// the parameter as immutable once set, as is recommended by the JDBC spec.
try {
DataTypes.getCheckedLength(con, dtv.getJdbcType(), clobValue.length(), false);
}
catch (SQLException e) {
SQLServerException.makeFromDriverError(con, null, e.getMessage(), null, false);
}
}
void execute(DTV dtv,
SQLServerSQLXML xmlValue) throws SQLServerException {
}
void execute(DTV dtv,
Byte byteValue) throws SQLServerException {
}
void execute(DTV dtv,
Integer intValue) throws SQLServerException {
}
void execute(DTV dtv,
java.sql.Time timeValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert timeValue != null : "value is null";
dtv.setValue(timeValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
java.sql.Date dateValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert dateValue != null : "value is null";
dtv.setValue(dateValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
java.sql.Timestamp timestampValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert timestampValue != null : "value is null";
dtv.setValue(timestampValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
java.util.Date utilDateValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert utilDateValue != null : "value is null";
dtv.setValue(utilDateValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
LocalDate localDateValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert localDateValue != null : "value is null";
dtv.setValue(localDateValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
LocalTime localTimeValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert localTimeValue != null : "value is null";
dtv.setValue(localTimeValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
LocalDateTime localDateTimeValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert localDateTimeValue != null : "value is null";
dtv.setValue(localDateTimeValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
OffsetTime offsetTimeValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert offsetTimeValue != null : "value is null";
dtv.setValue(offsetTimeValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
OffsetDateTime offsetDateTimeValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert offsetDateTimeValue != null : "value is null";
dtv.setValue(offsetDateTimeValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
java.util.Calendar calendarValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert calendarValue != null : "value is null";
dtv.setValue(calendarValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
microsoft.sql.DateTimeOffset dtoValue) throws SQLServerException {
if (dtv.getJdbcType().isTextual()) {
assert dtoValue != null : "value is null";
dtv.setValue(dtoValue.toString(), JavaType.STRING);
}
}
void execute(DTV dtv,
TVP tvpValue) throws SQLServerException {
}
void execute(DTV dtv,
Float floatValue) throws SQLServerException {
}
void execute(DTV dtv,
Double doubleValue) throws SQLServerException {
}
void execute(DTV dtv,
BigDecimal bigDecimalValue) throws SQLServerException {
// Rescale the value if necessary
if (null != bigDecimalValue) {
Integer inScale = dtv.getScale();
if (null != inScale && inScale.intValue() != bigDecimalValue.scale())
bigDecimalValue = bigDecimalValue.setScale(inScale.intValue(), BigDecimal.ROUND_DOWN);
}
dtv.setValue(bigDecimalValue, JavaType.BIGDECIMAL);
}
void execute(DTV dtv,
Long longValue) throws SQLServerException {
}
void execute(DTV dtv,
BigInteger bigIntegerValue) throws SQLServerException {
}
void execute(DTV dtv,
Short shortValue) throws SQLServerException {
}
void execute(DTV dtv,
Boolean booleanValue) throws SQLServerException {
}
void execute(DTV dtv,
byte[] byteArrayValue) throws SQLServerException {
}
void execute(DTV dtv,
Blob blobValue) throws SQLServerException {
assert null != blobValue;
// Fail fast if the Blob's advertised length is not within bounds.
// The Blob's length or contents may still change before SendByRPCOp
// materializes the Blob at execution time if the app fails to treat
// the parameter as immutable once set, as is recommended by the JDBC spec.
try {
DataTypes.getCheckedLength(con, dtv.getJdbcType(), blobValue.length(), false);
}
catch (SQLException e) {
SQLServerException.makeFromDriverError(con, null, e.getMessage(), null, false);
}
}
void execute(DTV dtv,
InputStream inputStreamValue) throws SQLServerException {
DataTypes.getCheckedLength(con, dtv.getJdbcType(), dtv.getStreamSetterArgs().getLength(), true);
// If the stream is to be sent as Unicode, then assume it's an ASCII stream
if (JDBCType.NCHAR == jdbcType || JDBCType.NVARCHAR == jdbcType || JDBCType.LONGNVARCHAR == jdbcType) {
Reader readerValue = null;
try {
readerValue = new InputStreamReader(inputStreamValue, "US-ASCII");
}
catch (UnsupportedEncodingException ex) {
throw new SQLServerException(ex.getMessage(), null, 0, ex);
}
dtv.setValue(readerValue, JavaType.READER);
// No need to change SetterArgs since, for ASCII streams, the
// Reader length, in characters, is the same as the InputStream
// length, in bytes.
// Re-execute with the stream value to perform any further conversions
execute(dtv, readerValue);
}
}
void execute(DTV dtv,
Reader readerValue) throws SQLServerException {
// executeOp should have handled null Reader as a null String.
assert null != readerValue;
JDBCType jdbcType = dtv.getJdbcType();
long readerLength = DataTypes.getCheckedLength(con, dtv.getJdbcType(), dtv.getStreamSetterArgs().getLength(), true);
if (
// If the backend column is a binary type, or we don't know the backend
// type, but we are being told that it is binary, then we need to convert
// the hexized text value to binary here because the server doesn't do
// this conversion for us.
jdbcType.isBinary()) {
String stringValue = DDC.convertReaderToString(readerValue, (int) readerLength);
// If we were given an input stream length that we had to match and
// the actual stream length did not match then cancel the request.
if (DataTypes.UNKNOWN_STREAM_LENGTH != readerLength && stringValue.length() != readerLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength"));
Object[] msgArgs = {Long.valueOf(readerLength), Integer.valueOf(stringValue.length())};
SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), "", true);
}
dtv.setValue(stringValue, JavaType.STRING);
execute(dtv, stringValue);
}
// If the reader value is to be sent as MBCS, then convert the value to an MBCS InputStream
else if (null != collation
&& (JDBCType.CHAR == jdbcType || JDBCType.VARCHAR == jdbcType || JDBCType.LONGVARCHAR == jdbcType || JDBCType.CLOB == jdbcType)) {
ReaderInputStream streamValue = new ReaderInputStream(readerValue, collation.getCharset(), readerLength);
dtv.setValue(streamValue, JavaType.INPUTSTREAM);
// Even if we knew the length of the Reader, we do not know the length of the converted MBCS stream up front.
dtv.setStreamSetterArgs(new StreamSetterArgs(StreamType.CHARACTER, DataTypes.UNKNOWN_STREAM_LENGTH));
execute(dtv, streamValue);
}
}
}
void setValue(DTV dtv,
SQLCollation collation,
JDBCType jdbcType,
Object value,
JavaType javaType,
StreamSetterArgs streamSetterArgs,
Calendar cal,
Integer scale,
SQLServerConnection con,
boolean forceEncrypt) throws SQLServerException {
// Set the value according to its Java object type, nullness, and specified JDBC type
dtv.setValue(value, javaType);
dtv.setJdbcType(jdbcType);
dtv.setStreamSetterArgs(streamSetterArgs);
dtv.setCalendar(cal);
dtv.setScale(scale);
dtv.setForceEncrypt(forceEncrypt);
dtv.executeOp(new SetValueOp(collation, con));
}
void setValue(Object value,
JavaType javaType) {
this.value = value;
this.javaType = javaType;
}
void setStreamSetterArgs(StreamSetterArgs streamSetterArgs) {
this.streamSetterArgs = streamSetterArgs;
}
void setCalendar(Calendar cal) {
this.cal = cal;
}
void setScale(Integer scale) {
this.scale = scale;
}
void setForceEncrypt(boolean forceEncrypt) {
this.forceEncrypt = forceEncrypt;
}
StreamSetterArgs getStreamSetterArgs() {
return streamSetterArgs;
}
Calendar getCalendar() {
return cal;
}
Integer getScale() {
return scale;
}
boolean isNull() {
return null == value;
}
void setJdbcType(JDBCType jdbcType) {
this.jdbcType = jdbcType;
}
JDBCType getJdbcType() {
return jdbcType;
}
JavaType getJavaType() {
return javaType;
}
Object getValue(DTV dtv,
JDBCType jdbcType,
int scale,
InputStreamGetterArgs streamGetterArgs,
Calendar cal,
TypeInfo typeInfo,
CryptoMetadata cryptoMetadata,
TDSReader tdsReader) throws SQLServerException {
// Client side type conversion is not supported
if (this.jdbcType != jdbcType)
DataTypes.throwConversionError(this.jdbcType.toString(), jdbcType.toString());
return value;
}
Object getSetterValue() {
return value;
}
}
/**
* Encapsulation of type information associated with values returned in the TDS response stream (TYPE_INFO).
*
* ResultSet rows have type info for each column returned in a COLMETADATA response stream.
*
* CallableStatement output parameters have their type info returned in a RETURNVALUE response stream.
*/
final class TypeInfo {
private int maxLength; // Max length of data
private SSLenType ssLenType; // Length type (FIXEDLENTYPE, PARTLENTYPE, etc.)
private int precision;
private int displaySize;// size is in characters. display size assumes a formatted hexa decimal representation for binaries.
private int scale;
private short flags;
private SSType ssType;
private int userType;
private String udtTypeName;
// Collation (will be null for non-textual types).
private SQLCollation collation;
private Charset charset;
SSType getSSType() {
return ssType;
}
SSLenType getSSLenType() {
return ssLenType;
}
String getSSTypeName() {
return (SSType.UDT == ssType) ? udtTypeName : ssType.toString();
}
int getMaxLength() {
return maxLength;
}
int getPrecision() {
return precision;
}
int getDisplaySize() {
return displaySize;
}
int getScale() {
return scale;
}
SQLCollation getSQLCollation() {
return collation;
}
void setSQLCollation(SQLCollation collation) {
this.collation = collation;
}
Charset getCharset() {
return charset;
}
boolean isNullable() {
return 0x0001 == (flags & 0x0001);
}
boolean isCaseSensitive() {
return 0x0002 == (flags & 0x0002);
}
boolean isSparseColumnSet() {
return 0x0400 == (flags & 0x0400);
}
boolean isEncrypted() {
return 0x0800 == (flags & 0x0800);
}
static int UPDATABLE_READ_ONLY = 0;
static int UPDATABLE_READ_WRITE = 1;
static int UPDATABLE_UNKNOWN = 2;
int getUpdatability() {
return (flags >> 2) & 0x0003;
}
boolean isIdentity() {
return 0x0010 == (flags & 0x0010);
}
byte[] getFlags() {
byte[] f = new byte[2];
f[0] = (byte) (flags & 0xFF);
f[1] = (byte) ((flags >> 8) & 0xFF);
return f;
}
short getFlagsAsShort() {
return flags;
}
void setFlags(Short flags) {
this.flags = flags;
}
//TypeInfo Builder enum defines a set of builders used to construct TypeInfo instances
//for the various data types. Each builder builds a TypeInfo instance using a builder Strategy.
//Some strategies are used for multiple types (for example: FixedLenStrategy)
enum Builder
{
BIT (TDSType.BIT1, new FixedLenStrategy(
SSType.BIT,
1, // TDS length (bytes)
1, // precision (max numeric precision, in decimal digits)
"1".length(), // column display size
0) // scale
),
BIGINT (TDSType.INT8, new FixedLenStrategy(
SSType.BIGINT,
8, // TDS length (bytes)
Long.toString(Long.MAX_VALUE).length(), //precision (max numeric precision, in decimal digits)
("-" + Long.toString(Long.MAX_VALUE)).length(), // column display size (includes sign)
0) // scale
),
INTEGER (TDSType.INT4, new FixedLenStrategy(
SSType.INTEGER,
4, // TDS length (bytes)
Integer.toString(Integer.MAX_VALUE).length(), // precision (max numeric precision, in decimal digits)
("-" + Integer.toString(Integer.MAX_VALUE)).length(), // column display size (includes sign)
0) // scale
),
SMALLINT (TDSType.INT2, new FixedLenStrategy(
SSType.SMALLINT,
2, // TDS length (bytes)
Short.toString(Short.MAX_VALUE).length(), // precision (max numeric precision, in decimal digits)
("-" + Short.toString(Short.MAX_VALUE)).length(), // column display size (includes sign)
0) // scale
),
TINYINT (TDSType.INT1, new FixedLenStrategy(
SSType.TINYINT,
1, // TDS length (bytes)
Byte.toString(Byte.MAX_VALUE).length(), // precision (max numeric precision, in decimal digits)
Byte.toString(Byte.MAX_VALUE).length(), // column display size (no sign - TINYINT is unsigned)
0) // scale
),
REAL (TDSType.FLOAT4, new FixedLenStrategy(
SSType.REAL,
4, // TDS length (bytes)
7, // precision (max numeric precision, in bits)
13, // column display size
0) // scale
),
FLOAT (TDSType.FLOAT8, new FixedLenStrategy(
SSType.FLOAT,
8, // TDS length (bytes)
15, // precision (max numeric precision, in bits)
22, // column display size
0) // scale
),
SMALLDATETIME (TDSType.DATETIME4, new FixedLenStrategy(
SSType.SMALLDATETIME,
4, // TDS length (bytes)
"yyyy-mm-dd hh:mm".length(), // precision (formatted length, in characters, assuming max fractional seconds precision (0))
"yyyy-mm-dd hh:mm".length(), // column display size
0) // scale
),
DATETIME (TDSType.DATETIME8, new FixedLenStrategy(
SSType.DATETIME,
8, // TDS length (bytes)
"yyyy-mm-dd hh:mm:ss.fff".length(), // precision (formatted length, in characters, assuming max fractional seconds precision)
"yyyy-mm-dd hh:mm:ss.fff".length(), // column display size
3) // scale
),
SMALLMONEY (TDSType.MONEY4, new FixedLenStrategy(
SSType.SMALLMONEY,
4, // TDS length (bytes)
Integer.toString(Integer.MAX_VALUE).length(), // precision (max unscaled numeric precision, in decimal digits)
("-" + "." + Integer.toString(Integer.MAX_VALUE)).length(), // column display size (includes sign and decimal for scale)
4) // scale
),
MONEY (TDSType.MONEY8, new FixedLenStrategy(
SSType.MONEY,
8, // TDS length (bytes)
Long.toString(Long.MAX_VALUE).length(), // precision (max unscaled numeric precision, in decimal digits)
("-" + "." + Long.toString(Long.MAX_VALUE)).length(), // column display size (includes sign and decimal for scale)
4) // scale
),
BITN (TDSType.BITN, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
if (1 != tdsReader.readUnsignedByte())
tdsReader.throwInvalidTDS();
BIT.build(typeInfo, tdsReader);
typeInfo.ssLenType = SSLenType.BYTELENTYPE;
}
}),
INTN (TDSType.INTN, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
switch (tdsReader.readUnsignedByte()) {
case 8:
BIGINT.build(typeInfo, tdsReader);
break;
case 4:
INTEGER.build(typeInfo, tdsReader);
break;
case 2:
SMALLINT.build(typeInfo, tdsReader);
break;
case 1:
TINYINT.build(typeInfo, tdsReader);
break;
default:
tdsReader.throwInvalidTDS();
break;
}
typeInfo.ssLenType = SSLenType.BYTELENTYPE;
}
}),
DECIMAL (TDSType.DECIMALN, new DecimalNumericStrategy(SSType.DECIMAL)),
NUMERIC (TDSType.NUMERICN, new DecimalNumericStrategy(SSType.NUMERIC)),
FLOATN (TDSType.FLOATN, new BigOrSmallByteLenStrategy(FLOAT, REAL)),
MONEYN (TDSType.MONEYN, new BigOrSmallByteLenStrategy(MONEY, SMALLMONEY)),
DATETIMEN (TDSType.DATETIMEN, new BigOrSmallByteLenStrategy(DATETIME, SMALLDATETIME)),
TIME (TDSType.TIMEN, new KatmaiScaledTemporalStrategy(SSType.TIME)),
DATETIME2 (TDSType.DATETIME2N, new KatmaiScaledTemporalStrategy(SSType.DATETIME2)),
DATETIMEOFFSET (TDSType.DATETIMEOFFSETN, new KatmaiScaledTemporalStrategy(SSType.DATETIMEOFFSET)),
DATE (TDSType.DATEN, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.ssType = SSType.DATE;
typeInfo.ssLenType = SSLenType.BYTELENTYPE;
typeInfo.maxLength = 3;
typeInfo.displaySize = typeInfo.precision = "yyyy-mm-dd".length();
}
}),
BIGBINARY (TDSType.BIGBINARY, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.ssLenType = SSLenType.USHORTLENTYPE;
typeInfo.maxLength = tdsReader.readUnsignedShort();
if (typeInfo.maxLength > DataTypes.SHORT_VARTYPE_MAX_BYTES)
tdsReader.throwInvalidTDS();
typeInfo.precision = typeInfo.maxLength;
typeInfo.displaySize = 2 * typeInfo.maxLength;
typeInfo.ssType = (UserTypes.TIMESTAMP == typeInfo.userType) ? SSType.TIMESTAMP : SSType.BINARY;
}
}),
BIGVARBINARY (TDSType.BIGVARBINARY, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.maxLength = tdsReader.readUnsignedShort();
if (DataTypes.MAXTYPE_LENGTH == typeInfo.maxLength)// for PLP types
{
typeInfo.ssLenType = SSLenType.PARTLENTYPE;
typeInfo.ssType = SSType.VARBINARYMAX;
typeInfo.displaySize = typeInfo.precision = DataTypes.MAX_VARTYPE_MAX_BYTES;
}
else if (typeInfo.maxLength <= DataTypes.SHORT_VARTYPE_MAX_BYTES)// for non-PLP types
{
typeInfo.ssLenType = SSLenType.USHORTLENTYPE;
typeInfo.ssType = SSType.VARBINARY;
typeInfo.precision = typeInfo.maxLength;
typeInfo.displaySize = 2 * typeInfo.maxLength;
}
else {
tdsReader.throwInvalidTDS();
}
}
}),
IMAGE (TDSType.IMAGE, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.ssLenType = SSLenType.LONGLENTYPE;
typeInfo.maxLength = tdsReader.readInt();
if (typeInfo.maxLength < 0)
tdsReader.throwInvalidTDS();
typeInfo.ssType = SSType.IMAGE;
typeInfo.displaySize = typeInfo.precision = Integer.MAX_VALUE;
}
}),
BIGCHAR (TDSType.BIGCHAR, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.ssLenType = SSLenType.USHORTLENTYPE;
typeInfo.maxLength = tdsReader.readUnsignedShort();
if (typeInfo.maxLength > DataTypes.SHORT_VARTYPE_MAX_BYTES)
tdsReader.throwInvalidTDS();
typeInfo.displaySize = typeInfo.precision = typeInfo.maxLength;
typeInfo.ssType = SSType.CHAR;
typeInfo.collation = tdsReader.readCollation();
typeInfo.charset = typeInfo.collation.getCharset();
}
}),
BIGVARCHAR (TDSType.BIGVARCHAR, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.maxLength = tdsReader.readUnsignedShort();
if (DataTypes.MAXTYPE_LENGTH == typeInfo.maxLength)// for PLP types
{
typeInfo.ssLenType = SSLenType.PARTLENTYPE;
typeInfo.ssType = SSType.VARCHARMAX;
typeInfo.displaySize = typeInfo.precision = DataTypes.MAX_VARTYPE_MAX_BYTES;
}
else if (typeInfo.maxLength <= DataTypes.SHORT_VARTYPE_MAX_BYTES)// for non-PLP types
{
typeInfo.ssLenType = SSLenType.USHORTLENTYPE;
typeInfo.ssType = SSType.VARCHAR;
typeInfo.displaySize = typeInfo.precision = typeInfo.maxLength;
}
else {
tdsReader.throwInvalidTDS();
}
typeInfo.collation = tdsReader.readCollation();
typeInfo.charset = typeInfo.collation.getCharset();
}
}),
TEXT (TDSType.TEXT, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.ssLenType = SSLenType.LONGLENTYPE;
typeInfo.maxLength = tdsReader.readInt();
if (typeInfo.maxLength < 0)
tdsReader.throwInvalidTDS();
typeInfo.ssType = SSType.TEXT;
typeInfo.displaySize = typeInfo.precision = Integer.MAX_VALUE;
typeInfo.collation = tdsReader.readCollation();
typeInfo.charset = typeInfo.collation.getCharset();
}
}),
NCHAR (TDSType.NCHAR, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.ssLenType = SSLenType.USHORTLENTYPE;
typeInfo.maxLength = tdsReader.readUnsignedShort();
if (typeInfo.maxLength > DataTypes.SHORT_VARTYPE_MAX_BYTES || 0 != typeInfo.maxLength % 2)
tdsReader.throwInvalidTDS();
typeInfo.displaySize = typeInfo.precision = typeInfo.maxLength / 2;
typeInfo.ssType = SSType.NCHAR;
typeInfo.collation = tdsReader.readCollation();
typeInfo.charset = Encoding.UNICODE.charset();
}
}),
NVARCHAR (TDSType.NVARCHAR, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.maxLength = tdsReader.readUnsignedShort();
if (DataTypes.MAXTYPE_LENGTH == typeInfo.maxLength)// for PLP types
{
typeInfo.ssLenType = SSLenType.PARTLENTYPE;
typeInfo.ssType = SSType.NVARCHARMAX;
typeInfo.displaySize = typeInfo.precision = DataTypes.MAX_VARTYPE_MAX_CHARS;
}
else if (typeInfo.maxLength <= DataTypes.SHORT_VARTYPE_MAX_BYTES && 0 == typeInfo.maxLength % 2)// for non-PLP types
{
typeInfo.ssLenType = SSLenType.USHORTLENTYPE;
typeInfo.ssType = SSType.NVARCHAR;
typeInfo.displaySize = typeInfo.precision = typeInfo.maxLength / 2;
}
else {
tdsReader.throwInvalidTDS();
}
typeInfo.collation = tdsReader.readCollation();
typeInfo.charset = Encoding.UNICODE.charset();
}
}),
NTEXT (TDSType.NTEXT, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.ssLenType = SSLenType.LONGLENTYPE;
typeInfo.maxLength = tdsReader.readInt();
if (typeInfo.maxLength < 0)
tdsReader.throwInvalidTDS();
typeInfo.ssType = SSType.NTEXT;
typeInfo.displaySize = typeInfo.precision = Integer.MAX_VALUE / 2;
typeInfo.collation = tdsReader.readCollation();
typeInfo.charset = Encoding.UNICODE.charset();
}
}),
GUID (TDSType.GUID, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
int maxLength = tdsReader.readUnsignedByte();
if (maxLength != 16 && maxLength != 0)
tdsReader.throwInvalidTDS();
typeInfo.ssLenType = SSLenType.BYTELENTYPE;
typeInfo.ssType = SSType.GUID;
typeInfo.maxLength = maxLength;
typeInfo.displaySize = typeInfo.precision = "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN".length();
}
}),
UDT (TDSType.UDT, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
UDTTDSHeader udtTDSHeader = new UDTTDSHeader(tdsReader);
typeInfo.maxLength = udtTDSHeader.getMaxLen();
if (DataTypes.MAXTYPE_LENGTH == typeInfo.maxLength) {
typeInfo.precision = DataTypes.MAX_VARTYPE_MAX_BYTES;
typeInfo.displaySize = DataTypes.MAX_VARTYPE_MAX_BYTES;
}
else if (typeInfo.maxLength <= DataTypes.SHORT_VARTYPE_MAX_BYTES) {
typeInfo.precision = typeInfo.maxLength;
typeInfo.displaySize = 2 * typeInfo.maxLength;
}
else {
tdsReader.throwInvalidTDS();
}
typeInfo.ssLenType = SSLenType.PARTLENTYPE;
typeInfo.ssType = SSType.UDT;
// Every UDT type has an additional type name embedded in the TDS COLMETADATA
// header. Per meta-data spec for UDT types we return this type name
// instead of "UDT".
typeInfo.udtTypeName = udtTDSHeader.getTypeName();
}
}),
XML (TDSType.XML, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
XMLTDSHeader xmlTDSHeader = new XMLTDSHeader(tdsReader);
typeInfo.ssLenType = SSLenType.PARTLENTYPE;
typeInfo.ssType = SSType.XML;
typeInfo.displaySize = typeInfo.precision = Integer.MAX_VALUE / 2;
typeInfo.charset = Encoding.UNICODE.charset();
}
}),
SQL_VARIANT(TDSType.SQL_VARIANT, new Strategy()
{
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
try {
SQLServerException.makeFromDriverError(tdsReader.getConnection(), null, SQLServerException.getErrString("R_variantNotSupported"),
null, false);
}
finally {
/*
* As the driver doesn't know how to process or skip the VARIANT type in TDS token stream, we send an interrupt Signal to server,
* and skips all the data received while waiting for the interrupt acknowledgment.
*/
int remainingPackets = 0;
// Skip the current buffered packet
remainingPackets = tdsReader.availableCurrentPacket();
tdsReader.skip(remainingPackets);
// send interrupt to server
tdsReader.getCommand().interrupt(SQLServerException.getErrString("R_variantNotSupported"));
/*
* Skip all data only if waiting for attention ack and until interrupt acknowledgment is received.
*
* Interrupt acknowledgment is a DONE token with the DONE_ATTN(0x0020) bit set.
*/
while (tdsReader.getCommand().attentionPending() && (TDS.TDS_DONE != tdsReader.peekTokenType())
&& (0 != (tdsReader.peekStatusFlag() & 0x0020))) {
remainingPackets = tdsReader.availableCurrentPacket();
tdsReader.skip(remainingPackets);
}
tdsReader.getCommand().close();
}
}
});
private final TDSType tdsType;
private final Strategy strategy;
private interface Strategy {
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException;
}
private static final class FixedLenStrategy implements Strategy {
private final SSType ssType;
private final int maxLength;
private final int precision;
private final int displaySize;
private final int scale;
FixedLenStrategy(SSType ssType,
int maxLength,
int precision,
int displaySize,
int scale) {
this.ssType = ssType;
this.maxLength = maxLength;
this.precision = precision;
this.displaySize = displaySize;
this.scale = scale;
}
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) {
typeInfo.ssLenType = SSLenType.FIXEDLENTYPE;
typeInfo.ssType = ssType;
typeInfo.maxLength = maxLength;
typeInfo.precision = precision;
typeInfo.displaySize = displaySize;
typeInfo.scale = scale;
}
}
private static final class DecimalNumericStrategy implements Strategy {
private final SSType ssType;
DecimalNumericStrategy(SSType ssType) {
this.ssType = ssType;
}
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
int maxLength = tdsReader.readUnsignedByte();
int precision = tdsReader.readUnsignedByte();
int scale = tdsReader.readUnsignedByte();
if (maxLength > 17)
tdsReader.throwInvalidTDS();
typeInfo.ssLenType = SSLenType.BYTELENTYPE;
typeInfo.ssType = ssType;
typeInfo.maxLength = maxLength;
typeInfo.precision = precision;
typeInfo.displaySize = precision + 2;
typeInfo.scale = scale;
}
}
private static final class BigOrSmallByteLenStrategy implements Strategy {
private final Builder bigBuilder;
private final Builder smallBuilder;
BigOrSmallByteLenStrategy(Builder bigBuilder,
Builder smallBuilder) {
this.bigBuilder = bigBuilder;
this.smallBuilder = smallBuilder;
}
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
switch (tdsReader.readUnsignedByte()) // maxLength
{
case 8:
bigBuilder.build(typeInfo, tdsReader);
break;
case 4:
smallBuilder.build(typeInfo, tdsReader);
break;
default:
tdsReader.throwInvalidTDS();
break;
}
typeInfo.ssLenType = SSLenType.BYTELENTYPE;
}
}
private static final class KatmaiScaledTemporalStrategy implements Strategy {
private final SSType ssType;
KatmaiScaledTemporalStrategy(SSType ssType) {
this.ssType = ssType;
}
private int getPrecision(String baseFormat,
int scale) {
// For 0-scale temporal, there is no '.' after the seconds component because there are no sub-seconds.
// Example: 12:34:56.12134 includes a '.', but 12:34:56 doesn't
return baseFormat.length() + ((scale > 0) ? (1 + scale) : 0);
}
/**
* Sets the fields of typeInfo to the correct values
*
* @param typeInfo
* the TypeInfo whos values are being corrected
* @param tdsReader
* the TDSReader used to set the fields of typeInfo to the correct values
* @throws SQLServerException
* when an error occurs
*/
public void apply(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
typeInfo.scale = tdsReader.readUnsignedByte();
if (typeInfo.scale > TDS.MAX_FRACTIONAL_SECONDS_SCALE)
tdsReader.throwInvalidTDS();
switch (ssType) {
case TIME:
typeInfo.precision = getPrecision("hh:mm:ss", typeInfo.scale);
typeInfo.maxLength = TDS.timeValueLength(typeInfo.scale);
break;
case DATETIME2:
typeInfo.precision = getPrecision("yyyy-mm-dd hh:mm:ss", typeInfo.scale);
typeInfo.maxLength = TDS.datetime2ValueLength(typeInfo.scale);
break;
case DATETIMEOFFSET:
typeInfo.precision = getPrecision("yyyy-mm-dd hh:mm:ss +HH:MM", typeInfo.scale);
typeInfo.maxLength = TDS.datetimeoffsetValueLength(typeInfo.scale);
break;
default:
assert false : "Unexpected SSType: " + ssType;
}
typeInfo.ssLenType = SSLenType.BYTELENTYPE;
typeInfo.ssType = ssType;
typeInfo.displaySize = typeInfo.precision;
}
}
private Builder(TDSType tdsType,
Strategy strategy) {
this.tdsType = tdsType;
this.strategy = strategy;
}
final TDSType getTDSType() {
return tdsType;
}
final TypeInfo build(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
strategy.apply(typeInfo, tdsReader);
// Postcondition: SSType and SSLenType are initialized
assert null != typeInfo.ssType;
assert null != typeInfo.ssLenType;
return typeInfo;
}
}
/**
* Returns true if this type is a textual type with a single-byte character set that is compatible with the 7-bit US-ASCII character set.
*/
boolean supportsFastAsciiConversion() {
switch (ssType) {
case CHAR:
case VARCHAR:
case VARCHARMAX:
case TEXT:
return collation.hasAsciiCompatibleSBCS();
default:
return false;
}
}
private static final Map<TDSType, Builder> builderMap = new EnumMap<TDSType, Builder>(TDSType.class);
static {
for (Builder builder : Builder.values())
builderMap.put(builder.getTDSType(), builder);
}
private TypeInfo() {
}
static TypeInfo getInstance(TDSReader tdsReader,
boolean readFlags) throws SQLServerException {
TypeInfo typeInfo = new TypeInfo();
// UserType is USHORT in TDS 7.1 and earlier; ULONG in TDS 7.2 and later.
typeInfo.userType = tdsReader.readInt();
if (readFlags) {
// Flags (2 bytes)
typeInfo.flags = tdsReader.readShort();
}
TDSType tdsType = null;
try {
tdsType = TDSType.valueOf(tdsReader.readUnsignedByte());
}
catch (IllegalArgumentException e) {
tdsReader.getConnection().terminate(SQLServerException.DRIVER_ERROR_INVALID_TDS, e.getMessage(), e);
// not reached
}
assert null != builderMap.get(tdsType) : "Missing TypeInfo builder for TDSType " + tdsType;
return builderMap.get(tdsType).build(typeInfo, tdsReader);
}
}
/**
* DTV implementation for values set from the TDS response stream.
*/
final class ServerDTVImpl extends DTVImpl {
private int valueLength;
private TDSReaderMark valueMark;
private boolean isNull;
/**
* Sets the value of the DTV to an app-specified Java type.
*
* Generally, the value cannot be stored back into the TDS byte stream (although this could be done for fixed-length types). So this
* implementation sets the new value in a new AppDTVImpl instance.
*/
void setValue(DTV dtv,
SQLCollation collation,
JDBCType jdbcType,
Object value,
JavaType javaType,
StreamSetterArgs streamSetterArgs,
Calendar cal,
Integer scale,
SQLServerConnection con,
boolean forceEncrypt) throws SQLServerException {
dtv.setImpl(new AppDTVImpl());
dtv.setValue(collation, jdbcType, value, javaType, streamSetterArgs, cal, scale, con, forceEncrypt);
}
void setValue(Object value,
JavaType javaType) {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
}
private final static int STREAMCONSUMED = -2;
// This function is used by Adaptive stream objects to denote that the
// whole value of the stream has been consumed.
// Note this only to be used by the streams returned to the user.
void setPositionAfterStreamed(TDSReader tdsReader) {
valueMark = tdsReader.mark();
valueLength = STREAMCONSUMED;
}
void setStreamSetterArgs(StreamSetterArgs streamSetterArgs) {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
}
void setCalendar(Calendar calendar) {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
}
void setScale(Integer scale) {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
}
void setForceEncrypt(boolean forceEncrypt) {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
}
StreamSetterArgs getStreamSetterArgs() {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
return null;
}
Calendar getCalendar() {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
return null;
}
Integer getScale() {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
return null;
}
boolean isNull() {
return isNull;
}
void setJdbcType(JDBCType jdbcType) {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
}
JDBCType getJdbcType() {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
return JDBCType.UNKNOWN;
}
JavaType getJavaType() {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
return JavaType.OBJECT;
}
// used to set null value
// for the DTV when a null value is
// received from NBCROW for a particular column
final void initFromCompressedNull() {
assert valueMark == null;
isNull = true;
}
final void skipValue(TypeInfo type,
TDSReader tdsReader,
boolean isDiscard) throws SQLServerException {
// indicates that this value was obtained from NBCROW
// So, there is nothing else to read from the wire
if (null == valueMark && isNull) {
return;
}
if (null == valueMark)
getValuePrep(type, tdsReader);
tdsReader.reset(valueMark);
// value length zero means that the stream has been already skipped to the end - adaptive case
if (valueLength != STREAMCONSUMED) {
if (valueLength == DataTypes.UNKNOWN_STREAM_LENGTH) {
assert SSLenType.PARTLENTYPE == type.getSSLenType();
// create a plp type and close it so the value can be skipped.
// We buffer even when adaptive if the user skips this item.
PLPInputStream tempPLP = PLPInputStream.makeTempStream(tdsReader, isDiscard, this);
try {
if (null != tempPLP)
tempPLP.close();
}
catch (IOException e) {
tdsReader.getConnection().terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage());
}
}
else {
assert valueLength >= 0;
tdsReader.skip(valueLength); // jump over the value data
}
}
}
static final private java.util.logging.Logger aeLogger = java.util.logging.Logger.getLogger("com.microsoft.sqlserver.jdbc.DTV");
private void getValuePrep(TypeInfo typeInfo,
TDSReader tdsReader) throws SQLServerException {
// If we've already seen this value before, then we shouldn't be here.
assert null == valueMark;
// Otherwise, mark the value's location, figure out its length, and determine whether it was NULL.
switch (typeInfo.getSSLenType()) {
case PARTLENTYPE:
valueLength = DataTypes.UNKNOWN_STREAM_LENGTH;
isNull = PLPInputStream.isNull(tdsReader);
break;
case FIXEDLENTYPE:
valueLength = typeInfo.getMaxLength();
isNull = (0 == valueLength);
break;
case BYTELENTYPE:
valueLength = tdsReader.readUnsignedByte();
isNull = (0 == valueLength);
break;
case USHORTLENTYPE:
valueLength = tdsReader.readUnsignedShort();
isNull = (65535 == valueLength);
if (isNull)
valueLength = 0;
break;
case LONGLENTYPE:
if (SSType.TEXT == typeInfo.getSSType() || SSType.IMAGE == typeInfo.getSSType() || SSType.NTEXT == typeInfo.getSSType()) {
isNull = (0 == tdsReader.readUnsignedByte());
if (isNull) {
valueLength = 0;
}
else {
// skip(24) is to skip the textptr and timestamp fields (Section 2.2.7.17 of TDS 7.3 spec)
tdsReader.skip(24);
valueLength = tdsReader.readInt();
}
}
else {
valueLength = tdsReader.readInt();
isNull = (0 == valueLength);
}
break;
}
if (valueLength > typeInfo.getMaxLength())
tdsReader.throwInvalidTDS();
valueMark = tdsReader.mark();
}
Object denormalizedValue(byte[] decryptedValue,
JDBCType jdbcType,
TypeInfo baseTypeInfo,
SQLServerConnection con,
InputStreamGetterArgs streamGetterArgs,
byte normalizeRuleVersion,
Calendar cal) throws SQLServerException {
if (0x01 != normalizeRuleVersion) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_UnsupportedNormalizationVersionAE"));
throw new SQLServerException(form.format(new Object[] {normalizeRuleVersion, 1}), null, 0, null);
}
if (aeLogger.isLoggable(java.util.logging.Level.FINE)) {
aeLogger.fine(
"Denormalizing decrypted data based on its SQL Server type(" + baseTypeInfo.getSSType() + ") and JDBC type(" + jdbcType + ").");
}
SSType baseSSType = baseTypeInfo.getSSType();
switch (baseSSType) {
case CHAR:
case VARCHAR:
case NCHAR:
case NVARCHAR:
case VARCHARMAX:
case NVARCHARMAX: {
try {
String strVal = new String(decryptedValue, 0, decryptedValue.length,
(null == baseTypeInfo.getCharset()) ? con.getDatabaseCollation().getCharset() : baseTypeInfo.getCharset());
if ((SSType.CHAR == baseSSType) || (SSType.NCHAR == baseSSType)) {
// Right pad the string for CHAR types.
StringBuilder sb = new StringBuilder(strVal);
int padLength = baseTypeInfo.getPrecision() - strVal.length();
for (int i = 0; i < padLength; i++) {
sb.append(' ');
}
strVal = sb.toString();
}
return DDC.convertStringToObject(strVal, baseTypeInfo.getCharset(), jdbcType, streamGetterArgs.streamType);
}
catch (IllegalArgumentException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
throw new SQLServerException(form.format(new Object[] {baseSSType, jdbcType}), null, 0, e);
}
catch (UnsupportedEncodingException e) {
// Important: we should not pass the exception here as it displays the data.
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedEncoding"));
throw new SQLServerException(form.format(new Object[] {baseTypeInfo.getCharset()}), null, 0, e);
}
}
case BIT:
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT: {
// If data is encrypted, then these types are normalized to BIGINT. Need to denormalize here.
if (8 != decryptedValue.length) {
// Integer datatypes are normalized to bigint for AE.
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
return DDC.convertLongToObject(Util.readLong(decryptedValue, 0), jdbcType, baseSSType, streamGetterArgs.streamType);
}
case REAL:
case FLOAT: {
// JDBC driver does not normalize real to float.
if (8 == decryptedValue.length) {
return DDC.convertDoubleToObject(ByteBuffer.wrap(decryptedValue).order(ByteOrder.LITTLE_ENDIAN).getDouble(),
JDBCType.VARBINARY == jdbcType ? baseSSType.getJDBCType() : jdbcType, // use jdbc type from baseTypeInfo if using
// getObject()
streamGetterArgs.streamType);
}
else if (4 == decryptedValue.length) {
return DDC.convertFloatToObject(ByteBuffer.wrap(decryptedValue).order(ByteOrder.LITTLE_ENDIAN).getFloat(),
JDBCType.VARBINARY == jdbcType ? baseSSType.getJDBCType() : jdbcType, // use jdbc type from baseTypeInfo if using
// getObject()
streamGetterArgs.streamType);
}
else {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
}
case SMALLMONEY: {
return DDC.convertMoneyToObject(new BigDecimal(BigInteger.valueOf(Util.readInt(decryptedValue, 4)), 4),
JDBCType.VARBINARY == jdbcType ? baseSSType.getJDBCType() : jdbcType, // use jdbc type from baseTypeInfo if using getObject()
streamGetterArgs.streamType, 4);
}
case MONEY: {
BigInteger bi = BigInteger.valueOf(((long) Util.readInt(decryptedValue, 0) << 32) | (Util.readInt(decryptedValue, 4) & 0xFFFFFFFFL));
return DDC.convertMoneyToObject(new BigDecimal(bi, 4), JDBCType.VARBINARY == jdbcType ? baseSSType.getJDBCType() : jdbcType, // use
// jdbc
// type
// from
// baseTypeInfo
// using
// getObject()
streamGetterArgs.streamType, 8);
}
case NUMERIC:
case DECIMAL: {
return DDC.convertBigDecimalToObject(Util.readBigDecimal(decryptedValue, decryptedValue.length, baseTypeInfo.getScale()),
JDBCType.VARBINARY == jdbcType ? baseSSType.getJDBCType() : jdbcType, // use jdbc type from baseTypeInfo if using getObject()
streamGetterArgs.streamType);
}
case BINARY:
case VARBINARY:
case VARBINARYMAX: {
return DDC.convertBytesToObject(decryptedValue, jdbcType, baseTypeInfo);
}
case DATE: {
// get the number of days !! Size should be 3
if (3 != decryptedValue.length) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
// Getting number of days
// Following Lines of code copied from IOBuffer.readDaysIntoCE as we
// cannot reuse method
int daysIntoCE = getDaysIntoCE(decryptedValue, baseSSType);
return DDC.convertTemporalToObject(jdbcType, baseSSType, cal, daysIntoCE, 0, 0);
}
case TIME: {
long localNanosSinceMidnight = readNanosSinceMidnightAE(decryptedValue, baseTypeInfo.getScale(), baseSSType);
return DDC.convertTemporalToObject(jdbcType, SSType.TIME, cal, 0, localNanosSinceMidnight, baseTypeInfo.getScale());
}
case DATETIME2: {
if (8 != decryptedValue.length) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
// Last three bytes are for date and remaining for time
int dateOffset = decryptedValue.length - 3;
byte[] timePortion = new byte[dateOffset];
byte[] datePortion = new byte[3];
System.arraycopy(decryptedValue, 0, timePortion, 0, dateOffset);
System.arraycopy(decryptedValue, dateOffset, datePortion, 0, 3);
long localNanosSinceMidnight = readNanosSinceMidnightAE(timePortion, baseTypeInfo.getScale(), baseSSType);
int daysIntoCE = getDaysIntoCE(datePortion, baseSSType);
// Convert the DATETIME2 value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME2, cal, daysIntoCE, localNanosSinceMidnight, baseTypeInfo.getScale());
}
case SMALLDATETIME: {
if (4 != decryptedValue.length) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
// SQL smalldatetime has less precision. It stores 2 bytes
// for the days since SQL Base Date and 2 bytes for minutes
// after midnight.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME, cal, Util.readUnsignedShort(decryptedValue, 0),
Util.readUnsignedShort(decryptedValue, 2) * 60L * 1000L, 0);
}
case DATETIME: {
if (8 != decryptedValue.length) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
// SQL datetime is 4 bytes for days since SQL Base Date
// (January 1, 1900 00:00:00 GMT) and 4 bytes for
// the number of three hundredths (1/300) of a second since midnight.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME, cal, Util.readInt(decryptedValue, 0),
(Util.readInt(decryptedValue, 4) * 10 + 1) / 3, 0);
}
case DATETIMEOFFSET: {
// Last 5 bytes are for date and offset
int dateOffset = decryptedValue.length - 5;
byte[] timePortion = new byte[dateOffset];
byte[] datePortion = new byte[3];
byte[] offsetPortion = new byte[2];
System.arraycopy(decryptedValue, 0, timePortion, 0, dateOffset);
System.arraycopy(decryptedValue, dateOffset, datePortion, 0, 3);
System.arraycopy(decryptedValue, dateOffset + 3, offsetPortion, 0, 2);
long localNanosSinceMidnight = readNanosSinceMidnightAE(timePortion, baseTypeInfo.getScale(), baseSSType);
int daysIntoCE = getDaysIntoCE(datePortion, baseSSType);
int localMinutesOffset = ByteBuffer.wrap(offsetPortion).order(ByteOrder.LITTLE_ENDIAN).getShort();
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIMEOFFSET,
new GregorianCalendar(new SimpleTimeZone(localMinutesOffset * 60 * 1000, ""), Locale.US), daysIntoCE, localNanosSinceMidnight,
baseTypeInfo.getScale());
}
case GUID: {
return Util.readGUID(decryptedValue);
}
default:
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_UnsupportedDataTypeAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
}
Object getValue(DTV dtv,
JDBCType jdbcType,
int scale,
InputStreamGetterArgs streamGetterArgs,
Calendar cal,
TypeInfo typeInfo,
CryptoMetadata cryptoMetadata,
TDSReader tdsReader) throws SQLServerException {
SQLServerConnection con = tdsReader.getConnection();
Object convertedValue = null;
byte[] decryptedValue;
boolean encrypted = false;
SSType baseSSType = typeInfo.getSSType();
// If column encryption is not enabled on connection or on statement, cryptoMeta will be null.
if (null != cryptoMetadata) {
assert (SSType.VARBINARY == typeInfo.getSSType()) || (SSType.VARBINARYMAX == typeInfo.getSSType()) ;
baseSSType = cryptoMetadata.baseTypeInfo.getSSType();
encrypted = true;
if (aeLogger.isLoggable(java.util.logging.Level.FINE)) {
aeLogger.fine("Data is encrypted, SQL Server Data Type: " + baseSSType + ", Encryption Type: " + cryptoMetadata.getEncryptionType());
}
}
// Note that the value should be prepped
// only for columns whose values can be read of the wire.
// If valueMark == null and isNull, it implies that
// the column is null according to NBCROW and that
// there is nothing to be read from the wire.
if (null == valueMark && (!isNull))
getValuePrep(typeInfo, tdsReader);
// either there should be a valueMark
// or valueMark should be null and isNull should be set to true(NBCROW case)
assert ((valueMark != null) || (valueMark == null && isNull));
if (null != streamGetterArgs) {
if (!streamGetterArgs.streamType.convertsFrom(typeInfo))
DataTypes.throwConversionError(typeInfo.getSSType().toString(), streamGetterArgs.streamType.toString());
}
else {
if (!baseSSType.convertsTo(jdbcType)) {
// if the baseSSType is Character or NCharacter and jdbcType is Longvarbinary,
// does not throw type conversion error, which allows getObject() on Long Character types.
if (encrypted) {
if (!Util.isBinaryType(jdbcType.getIntValue())) {
DataTypes.throwConversionError(baseSSType.toString(), jdbcType.toString());
}
}
else {
DataTypes.throwConversionError(baseSSType.toString(), jdbcType.toString());
}
}
streamGetterArgs = InputStreamGetterArgs.getDefaultArgs();
}
if (STREAMCONSUMED == valueLength) {
throw new SQLServerException(null, SQLServerException.getErrString("R_dataAlreadyAccessed"), null, 0, false);
}
if (!isNull) {
tdsReader.reset(valueMark);
if (encrypted) {
if (DataTypes.UNKNOWN_STREAM_LENGTH == valueLength) {
convertedValue = DDC.convertStreamToObject(PLPInputStream.makeStream(tdsReader, streamGetterArgs, this), typeInfo,
JDBCType.VARBINARY, streamGetterArgs);
}
else {
convertedValue = DDC.convertStreamToObject(new SimpleInputStream(tdsReader, valueLength, streamGetterArgs, this), typeInfo,
JDBCType.VARBINARY, streamGetterArgs);
}
if (aeLogger.isLoggable(java.util.logging.Level.FINE)) {
aeLogger.fine("Encrypted data is retrieved.");
}
// AE does not support streaming types
if ((convertedValue instanceof SimpleInputStream) || (convertedValue instanceof PLPInputStream)) {
throw new SQLServerException(SQLServerException.getErrString("R_notSupported"), null);
}
decryptedValue = SQLServerSecurityUtility.decryptWithKey((byte[]) convertedValue, cryptoMetadata, con);
return denormalizedValue(decryptedValue, jdbcType, cryptoMetadata.baseTypeInfo, con, streamGetterArgs,
cryptoMetadata.normalizationRuleVersion, cal);
}
switch (baseSSType) {
// Process all PLP types here.
case VARBINARYMAX:
case VARCHARMAX:
case NVARCHARMAX:
case UDT: {
convertedValue = DDC.convertStreamToObject(PLPInputStream.makeStream(tdsReader, streamGetterArgs, this), typeInfo, jdbcType,
streamGetterArgs);
break;
}
case XML: {
convertedValue = DDC.convertStreamToObject(
((jdbcType.isBinary() || jdbcType == JDBCType.SQLXML) ? PLPXMLInputStream.makeXMLStream(tdsReader, streamGetterArgs, this)
: PLPInputStream.makeStream(tdsReader, streamGetterArgs, this)),
typeInfo, jdbcType, streamGetterArgs);
break;
}
// Convert other variable length native types
// (CHAR/VARCHAR/TEXT/NCHAR/NVARCHAR/NTEXT/BINARY/VARBINARY/IMAGE) -> ANY jdbcType.
case CHAR:
case VARCHAR:
case TEXT:
case NCHAR:
case NVARCHAR:
case NTEXT:
case IMAGE:
case BINARY:
case VARBINARY:
case TIMESTAMP: // A special BINARY(8)
{
convertedValue = DDC.convertStreamToObject(new SimpleInputStream(tdsReader, valueLength, streamGetterArgs, this), typeInfo,
jdbcType, streamGetterArgs);
break;
}
// Convert BIT/TINYINT/SMALLINT/INTEGER/BIGINT native type -> ANY jdbcType.
case BIT:
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT: {
switch (valueLength) {
case 8:
convertedValue = DDC.convertLongToObject(tdsReader.readLong(), jdbcType, baseSSType, streamGetterArgs.streamType);
break;
case 4:
convertedValue = DDC.convertIntegerToObject(tdsReader.readInt(), valueLength, jdbcType, streamGetterArgs.streamType);
break;
case 2:
convertedValue = DDC.convertIntegerToObject(tdsReader.readShort(), valueLength, jdbcType, streamGetterArgs.streamType);
break;
case 1:
convertedValue = DDC.convertIntegerToObject(tdsReader.readUnsignedByte(), valueLength, jdbcType,
streamGetterArgs.streamType);
break;
default:
assert false : "Unexpected valueLength" + valueLength;
break;
}
break;
}
// Convert DECIMAL|NUMERIC native types -> ANY jdbcType.
case DECIMAL:
case NUMERIC:
convertedValue = tdsReader.readDecimal(valueLength, typeInfo, jdbcType, streamGetterArgs.streamType);
break;
// Convert MONEY|SMALLMONEY native types -> ANY jdbcType.
case MONEY:
case SMALLMONEY:
convertedValue = tdsReader.readMoney(valueLength, jdbcType, streamGetterArgs.streamType);
break;
// Convert FLOAT native type -> ANY jdbcType.
case FLOAT:
convertedValue = tdsReader.readFloat(valueLength, jdbcType, streamGetterArgs.streamType);
break;
// Convert REAL native type -> ANY jdbcType.
case REAL:
convertedValue = tdsReader.readReal(valueLength, jdbcType, streamGetterArgs.streamType);
break;
// Convert DATETIME|SMALLDATETIME native types -> ANY jdbcType.
case DATETIME:
case SMALLDATETIME:
convertedValue = tdsReader.readDateTime(valueLength, cal, jdbcType, streamGetterArgs.streamType);
break;
// Convert DATE native type -> ANY jdbcType.
case DATE:
convertedValue = tdsReader.readDate(valueLength, cal, jdbcType);
break;
// Convert TIME native type -> ANY jdbcType.
case TIME:
convertedValue = tdsReader.readTime(valueLength, typeInfo, cal, jdbcType);
break;
// Convert DATETIME2 native type -> ANY jdbcType.
case DATETIME2:
convertedValue = tdsReader.readDateTime2(valueLength, typeInfo, cal, jdbcType);
break;
// Convert DATETIMEOFFSET native type -> ANY jdbcType.
case DATETIMEOFFSET:
convertedValue = tdsReader.readDateTimeOffset(valueLength, typeInfo, jdbcType);
break;
// Convert GUID native type -> ANY jdbcType.
case GUID:
convertedValue = tdsReader.readGUID(valueLength, jdbcType, streamGetterArgs.streamType);
break;
// Unknown SSType should have already been rejected by TypeInfo.setFromTDS()
default:
assert false : "Unexpected SSType " + typeInfo.getSSType();
break;
}
} // !isNull
// Postcondition: returned object is null only if value was null.
assert isNull || null != convertedValue;
return convertedValue;
}
Object getSetterValue() {
// This function is never called, but must be implemented; it's abstract in DTVImpl.
assert false;
return null;
}
private long readNanosSinceMidnightAE(byte[] value,
int scale,
SSType baseSSType) throws SQLServerException {
long hundredNanosSinceMidnight = 0;
for (int i = 0; i < value.length; i++)
hundredNanosSinceMidnight |= (value[i] & 0xFFL) << (8 * i);
if (!(0 <= hundredNanosSinceMidnight && hundredNanosSinceMidnight < Nanos.PER_DAY / 100)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
return 100 * hundredNanosSinceMidnight;
}
private int getDaysIntoCE(byte[] datePortion,
SSType baseSSType) throws SQLServerException {
int daysIntoCE = 0;
for (int i = 0; i < datePortion.length; i++) {
daysIntoCE |= ((datePortion[i] & 0xFF) << (8 * i));
}
if (daysIntoCE < 0) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NormalizationErrorAE"));
throw new SQLServerException(form.format(new Object[] {baseSSType}), null, 0, null);
}
return daysIntoCE;
}
} |
package com.minelittlepony.client;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.event.client.ClientTickCallback;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import com.minelittlepony.client.gui.hdskins.MineLPHDSkins;
import com.minelittlepony.common.client.IModUtilities;
import javax.annotation.Nullable;
public class FabMod implements ClientModInitializer, ClientTickCallback, IModUtilities {
@Nullable
private MineLPClient mlp;
private boolean firstTick = true;
@Override
public void onInitializeClient() {
ClientTickCallback.EVENT.register(this);
if (FabricLoader.getInstance().isModLoaded("hdskins")) {
mlp = new MineLPHDSkins(this);
} else {
mlp = new MineLPClient(this);
}
}
@Override
public void tick(MinecraftClient client) {
if (mlp == null) {
return;
}
if (firstTick) {
firstTick = false;
mlp.postInit(client);
} else {
mlp.onTick(client, client.world != null && client.player != null);
}
}
} |
package org.jeffpiazza.derby.gui;
import jssc.SerialPort;
import org.jeffpiazza.derby.*;
import org.jeffpiazza.derby.devices.TimerDevice;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.jeffpiazza.derby.devices.TimerTask;
// On the HTTP side, the GUI makes this approximate progression:
// (obtain URL for web server)
// (contact web server and get roles)
// (choose role and password)
// (login and start HttpTask)
// Command-line arguments may let us skip some of these steps.
public class TimerGui {
private Components components;
private HttpTask.MessageTracer traceMessages;
private HttpTask.MessageTracer traceHeartbeats;
private Connector connector;
private RoleFinder roleFinder;
private boolean rolesPopulated = false;
private TimerClassListController timerClassListController;
private SerialPortListController portListController;
public TimerGui(HttpTask.MessageTracer traceMessages,
HttpTask.MessageTracer traceHeartbeats,
Connector connector) {
this.components = new Components();
this.connector = connector;
this.traceMessages = traceMessages;
this.traceHeartbeats = traceHeartbeats;
timerClassListController = new TimerClassListController(
components.timerClassList);
components.timerClassList.addListSelectionListener(timerClassListController);
portListController = new SerialPortListController(components.portList);
components.portList.addListSelectionListener(portListController);
}
public void show() {
components.setTitle("Derby Timer Management");
components.getRootPane().setDefaultButton(components.connectButton);
components.httpIconStatus.setIcon(new ImageIcon(getClass().getResource(
"/status/trouble.png")));
components.serialIconStatus.setIcon(new ImageIcon(getClass().
getResource("/status/unknown.png")));
components.portList.setCellRenderer(new SerialPortListRenderer());
components.connectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TimerGui.this.onConnectButtonClick();
}
});
components.scanButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TimerGui.this.onScanButtonClick();
}
});
components.pack();
components.setVisible(true);
}
// If connection details were entered on the command line, use them to
// prefill the corresponding GUI fields, and then treat as though user
// performed equivalent interaction. If all details provided, call
// setUrl before setRoleAndPassword.
public void setUrl(String url) {
components.urlField.setText(url);
onConnectButtonClick();
}
public void setRoleAndPassword(String role, String password) {
components.roleComboBox.setSelectedItem(role);
components.passwordField.setText(password);
(new Thread() {
@Override
public void run() {
// Wait for RoleFinder to finish populating roles. If there's no
// RoleFinder, then give up (there's no URL, or the RoleFinder failed).
while (!rolesPopulated()) {
if (getRoleFinder() == null) {
return;
}
synchronized (TimerGui.this) {
try {
TimerGui.this.wait();
} catch (InterruptedException ex) {
}
}
}
startHttpTask(getRoleFinder().getSession());
}
}).start();
}
// This is mainly used to introduce a SimulatedClientSession and skip all the
// communication with an actual server.
public void setClientSession(ClientSession session) {
startHttpTask(session);
}
private synchronized RoleFinder getRoleFinder() {
return roleFinder;
}
private synchronized void setRoleFinder(RoleFinder roleFinder) {
this.roleFinder = roleFinder;
}
private synchronized boolean rolesPopulated() {
return rolesPopulated;
}
private synchronized void setRolesPopulated(boolean rolesPopulated) {
this.rolesPopulated = rolesPopulated;
this.notifyAll();
}
private static Color green = new Color(52, 127, 79);
private static Color black = Color.BLACK;
private static Color red = Color.RED;
private static Color defaultBackground = new Color(184, 207, 229);
public void setHttpStatus(String message, Color color) {
components.httpStatusLabel.setForeground(color);
components.httpStatusLabel.setText(message);
}
// Status icons should be one of: "ok", "trouble", "unknown".
// Check the build file for where these icons come from, and to change the
// available choices.
public static String icon_ok = "ok";
public static String icon_trouble = "trouble";
public static String icon_unknown = "unknown";
public void setHttpStatus(String message, Color color, String icon) {
setHttpStatus(message, color);
components.httpIconStatus.setIcon(new ImageIcon(getClass().getResource(
"/status/" + icon + ".png")));
}
public void setSerialStatus(String message) {
components.serialStatusLabel.setText(message);
}
public void setSerialStatus(String message, Color color) {
components.serialStatusLabel.setForeground(color);
setSerialStatus(message);
}
public void setSerialStatus(String message, Color color, String icon) {
setSerialStatus(message, color);
components.serialIconStatus.setIcon(new ImageIcon(getClass().
getResource("/status/" + icon + ".png")));
}
// Runs on dispatch thread; no individual invocation can be long-running.
// The first click of the button will launch a RoleFinder in a separate
// thread, which attempts to contact the server and obtain a list of valid
// roles. A second click is detectable by the existence of a RoleFinder
// already created for the current url
private void onConnectButtonClick() {
RoleFinder roleFinder = getRoleFinder();
if (roleFinder != null && !roleFinder.getServerAddress().equals(
components.urlField.getText())) {
// Cancel existing rolefinder
roleFinder.cancel();
setRoleFinder(null);
}
if (roleFinder == null) {
setHttpStatus("Contacting server...", black, icon_unknown);
components.roleComboBox.setEnabled(false);
components.passwordField.setEnabled(false);
startRoleFinder();
} else // There's an existing roleFinder for the current URL, and the user
// clicked "Connect." If we're still waiting for the roles to
// populate, then ignore the button, otherwise start a login request
if (rolesPopulated()) {
startHttpTask(roleFinder.getSession());
} else {
setHttpStatus("(Hold your horses)", black, icon_unknown);
}
}
// Start a separate thread to contact the server and ask it for the available
// roles; use the results to populate the role picker.
private void startRoleFinder() {
setRoleFinder(new RoleFinder(components.urlField.getText(), this));
setRolesPopulated(false);
(new Thread() {
@Override
public void run() {
getRoleFinder().findRoles();
}
}).start();
}
private void startHttpTask(ClientSession clientSession) {
setHttpStatus("Logging in...", black, icon_unknown);
HttpTask.start(components.roleComboBox.getItemAt(
components.roleComboBox.getSelectedIndex()),
new String(components.passwordField.getPassword()),
clientSession, traceMessages, traceHeartbeats,
connector,
new HttpTask.LoginCallback() {
@Override
public void onLoginSuccess() {
setHttpStatus("Connected", green, icon_ok);
}
@Override
public void onLoginFailed(String message) {
setHttpStatus("Unsuccessful login", red, icon_trouble);
}
});
}
// Called once for each role to be added to the role combobox. After the last role is added,
// call rolesComplete()
public void addRole(String role) {
components.roleComboBox.addItem(role);
}
// Called to signify that all the appropriate roles from the server have
// been added to the role combobox
public synchronized void rolesComplete() {
setRolesPopulated(true);
// Try logging in to the first role with an empty password -- almost always
// works, and makes for one less thing for the operator to have to do.
onConnectButtonClick();
setHttpStatus("Please log in", black, icon_unknown);
components.roleComboBox.setEnabled(true);
components.passwordField.setEnabled(true);
components.passwordField.requestFocus();
}
public synchronized void roleFinderFailed(String message) {
setHttpStatus(message, red, icon_trouble);
roleFinder = null;
}
public void updateSerialPorts(TimerTask timerTask, String[] portNames) {
portListController.updateSerialPorts(timerTask, portNames);
}
public void setSerialPort(String portName) {
portListController.setSerialPort(portName);
}
public void markSerialPortWontOpen() {
portListController.markSerialPortWontOpen();
}
public void updateTimerClasses(TimerTask timerTask, Class<? extends TimerDevice>[] timerClasses) {
timerClassListController.updateTimerClasses(timerTask, timerClasses);
}
public void setTimerClass(Class<? extends TimerDevice> timerClass) {
timerClassListController.setTimerClass(timerClass);
}
private void onScanButtonClick() {
System.out.println("Scan/Stop Scanning button not implemented");
}
public void confirmDevice() {
components.portList.setSelectionBackground(green);
components.timerClassList.setSelectionBackground(green);
setSerialStatus("Timer device identified", green, icon_ok);
// TODO components.scanButton.setVisible(false);
}
// Remove selections between scan cycles
public void deselectAll() {
portListController.deselectAll();
components.portList.setSelectionBackground(defaultBackground);
timerClassListController.deselectAll();
components.timerClassList.setSelectionBackground(defaultBackground);
}
} |
package com.skelril.aurora.util;
import java.util.Calendar;
public class TimeUtil {
private static Calendar calendar = Calendar.getInstance();
/**
* Gets the ticks till the start of the next hour
*
* @return the number of ticks till the next hour
*/
public static long getTicksTillHour() {
Calendar localCalendar = Calendar.getInstance();
long returnValue;
localCalendar.set(Calendar.MINUTE, 0);
localCalendar.add(Calendar.HOUR_OF_DAY, 1);
returnValue = localCalendar.getTimeInMillis() - calendar.getTimeInMillis();
returnValue = (returnValue / 1000) * 20; // To Ticks
return returnValue;
}
/**
* Gets the ticks till a given base 24 hour
*
* @param hour The hour, for example 13 is 1 P.M.
* @return the number of ticks till the given time
*/
public static long getTicksTill(int hour) {
return getTicksTill(hour, -1);
}
/**
* Gets the ticks till a given base 24 hour on a day of the week
*
* @param hour The hour, for example 13 is 1 P.M.
* @param dayofweek The day, for example 7 is Saturday
* @return the number of ticks till the given time
*/
public static long getTicksTill(int hour, int dayofweek) {
Calendar localCalendar = Calendar.getInstance();
long returnValue;
localCalendar.set(Calendar.MINUTE, 0);
while (localCalendar.get(Calendar.HOUR_OF_DAY) != hour) {
localCalendar.add(Calendar.HOUR_OF_DAY, 1);
}
if (dayofweek != -1) {
while (localCalendar.get(Calendar.DAY_OF_WEEK) != dayofweek) {
localCalendar.add(Calendar.DAY_OF_WEEK, 1);
}
}
returnValue = localCalendar.getTimeInMillis() - calendar.getTimeInMillis();
returnValue = (returnValue / 1000) * 20; // To Ticks
return returnValue;
}
} |
package com.tale.service;
import com.blade.exception.ValidatorException;
import com.blade.ioc.annotation.Bean;
import com.blade.kit.BladeKit;
import com.blade.kit.DateKit;
import com.tale.bootstrap.TaleConst;
import com.tale.extension.Commons;
import com.tale.model.dto.Comment;
import com.tale.model.entity.Comments;
import com.tale.model.entity.Contents;
import com.tale.model.params.CommentParam;
import com.tale.utils.TaleUtils;
import com.vdurmont.emoji.EmojiParser;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;
import java.util.ArrayList;
import java.util.List;
import static com.tale.bootstrap.TaleConst.*;
import static io.github.biezhi.anima.Anima.select;
import static io.github.biezhi.anima.Anima.update;
/**
* Service
*
* @author biezhi
* @since 1.3.1
*/
@Bean
public class CommentsService {
/**
*
*
* @param comments
*/
public void saveComment(Comments comments) {
comments.setAuthor(TaleUtils.cleanXSS(comments.getAuthor()));
comments.setContent(TaleUtils.cleanXSS(comments.getContent()));
comments.setAuthor(EmojiParser.parseToAliases(comments.getAuthor()));
comments.setContent(EmojiParser.parseToAliases(comments.getContent()));
Contents contents = select().from(Contents.class).byId(comments.getCid());
if (null == contents) {
throw new ValidatorException("");
}
try {
comments.setOwnerId(contents.getAuthorId());
comments.setAuthorId(null == comments.getAuthorId() ? 0 : comments.getAuthorId());
comments.setCreated(DateKit.nowUnix());
comments.setParent(null == comments.getCoid() ? 0 : comments.getCoid());
comments.setCoid(null);
comments.save();
new Contents().set(Contents::getCommentsNum, contents.getCommentsNum() + 1).updateById(contents.getCid());
} catch (Exception e) {
throw e;
}
}
/**
*
*
* @param coid
* @param cid
* @throws Exception
*/
public void delete(Integer coid, Integer cid) {
Anima.delete().from(Comments.class).deleteById(coid);
Contents contents = select().from(Contents.class).byId(cid);
if (null != contents && contents.getCommentsNum() > 0) {
update().from(Contents.class).set(Contents::getCommentsNum, contents.getCommentsNum() - 1).updateById(cid);
}
}
/**
*
*
* @param cid
* @param page
* @param limit
* @return
*/
public Page<Comment> getComments(Integer cid, int page, int limit) {
if (null == cid) {
return null;
}
Page<Comments> commentsPage = select().from(Comments.class)
.where(Comments::getCid, cid).and(Comments::getParent, 0)
.and(Comments::getStatus, COMMENT_APPROVED)
.order(Comments::getCoid, OrderBy.DESC).page(page, limit);
return commentsPage.map(this::apply);
}
/**
*
*
* @param cid ID
*/
public long getCommentCount(Integer cid) {
if (null == cid) {
return 0;
}
return select().from(Comments.class).where(Comments::getCid, cid).count();
}
/**
*
*
* @param coid
* @return
*/
private void getChildren(List<Comments> list, Integer coid) {
List<Comments> cms = select().from(Comments.class).where(Comments::getParent, coid).order(Comments::getCoid, OrderBy.ASC).all();
if (null != cms) {
list.addAll(cms);
cms.forEach(c -> getChildren(list, c.getCoid()));
}
}
private Comment apply(Comments parent) {
Comment comment = new Comment(parent);
List<Comments> children = new ArrayList<>();
getChildren(children, comment.getCoid());
comment.setChildren(children);
if (BladeKit.isNotEmpty(children)) {
comment.setLevels(1);
}
return comment;
}
public Page<Comments> findComments(CommentParam commentParam) {
return select().from(Comments.class)
.order(Comments::getCoid, OrderBy.DESC)
.page(commentParam.getPage(), commentParam.getLimit());
}
} |
package com.tightdb.lib;
import com.tightdb.TableQuery;
public class LongRowsetColumn<Cursor, View, Query> extends LongQueryColumn<Cursor, View, Query> implements RowsetColumn<Long> {
public LongRowsetColumn(EntityTypes<?, View, Cursor, Query> types, IRowsetBase rowset, int index, String name) {
this(types, rowset, null, index, name);
}
public LongRowsetColumn(EntityTypes<?, View, Cursor, Query> types, IRowsetBase rowset, TableQuery query, int index, String name) {
super(types, rowset, query, index, name);
}
public long sum() {
return rowset.sum(columnIndex);
}
public long maximum() {
return rowset.maximum(columnIndex);
}
public long minimum() {
return rowset.minimum(columnIndex);
}
public double average() {
return rowset.average(columnIndex);
}
/*
public void setIndex() {
rowset.setIndex(columnIndex);
}
public boolean hasIndex() {
return rowset.hasIndex(columnIndex);
}
*/
@Override
public Long[] getAll() {
long count = rowset.size();
Long[] values = new Long[(int) count];
for (int i = 0; i < count; i++) {
values[i] = rowset.getLong(columnIndex, i);
}
return values;
}
@Override
public void setAll(Long value) {
long count = rowset.size();
for (int i = 0; i < count; i++) {
rowset.setLong(columnIndex, i, value);
}
}
public void setAll(long value) {
setAll(new Long(value));
}
public void addLong(long value) {
rowset.addLong(columnIndex, value);
}
public Cursor findFirst(long value) {
return cursor(rowset.findFirstLong(columnIndex, value));
}
public View findAll(long value) {
return view(rowset.findAllLong(columnIndex, value));
}
} |
package com.tinkerrocks.storage;
import com.tinkerrocks.structure.*;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class VertexDB extends StorageAbstractClass implements VertexStorage {
public void close() {
if (rocksDB != null)
this.rocksDB.close();
}
@SuppressWarnings("unchecked")
public <V> void setProperty(byte[] id, String key, V value, VertexProperty.Cardinality cardinality) {
byte[] record_key = Utils.merge(id, StorageConstants.PROPERTY_SEPARATOR, key.getBytes());
try {
if (cardinality == VertexProperty.Cardinality.single) {
put(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key, serialize(value));
put(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key, StorageConstants.V_PROPERTY_SINGLE_TYPE);
}
if (cardinality == VertexProperty.Cardinality.list || cardinality == VertexProperty.Cardinality.set) {
byte[] oldData = get(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key);
byte[] oldType = get(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key);
ArrayList<V> results;
if (!Utils.compare(oldType, StorageConstants.V_PROPERTY_LIST_TYPE)) {
results = new ArrayList<>();
} else {
results = (ArrayList<V>) deserialize(oldData, ArrayList.class);
}
if (cardinality == VertexProperty.Cardinality.set && results.contains(value)) {
return;
}
results.add(value);
put(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key, serialize(results));
put(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key, StorageConstants.V_PROPERTY_LIST_TYPE);
}
} catch (RocksDBException e) {
e.printStackTrace();
}
}
public void addEdge(byte[] vertexId, Edge edge, Vertex inVertex) throws RocksDBException {
byte[] insert_label = Utils.merge(StorageConstants.PROPERTY_SEPARATOR, edge.label().getBytes(), StorageConstants.PROPERTY_SEPARATOR);
put(getColumn(VERTEX_COLUMNS.OUT_EDGES), Utils.merge(vertexId,
insert_label, (byte[]) edge.id()), (byte[]) inVertex.id());
put(getColumn(VERTEX_COLUMNS.IN_EDGES), Utils.merge((byte[]) inVertex.id(),
insert_label, (byte[]) edge.id()), vertexId);
}
@SuppressWarnings("unchecked")
public <V> List<VertexProperty<V>> getProperties(RocksElement rocksVertex, List<byte[]> propertyKeys) throws Exception {
List<VertexProperty<V>> results = new LinkedList<>();
if (propertyKeys == null) {
propertyKeys = new ArrayList<>();
}
if (propertyKeys.size() == 0) {
RocksIterator rocksIterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.PROPERTIES));
byte[] seek_key = Utils.merge((byte[]) rocksVertex.id(), StorageConstants.PROPERTY_SEPARATOR);
final List<byte[]> finalPropertyKeys = propertyKeys;
Utils.RocksIterUtil(rocksIterator, seek_key, (key, value) -> {
if (value != null)
finalPropertyKeys.add(Utils.slice(key, seek_key.length, key.length));
return true;
});
}
for (byte[] property : propertyKeys) {
byte[] lookup_key = Utils.merge((byte[]) rocksVertex.id(), StorageConstants.PROPERTY_SEPARATOR, property);
byte[] type = get(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), lookup_key);
byte[] value = get(getColumn(VERTEX_COLUMNS.PROPERTIES), lookup_key);
if (Utils.compare(type, StorageConstants.V_PROPERTY_SINGLE_TYPE)) {
results.add(new RocksVertexProperty<>(rocksVertex, new String(property), (V) deserialize(value, Object.class)));
}
if (Utils.compare(type, StorageConstants.V_PROPERTY_LIST_TYPE)) {
List<V> values = deserialize(value, List.class);
results.addAll(values.stream().map(inner_value -> new RocksVertexProperty<>(rocksVertex, new String(property), inner_value))
.collect(Collectors.toList()));
}
}
return results;
}
public List<byte[]> getEdgeIDs(byte[] id, Direction direction, String[] edgeLabels) {
List<byte[]> edgeIds = new ArrayList<>();
RocksIterator iterator;
byte[] seek_key = Utils.merge(id, StorageConstants.PROPERTY_SEPARATOR);
try {
if (edgeLabels.length > 0) {
for (String edgeLabel : edgeLabels) {
byte[] inner_seek_key = Utils.merge(seek_key, edgeLabel.getBytes(), StorageConstants.PROPERTY_SEPARATOR);
if (direction == Direction.BOTH || direction == Direction.IN) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.IN_EDGES));
Utils.RocksIterUtil(iterator, inner_seek_key, (key, value) -> {
edgeIds.add(Utils.slice(key, inner_seek_key.length));
return true;
});
}
if (direction == Direction.BOTH || direction == Direction.OUT) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.OUT_EDGES));
Utils.RocksIterUtil(iterator, inner_seek_key, (key, value) -> {
edgeIds.add(Utils.slice(key, inner_seek_key.length));
return true;
});
}
}
return edgeIds;
}
if (direction == Direction.BOTH || direction == Direction.IN) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.IN_EDGES));
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
byte[] edgeId = Utils.slice(key, Utils.findLastInArray(key, StorageConstants.PROPERTY_SEPARATOR));
edgeIds.add(edgeId);
return true;
});
}
if (direction == Direction.BOTH || direction == Direction.OUT) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.OUT_EDGES));
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
byte[] edgeId = Utils.slice(key, Utils.findLastInArray(key, StorageConstants.PROPERTY_SEPARATOR));
edgeIds.add(edgeId);
return true;
});
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
return edgeIds;
}
public RocksVertex vertex(byte[] id, RocksGraph rocksGraph) throws Exception {
return getVertex(id, rocksGraph);
}
public void remove(RocksVertex rocksVertex) throws RocksDBException {
this.rocksDB.remove((byte[]) rocksVertex.id());
}
public enum VERTEX_COLUMNS {
PROPERTIES("PROPERTIES"),
PROPERTY_TYPE("PROPERTY_TYPE"),
OUT_EDGES("OUT_EDGES"),
IN_EDGES("IN_EDGES");
String value;
VERTEX_COLUMNS(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public VertexDB(RocksGraph rocksGraph) throws RocksDBException {
super(rocksGraph);
RocksDB.loadLibrary();
columnFamilyDescriptors = new ArrayList<>(VERTEX_COLUMNS.values().length);
columnFamilyHandleList = new ArrayList<>(VERTEX_COLUMNS.values().length);
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, StorageConfigFactory.getColumnFamilyOptions()));
for (VERTEX_COLUMNS vertex_columns : VERTEX_COLUMNS.values()) {
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(vertex_columns.getValue().getBytes(),
StorageConfigFactory.getColumnFamilyOptions()));
}
this.rocksDB = RocksDB.open(StorageConfigFactory.getDBOptions(), getDbPath() + "/vertices", columnFamilyDescriptors, columnFamilyHandleList);
this.rocksDB.enableFileDeletions(true);
}
public ColumnFamilyHandle getColumn(VERTEX_COLUMNS vertex_column) {
return columnFamilyHandleList.get(vertex_column.ordinal() + 1);
}
public void addVertex(byte[] idValue, String label, Object[] keyValues) throws Exception {
if (exists(idValue)) {
throw Graph.Exceptions.vertexWithIdAlreadyExists(new String(idValue));
}
put(idValue, label.getBytes());
if (keyValues == null || keyValues.length == 0) {
return;
}
Map<String, Object> properties = ElementHelper.asMap(keyValues);
for (Map.Entry<String, Object> property : properties.entrySet()) {
setProperty(idValue, property.getKey(), property.getValue(), VertexProperty.Cardinality.single);
}
}
private boolean exists(byte[] idValue) throws RocksDBException {
return (get(idValue) != null);
}
public List<Vertex> vertices(List<byte[]> vertexIds, RocksGraph rocksGraph) throws RocksDBException {
if (vertexIds == null) {
RocksIterator iterator = this.rocksDB.newIterator();
vertexIds = new ArrayList<>();
iterator.seekToFirst();
try {
while (iterator.isValid()) {
vertexIds.add(iterator.key());
iterator.next();
}
} finally {
iterator.dispose();
}
}
return vertexIds.stream().map(bytes -> getVertex(bytes, rocksGraph)).
filter(rocksVertex -> rocksVertex != null).collect(Collectors.toList());
}
public RocksVertex getVertex(byte[] vertexId, RocksGraph rocksGraph) {
try {
if (get(vertexId) == null) {
return null;
}
return new RocksVertex(vertexId, getLabel(vertexId), rocksGraph);
} catch (RocksDBException ex) {
ex.printStackTrace();
}
return null;
}
public String getLabel(byte[] vertexId) throws RocksDBException {
byte[] result = get(vertexId);
if (result == null) {
throw Graph.Exceptions.elementNotFound(Vertex.class, new String(vertexId));
}
return new String(result);
}
} |
package daris.lifepool.client;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import com.pixelmed.dicom.Attribute;
import com.pixelmed.dicom.AttributeList;
import com.pixelmed.dicom.DicomFileUtilities;
import com.pixelmed.dicom.TagFromName;
import arc.archive.ArchiveOutput;
import arc.archive.ArchiveRegistry;
import arc.mf.client.RemoteServer;
import arc.mf.client.ServerClient;
import arc.mf.client.archive.Archive;
import arc.streams.StreamCopy.AbortCheck;
import arc.xml.XmlDoc;
import arc.xml.XmlStringWriter;
import daris.lifepool.client.dicom.DicomIngest;
import daris.lifepool.client.dicom.DicomModify;
public class DataUpload {
public static final String DEFAULT_AE_TITLE = "DARIS_LIFEPOOL_CLIENT";
public static void main(String[] args) throws Throwable {
if (args == null || args.length == 0) {
showHelp();
System.exit(1);
}
String mfHost = null;
int mfPort = -1;
String mfTransport = null;
boolean useHttp = true;
boolean encrypt = true;
String mfAuth = null;
String mfToken = null;
String mfSid = null;
String pid = null;
File patientIdMapFile = null;
List<File> inputs = new ArrayList<File>();
try {
for (int i = 0; i < args.length;) {
if (args[i].equals("--help") || args[i].equals("-h")) {
showHelp();
System.exit(0);
} else if (args[i].equals("--mf.host")) {
if (mfHost != null) {
throw new Exception("--mf.host has already been specified.");
}
mfHost = args[i + 1];
i += 2;
} else if (args[i].equals("--mf.port")) {
if (mfPort > 0) {
throw new Exception("--mf.port has already been specified.");
}
try {
mfPort = Integer.parseInt(args[i + 1]);
} catch (Throwable e) {
throw new Exception("Invalid mf.port: " + args[i + 1], e);
}
if (mfPort <= 0 || mfPort > 65535) {
throw new Exception("Invalid mf.port: " + args[i + 1]);
}
i += 2;
} else if (args[i].equals("--mf.transport")) {
if (mfTransport != null) {
throw new Exception("--mf.transport has already been specified.");
}
mfTransport = args[i + 1];
i += 2;
if ("http".equalsIgnoreCase(mfTransport)) {
useHttp = true;
encrypt = false;
} else if ("https".equalsIgnoreCase(mfTransport)) {
useHttp = true;
encrypt = true;
} else if ("tcp/ip".equalsIgnoreCase(mfTransport)) {
useHttp = false;
encrypt = false;
} else {
throw new Exception(
"Invalid mf.transport: " + mfTransport + ". Expects http, https or tcp/ip.");
}
} else if (args[i].equals("--mf.auth")) {
if (mfAuth != null) {
throw new Exception("--mf.auth has already been specified.");
}
if (mfSid != null || mfToken != null) {
throw new Exception(
"You can only specify one of mf.auth, mf.token or mf.sid. Found more than one.");
}
mfAuth = args[i + 1];
i += 2;
} else if (args[i].equals("--mf.token")) {
if (mfToken != null) {
throw new Exception("--mf.token has already been specified.");
}
if (mfSid != null || mfAuth != null) {
throw new Exception(
"You can only specify one of mf.auth, mf.token or mf.sid. Found more than one.");
}
mfToken = args[i + 1];
i += 2;
} else if (args[i].equals("--mf.sid")) {
if (mfSid != null) {
throw new Exception("--mf.sid has already been specified.");
}
if (mfToken != null || mfAuth != null) {
throw new Exception(
"You can only specify one of mf.auth, mf.token or mf.sid. Found more than one.");
}
mfSid = args[i + 1];
i += 2;
} else if (args[i].equals("--pid")) {
if (pid != null) {
throw new Exception("--pid has already been specified.");
}
pid = args[i + 1];
i += 2;
} else if (args[i].equals("--patient.id.map")) {
if (patientIdMapFile != null) {
throw new Exception("--patient.id.map has already been specified.");
}
patientIdMapFile = new File(args[i + 1]);
if (!patientIdMapFile.exists()) {
throw new FileNotFoundException("File " + args[i + 1] + " is not found.");
}
i += 2;
} else {
File input = new File(args[i]);
if (!input.exists()) {
throw new FileNotFoundException("File " + args[i] + " is not found.");
}
inputs.add(input);
i++;
}
}
if (pid == null) {
throw new Exception("--pid is not specified.");
}
if (patientIdMapFile == null) {
throw new Exception("--patient.id.map is not specified.");
}
if (inputs.isEmpty()) {
throw new Exception("No input dicom file/directory is specified.");
}
if (mfHost == null) {
throw new Exception("--mf.host is not specified.");
}
if (mfPort <= 0) {
throw new Exception("--mf.port is not specified.");
}
if (mfTransport == null) {
throw new Exception("--mf.transport is not specified.");
}
if (mfAuth == null && mfSid == null && mfToken == null) {
throw new Exception("You need to specify one of mf.auth, mf.token or mf.sid. Found none.");
}
System.out.print("loading accession.number->patient.id mapping file: " + patientIdMapFile.getCanonicalPath()
+ "...");
Map<String, String> patientIdMap = loadPatientIdMap(patientIdMapFile);
System.out.println("done.");
RemoteServer server = new RemoteServer(mfHost, mfPort, useHttp, encrypt);
final ServerClient.Connection cxn = server.open();
try {
if (mfToken != null) {
cxn.connectWithToken(mfToken);
} else if (mfAuth != null) {
String[] parts = mfAuth.split(",");
if (parts.length != 3) {
throw new Exception("Invalid mf.auth: " + mfAuth
+ ". Expects a string in the form of 'domain,user,password'");
}
cxn.connect(parts[0], parts[1], parts[2]);
} else {
cxn.reconnect(mfSid);
}
final String projectCid = pid;
for (File input : inputs) {
if (Files.isDirectory(input.toPath())) {
Files.walkFileTree(input.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
try {
uploadDicomFile(cxn, path.toFile(), projectCid, patientIdMap);
} catch (Throwable e) {
e.printStackTrace(System.err);
return FileVisitResult.SKIP_SIBLINGS;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path path, IOException ioe) {
ioe.printStackTrace(System.err);
return FileVisitResult.SKIP_SUBTREE;
}
});
} else {
uploadDicomFile(cxn, input, projectCid, patientIdMap);
}
}
} finally {
cxn.closeAndDiscard();
}
} catch (IllegalArgumentException ex) {
System.err.println("Error: " + ex.getMessage());
showHelp();
}
}
private static void showHelp() {
System.out.println(
"Usage: data-upload [--help] --mf.host <host> --mf.port <port> --mf.transport <transport> [--mf.sid <sid>|--mf.token <token>|--mf.auth <domain,user,password>] --pid <project-cid> <dicom-files/dicom-directories>");
System.out.println("Description:");
System.out.println(" --mf.host <host> The Mediaflux server host.");
System.out.println(" --mf.port <port> The Mediaflux server port.");
System.out.println(
" --mf.transport <transport> The Mediaflux server transport, can be http, https or tcp/ip.");
System.out.println(" --mf.auth <domain,user,password> The Mediaflux user authentication deatils.");
System.out.println(" --mf.token <token> The Mediaflux secure identity token.");
System.out.println(" --mf.sid <sid> The Mediaflux session id.");
System.out.println(" --pid <project-cid> The DaRIS project cid.");
System.out.println(
" --patient.id.map <paitent-id-map> The file contains AccessionNumber -> PatientID mapping.");
System.out.println(" --help Display help information.");
}
public static void uploadDicomFile(ServerClient.Connection cxn, File dicomFile, String projectCid,
Map<String, String> patientIdMap) throws Throwable {
if (!DicomFileUtilities.isDicomOrAcrNemaFile(dicomFile)) {
System.out.println("\"" + dicomFile.getCanonicalPath() + "\" is not a dicom file.");
return;
}
AttributeList attributeList = new AttributeList();
attributeList.read(dicomFile);
/*
* AccessionNumber:
*/
String accessionNumber = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.AccessionNumber);
if (accessionNumber == null) {
throw new Exception("No AccessionNumber is found in DICOM file header.");
}
/*
* SeriesInstanceUID: unique identifier for the series
*/
String seriesInstanceUID = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesInstanceUID);
if (seriesInstanceUID == null) {
throw new Exception("No SeriesInstanceUID is found in DICOM file header.");
}
/*
* SeriesNumber: series number
*
* set SeriesNumber to 1 if it is null, because Mediaflux DICOM engine
* requires it.
*/
String seriesNumber = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesNumber);
if (seriesNumber == null) {
DicomModify.putAttribute(attributeList, TagFromName.SeriesNumber, "1");
}
/*
* SOPInstanceUID: unique identifier for the instance/image
*/
String sopInstanceUID = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SOPInstanceUID);
if (sopInstanceUID == null) {
throw new Exception("No SOPInstanceUID is found in DICOM file header.");
}
/*
* check if the dataset already exists
*/
String datasetCid = findDicomDataset(cxn, projectCid, sopInstanceUID, true);
if (datasetCid != null) {
System.out.println("Dicom dataset " + datasetCid + " created from local file \""
+ dicomFile.getCanonicalPath() + "\" already exists.");
return;
}
/*
* modify dicom file
*/
String prefix = dicomFile.getName();
if (prefix.endsWith(".dcm") || prefix.endsWith(".DCM")) {
prefix = prefix.substring(0, prefix.length() - 4);
}
File modifiedDicomFile = File.createTempFile(prefix, ".dcm");
DicomModify.putAttribute(attributeList, TagFromName.PatientName, projectCid);
String patientId = patientIdMap.get(accessionNumber);
if (patientId == null) {
throw new Exception("Could not find PatientID in mapping file for AccessionNumber: " + accessionNumber);
}
DicomModify.putAttribute(attributeList, TagFromName.PatientID, patientId);
try {
DicomModify.save(attributeList, modifiedDicomFile);
/*
* find first dataset in the study
*/
XmlDoc.Element firstDatasetAE = getFirstDicomDataset(cxn, projectCid, seriesInstanceUID);
if (firstDatasetAE == null) {
/*
* dicom ingest
*/
System.out.print("ingesting study...");
firstDatasetAE = DicomIngest.ingest(cxn, modifiedDicomFile, projectCid);
String firstDatasetAssetId = firstDatasetAE.value("@id");
String firstDatasetCid = firstDatasetAE.value("cid");
// update study name & description
String studyCid = CiteableIdUtils.parent(firstDatasetCid);
System.out.println("created study " + studyCid + ".");
System.out.print("updating study " + studyCid + "(accession.number=" + accessionNumber + ")...");
updateStudyName(cxn, studyCid, attributeList);
System.out.println("done.");
// destory the newly ingested first dataset (then re-create
// it using om.pssd.dataset.derivation.create)
// run dicom.metadata.get to test
try {
cxn.execute("dicom.metadata.get", "<id>" + firstDatasetAssetId + "</id>");
} catch (Throwable e) {
System.err.println("Error: failed to run dicom.metadata.get on newly ingested dataset: "
+ firstDatasetCid + " (AccessionNumber: " + accessionNumber + ", source file: "
+ dicomFile.getCanonicalPath()
+ "). You may need to destroy it, fix the dicom file, and re-upload.");
throw e;
}
// check if it's locked.
if (cxn.execute("asset.lock.describe", "<id>" + firstDatasetAssetId + "</id>")
.elementExists("lock")) {
throw new Exception("DICOM dataset " + firstDatasetCid + " (asset_id=" + firstDatasetAssetId
+ ") is locked by DICOM server engine. Something not right.");
}
cxn.execute("om.pssd.object.destroy",
"<hard-destroy>true</hard-destroy><cid>" + firstDatasetCid + "</cid>");
}
/*
* create dataset
*/
System.out.print("creating dataset from file: \"" + dicomFile.getCanonicalPath() + "\"...");
datasetCid = createDicomDataset(cxn, firstDatasetAE, modifiedDicomFile, dicomFile.getCanonicalPath(),
attributeList);
System.out.println("created dataset " + datasetCid + ".");
} finally {
Files.deleteIfExists(modifiedDicomFile.toPath());
}
}
private static String findDicomDataset(ServerClient.Connection cxn, String projectCid, String sopInstanceUID,
boolean exceptionIfMultipleFound) throws Throwable {
StringBuilder sb = new StringBuilder();
sb.append("cid starts with '").append(projectCid).append("'");
sb.append(" and xpath(daris:dicom-dataset/object/de[@tag='00080018']/value)='").append(sopInstanceUID)
.append("'");
XmlStringWriter w = new XmlStringWriter();
w.add("where", sb.toString());
w.add("action", "get-cid");
XmlDoc.Element re = cxn.execute("asset.query", w.document());
int nbResults = re.count("cid");
if (nbResults > 1 && exceptionIfMultipleFound) {
throw new Exception("More than one dicom dataset found. Expects only one. ");
}
return re.value("cid");
}
private static XmlDoc.Element getFirstDicomDataset(ServerClient.Connection cxn, String projectCid,
String seriesInstanceUID) throws Throwable {
StringBuilder sb = new StringBuilder();
sb.append("cid starts with '").append(projectCid).append("'");
sb.append(" and xpath(mf-dicom-series/uid)='").append(seriesInstanceUID).append("'");
XmlStringWriter w = new XmlStringWriter();
w.add("where", sb.toString());
w.add("size", 1);
w.add("action", "get-meta");
return cxn.execute("asset.query", w.document()).element("asset");
}
private static String createDicomDataset(ServerClient.Connection cxn, XmlDoc.Element firstSiblingAE,
final File dicomFile, final String sourcePath, AttributeList attributeList) throws Throwable {
String firstDatasetCid = firstSiblingAE.value("cid");
String studyCid = CiteableIdUtils.parent(firstDatasetCid);
String exMethodCid = firstSiblingAE.value("meta/daris:pssd-derivation/method");
String exMethodStep = firstSiblingAE.value("meta/daris:pssd-derivation/method/@step");
String name = datasetNameFor(attributeList);
String description = datasetDescriptionFor(attributeList);
XmlStringWriter w = new XmlStringWriter();
w.add("pid", studyCid);
w.push("method");
w.add("id", exMethodCid);
w.add("step", exMethodStep);
w.pop();
w.add("type", "dicom/series");
w.add("ctype", "application/arc-archive");
w.add("processed", true);
w.add("name", name);
w.add("description", description);
w.add("fillin", true);
w.push("meta");
/*
* mf-dicom-series
*/
w.push("mf-dicom-series", new String[] { "tag", "pssd.meta", "ns", "dicom" });
String seriesInstanceUID = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesInstanceUID);
w.add("uid", seriesInstanceUID);
String seriesNumber = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesNumber);
if (seriesNumber != null) {
w.add("id", seriesNumber);
}
String seriesDescription = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesDescription);
if (seriesDescription != null || seriesNumber != null) {
w.add("description", seriesDescription == null ? seriesNumber : seriesDescription);
}
String seriesDate = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesDate);
String seriesTime = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesTime);
if (seriesDate != null && seriesTime != null) {
Date sdate = parseDate(seriesDate + seriesTime);
w.add("sdate", sdate);
}
String acquisitionDate = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.AcquisitionDate);
String acquisitionTime = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.AcquisitionTime);
if (acquisitionDate != null && acquisitionTime != null) {
Date adate = parseDate(acquisitionDate + acquisitionTime);
w.add("adate", adate);
}
String instanceNumber = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.InstanceNumber);
w.add("imin", instanceNumber);
w.add("imax", instanceNumber);
w.add("size", 1);
String modality = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.Modality);
w.add("modality", modality);
String protocolName = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.ProtocolName);
if (protocolName != null) {
w.add("protocol", protocolName);
}
double[] imagePosition = Attribute.getDoubleValues(attributeList, TagFromName.ImagePositionPatient);
double[] imageOrientation = Attribute.getDoubleValues(attributeList, TagFromName.ImageOrientationPatient);
if ((imagePosition != null && imagePosition.length == 3)
|| (imageOrientation != null && imageOrientation.length == 6)) {
w.push("image");
if (imagePosition != null) {
w.push("position");
w.add("x", imagePosition[0]);
w.add("y", imagePosition[1]);
w.add("z", imagePosition[2]);
w.pop();
}
if (imageOrientation != null) {
w.push("orientation");
for (int i = 0; i < 6; i++) {
w.add("value", imageOrientation[i]);
}
w.pop();
}
w.pop();
}
w.pop();
/*
* mf-note
*/
w.push("mf-note");
w.add("note", "source: " + sourcePath);
w.pop();
w.pop();
Archive.declareSupportForAllTypes();
ServerClient.Input sci = new ServerClient.GeneratedInput("application/arc-archive", "aar", sourcePath, -1,
null) {
@Override
protected void copyTo(OutputStream os, AbortCheck ac) throws Throwable {
ArchiveOutput ao = ArchiveRegistry.createOutput(os, "application/arc-archive",
DicomIngest.Settings.DEFAULT_COMPRESSION_LEVEL, null);
try {
ao.add("application/dicom", Paths.get(sourcePath).getFileName().toString(), dicomFile);
} finally {
ao.close();
}
}
};
String datasetCid = cxn.execute("om.pssd.dataset.derivation.create", w.document(), sci).value("id");
/*
* daris:dicom-dataset
*/
populateAdditionalDicomMetadata(cxn, datasetCid);
return datasetCid;
}
private static String datasetNameFor(AttributeList attributeList) {
String protocolName = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.ProtocolName);
String seriesDescription = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesDescription);
StringBuilder sb = new StringBuilder();
if (seriesDescription != null) {
if (protocolName != null) {
if (seriesDescription.startsWith(protocolName)) {
sb.append(seriesDescription.replace(',', ' ').replaceAll("\\ {2,}+", "\\ "));
} else {
sb.append(protocolName).append("_").append(seriesDescription);
}
}
} else {
if (protocolName != null) {
sb.append(protocolName);
}
}
String viewPosition = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.ViewPosition);
if (viewPosition != null) {
if (sb.length() > 0) {
sb.append("_");
}
sb.append(viewPosition);
}
String imageLaterality = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.ImageLaterality);
if (imageLaterality != null) {
if (sb.length() > 0) {
sb.append("_");
}
sb.append(imageLaterality);
}
if (sb.length() > 0) {
return sb.toString();
} else {
return null;
}
}
private static String datasetDescriptionFor(AttributeList attributeList) {
String seriesDescription = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.SeriesDescription);
StringBuilder sb = new StringBuilder();
if (seriesDescription != null) {
sb.append(seriesDescription.replace(',', ' ').replaceAll("\\ {2,}+", "\\ ")).append(", ");
}
String imageType = Attribute.getDelimitedStringValuesOrNull(attributeList, TagFromName.ImageType);
if (imageType != null) {
sb.append(imageType).append(", ");
}
String viewPosition = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.ViewPosition);
if (viewPosition != null) {
sb.append(viewPosition).append(", ");
}
String imageLaterality = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.ImageLaterality);
if (imageLaterality != null) {
sb.append(imageLaterality).append(", ");
}
if (sb.length() > 0) {
return sb.toString();
} else {
return null;
}
}
private static String studyNameFor(AttributeList attributeList) {
String studyDescription = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.StudyDescription);
String accessionNumber = Attribute.getSingleStringValueOrNull(attributeList, TagFromName.AccessionNumber);
StringBuilder sb = new StringBuilder();
if (studyDescription != null) {
sb.append(studyDescription).append(" - ");
}
sb.append(accessionNumber);
return sb.toString();
}
private static Date parseDate(String dateTime) throws Throwable {
int idx = dateTime.indexOf('.');
if (idx == -1) {
return new SimpleDateFormat("yyyyMMddHHmmss").parse(dateTime);
} else {
Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateTime.substring(0, idx));
int millisecs = (int) (Double.parseDouble("0" + dateTime.substring(idx)) * 1000.0);
return new Date(date.getTime() + millisecs);
}
}
private static void populateAdditionalDicomMetadata(ServerClient.Connection cxn, String datasetCid)
throws Throwable {
XmlStringWriter w = new XmlStringWriter();
w.add("cid", datasetCid);
// NOTE: code commented out below are replaced by calling
// vicnode.daris.lifepool.metadata.extract service
// @formatter:off
// w.add("doc-tag", "pssd.meta");
// w.add("if-exists", "merge");
// w.add("tag", "00080008"); // ImageType
// w.add("tag", "00080018"); // SOPInstanceUID
// w.add("tag", "00080050"); // AccessionNumber
// w.add("tag", "00080060"); // Modality
// w.add("tag", "00080068"); // PresentationIntentType
// w.add("tag", "00080070"); // Manufacturer
// w.add("tag", "00080080"); // InstitutionName
// w.add("tag", "0008103E"); // SeriesDescription
// w.add("tag", "00081090"); // ManufacturerModelName
// w.add("tag", "00181400"); // AcquisitionDeviceProcessingDescription
// w.add("tag", "00185101"); // ViewPosition
// w.add("tag", "00200062"); // ImageLaterality
// cxn.execute("dicom.metadata.populate", w.document());
// @formatter:on
cxn.execute("vicnode.daris.lifepool.metadata.extract", w.document());
}
private static void updateStudyName(ServerClient.Connection cxn, String studyCid, AttributeList attributeList)
throws Throwable {
XmlDoc.Element ae = cxn.execute("asset.get", "<cid>" + studyCid + "</cid>");
String studyName = studyNameFor(attributeList);
if (!studyName.equals(ae.value("meta/daris:pssd-object/name"))) {
XmlStringWriter w = new XmlStringWriter();
w.add("cid", studyCid);
w.push("meta");
w.push("daris:pssd-object", new String[] { "id", ae.value("meta/daris:pssd-object/@id") });
w.add("name", studyName);
w.add("description", studyName);
w.pop();
w.pop();
cxn.execute("asset.set", w.document());
}
}
private static Map<String, String> loadPatientIdMap(File file) throws Throwable {
Map<String, String> map = new HashMap<String, String>((120000 * 4 + 2) / 3);
try (Stream<String> stream = Files.lines(file.toPath())) {
stream.forEach(line -> {
if (line.matches("^\\ *\\d+\\ *,.+")) {
String[] tokens = line.trim().split("\\ *,\\ *");
String patientId = tokens[0];
String accessionNumber = tokens[1];
map.put(accessionNumber, patientId);
}
});
}
if (map.isEmpty()) {
throw new Exception("Failed to parse patient id mapping file: " + file.getCanonicalPath() + ".");
}
return map;
}
} |
package de.retest.recheck;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import org.apache.commons.lang3.StringUtils;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestCaseFinder {
/**
* Delimiter to separate methods names from their invocation count.
*/
public static final String DELIMITER = "_";
static final TestCaseInformation NO_TEST_CASE_INFORMATION =
new TestCaseInformation( null, TestCaseAnnotationType.NONE, 0 );
private static final Set<String> testCaseAnnotations = new HashSet<>( Arrays.asList(
// JUnit Vintage (v4)
"org.junit.Test",
"org.junit.Before",
"org.junit.After",
"org.junit.BeforeClass",
"org.junit.AfterClass",
// JUnit Jupiter (v5)
"org.junit.jupiter.api.Test",
"org.junit.jupiter.api.BeforeEach",
"org.junit.jupiter.api.AfterEach",
"org.junit.jupiter.api.BeforeAll",
"org.junit.jupiter.api.AfterAll",
// TestNG
"org.testng.annotations.Test",
"org.testng.annotations.BeforeMethod",
"org.testng.annotations.AfterMethod",
"org.testng.annotations.BeforeClass",
"org.testng.annotations.AfterClass" ) );
private static final Set<String> repeatableTestCaseAnnotations = new HashSet<>( Arrays.asList(
// JUnit Vintage (v4)
"org.junit.experimental.theories.Theory",
// JUnit Jupiter (v5)
"org.junit.jupiter.api.RepeatedTest",
"org.junit.jupiter.params.ParameterizedTest" ) );
private static Function<TestCaseInformation, String> toClassName() {
return info -> info.getStackTraceElement().getClassName();
}
private static Function<TestCaseInformation, String> toMethodName() {
return info -> {
final String methodName = info.getStackTraceElement().getMethodName();
return info.isRepeatable() ? methodName + DELIMITER + info.getInvocationCount() : methodName;
};
}
private static TestCaseFinder instance;
private final Map<StackTraceElement, Integer> repeatableTestCaseAnnotationsCount = new HashMap<>();
private TestCaseFinder() {}
public static TestCaseFinder getInstance() {
if ( instance == null ) {
instance = new TestCaseFinder();
}
return instance;
}
/**
* @return A <em>distinct</em> method name for the test case method in all stack traces.
*/
public Optional<String> findTestCaseMethodNameInStack() {
return findTestCaseMethodInStack( toMethodName() );
}
/**
* @return The class name for the test case method in all stack traces.
*/
public Optional<String> findTestCaseClassNameInStack() {
final Optional<String> testCaseClassName = findTestCaseMethodInStack( toClassName() );
if ( testCaseClassName.isPresent() ) {
return testCaseClassName;
} else {
return findTestCaseClassInStack();
}
}
/**
* @return The class name for the test being called from.
*/
public Optional<String> findTestCaseClassInStack() {
for ( final StackTraceElement[] stack : Thread.getAllStackTraces().values() ) {
final Optional<String> className = findTestCaseClassInStack( stack );
if ( className.isPresent() ) {
return className;
}
}
return Optional.empty();
}
/**
* @param trace
* The trace to be used for search.
* @return The class name for the test being called from.
*/
public Optional<String> findTestCaseClassInStack( final StackTraceElement[] trace ) {
for ( final StackTraceElement element : trace ) {
final String className = element.getClassName();
if ( StringUtils.endsWith( className, "Test" ) || StringUtils.endsWith( className, "IT" ) ) {
return Optional.of( className );
}
}
return Optional.empty();
}
/**
* @param trace
* The trace to be used for search.
* @return A <em>distinct</em> method name for the test case method in the given stack trace.
*/
public Optional<String> findTestCaseMethodNameInStack( final StackTraceElement[] trace ) {
return findTestCaseMethodInStack( toMethodName(), trace );
}
/**
* @param trace
* The trace to be used for search.
* @return The class name for the test case method in the given stack trace.
*/
public Optional<String> findTestCaseClassNameInStack( final StackTraceElement[] trace ) {
return findTestCaseMethodInStack( toClassName(), trace );
}
private Optional<String> findTestCaseMethodInStack( final Function<TestCaseInformation, String> mapper ) {
final TestCaseInformation info = findTestCaseMethodInStack();
return info.isFound() ? Optional.of( mapper.apply( info ) ) : Optional.empty();
}
private Optional<String> findTestCaseMethodInStack( final Function<TestCaseInformation, String> mapper,
final StackTraceElement[] trace ) {
final TestCaseInformation info = findTestCaseMethodInStack( trace );
return info.isFound() ? Optional.of( mapper.apply( info ) ) : Optional.empty();
}
/**
* @return Test case information for the test case method in all stack traces.
*/
public TestCaseInformation findTestCaseMethodInStack() {
for ( final StackTraceElement[] stack : Thread.getAllStackTraces().values() ) {
final TestCaseInformation info = findTestCaseMethodInStack( stack );
if ( info.isFound() ) {
return info;
}
}
return NO_TEST_CASE_INFORMATION;
}
/**
* @param trace
* The trace to be used for search.
* @return Test case information for the test case method in the given stack trace.
*/
public TestCaseInformation findTestCaseMethodInStack( final StackTraceElement[] trace ) {
for ( final StackTraceElement element : trace ) {
final TestCaseAnnotationType type = determineTestCaseAnnotationType( element );
if ( type == TestCaseAnnotationType.NORMAL ) {
return new TestCaseInformation( element, type, 1 );
}
if ( type == TestCaseAnnotationType.REPEATABLE ) {
final int count = repeatableTestCaseAnnotationsCount.merge( element, 1, Integer::sum );
return new TestCaseInformation( element, type, count );
}
}
return NO_TEST_CASE_INFORMATION;
}
private TestCaseAnnotationType determineTestCaseAnnotationType( final StackTraceElement element ) {
final Method method = tryToFindMethodForStackTraceElement( element );
if ( method == null ) {
return TestCaseAnnotationType.NONE;
}
final Annotation[] annotations = method.getAnnotations();
for ( final Annotation annotation : annotations ) {
final String annotationName = annotation.annotationType().getName();
if ( testCaseAnnotations.contains( annotationName ) ) {
return TestCaseAnnotationType.NORMAL;
}
if ( repeatableTestCaseAnnotations.contains( annotationName ) ) {
return TestCaseAnnotationType.REPEATABLE;
}
}
return TestCaseAnnotationType.NONE;
}
private Method tryToFindMethodForStackTraceElement( final StackTraceElement element ) {
final Class<?> clazz;
Method method = null;
try {
clazz = Class.forName( element.getClassName() );
} catch ( final ClassNotFoundException e ) {
return null;
}
try {
for ( final Method methodCandidate : clazz.getDeclaredMethods() ) {
if ( methodCandidate.getName().equals( element.getMethodName() ) ) {
if ( method == null ) {
method = methodCandidate;
} else {
// two methods with same name found, can't determine correct one!
return null;
}
}
}
} catch ( final NoClassDefFoundError e ) {
log.error( "Could not analyze method due to NoClassDefFoundError: {}", e.getMessage() );
}
return method;
}
@Value
public static class TestCaseInformation {
StackTraceElement stackTraceElement;
TestCaseAnnotationType testCaseAnnotationType;
int invocationCount;
public boolean isFound() {
return stackTraceElement != null;
}
public boolean isRepeatable() {
return testCaseAnnotationType == TestCaseAnnotationType.REPEATABLE;
}
}
public enum TestCaseAnnotationType {
NORMAL,
REPEATABLE,
NONE
}
} |
package de.retest.recheck;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestCaseFinder {
private static final Logger logger = LoggerFactory.getLogger( TestCaseFinder.class );
private TestCaseFinder() {}
/*
* TODO We need a special implementation for data-driven testing with annotations such as JUnit's @Theory, because
* then a single method is invoked multiple times.
*/
private static final Set<String> testCaseAnnotations = new HashSet<>( Arrays.asList(
// JUnit Vintage (v4)
"org.junit.Test",
"org.junit.Before",
"org.junit.After",
"org.junit.BeforeClass",
"org.junit.AfterClass",
// JUnit Jupiter (v5)
"org.junit.jupiter.api.Test",
"org.junit.jupiter.api.BeforeEach",
"org.junit.jupiter.api.AfterEach",
"org.junit.jupiter.api.BeforeAll",
"org.junit.jupiter.api.AfterAll",
"org.junit.jupiter.params.ParameterizedTest",
// TestNG
"org.testng.annotations.Test",
"org.testng.annotations.BeforeMethod",
"org.testng.annotations.AfterMethod",
"org.testng.annotations.BeforeClass",
"org.testng.annotations.AfterClass" ) );
public static StackTraceElement findTestCaseMethodInStack() {
for ( final StackTraceElement[] stack : Thread.getAllStackTraces().values() ) {
final StackTraceElement testCaseStackElement = findTestCaseMethodInStack( stack );
if ( testCaseStackElement != null ) {
return testCaseStackElement;
}
}
return null;
}
public static StackTraceElement findTestCaseMethodInStack( final StackTraceElement[] trace ) {
boolean inTestCase = false;
for ( int i = 0; i < trace.length; i++ ) {
if ( isTestCase( trace[i] ) ) {
inTestCase = true;
} else if ( inTestCase ) {
return trace[i - 1];
}
}
return null;
}
private static boolean isTestCase( final StackTraceElement element ) {
final Method method = tryToFindMethodForStackTraceElement( element );
if ( method == null ) {
return false;
}
final Annotation[] annotations = method.getAnnotations();
for ( final Annotation annotation : annotations ) {
final String annotationName = annotation.annotationType().getName();
if ( testCaseAnnotations.contains( annotationName ) ) {
return true;
}
}
return false;
}
private static Method tryToFindMethodForStackTraceElement( final StackTraceElement element ) {
final Class<?> clazz;
Method method = null;
try {
clazz = Class.forName( element.getClassName() );
} catch ( final ClassNotFoundException e ) {
return null;
}
try {
for ( final Method methodCandidate : clazz.getDeclaredMethods() ) {
if ( methodCandidate.getName().equals( element.getMethodName() ) ) {
if ( method == null ) {
method = methodCandidate;
} else {
// two methods with same name found, can't determine correct one!
return null;
}
}
}
} catch ( final NoClassDefFoundError noClass ) {
logger.error( "Could not analyze method due to NoClassDefFoundError: ", noClass );
}
return method;
}
} |
package edu.neu.ccs.pyramid.eval;
import edu.neu.ccs.pyramid.dataset.MultiLabel;
import edu.neu.ccs.pyramid.dataset.MultiLabelClfDataSet;
import edu.neu.ccs.pyramid.multilabel_classification.MultiLabelClassifier;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
public class Overlap {
public static double overlap(double tp, double fp, double fn){
return SafeDivide.divide(tp,tp+fp+fn,1);
}
@Deprecated
public static double overlap(MultiLabelClassifier classifier, MultiLabelClfDataSet dataSet){
return overlap(dataSet.getMultiLabels(),classifier.predict(dataSet));
}
@Deprecated
public static double overlap(MultiLabel[] multiLabels, MultiLabel[] predictions){
return IntStream.range(0,multiLabels.length).parallel()
.mapToDouble(i -> overlap(multiLabels[i],predictions[i]))
.average().getAsDouble();
}
public static double overlap(MultiLabel multiLabel1, MultiLabel multiLabel2){
Set<Integer> set1 = multiLabel1.getMatchedLabels();
Set<Integer> set2 = multiLabel2.getMatchedLabels();
Set<Integer> union = new HashSet<>();
union.addAll(set1);
union.addAll(set2);
Set<Integer> intersection = new HashSet<>();
intersection.addAll(set1);
intersection.retainAll(set2);
return SafeDivide.divide(intersection.size(),union.size(),1);
}
} |
package edu.ucsf.mousedatabase;
import java.sql.*;
import java.sql.Date;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import edu.ucsf.mousedatabase.beans.MouseSubmission;
import edu.ucsf.mousedatabase.beans.UserData;
import edu.ucsf.mousedatabase.dataimport.ImportHandler;
import edu.ucsf.mousedatabase.dataimport.ImportHandler.ImportObjectType;
import edu.ucsf.mousedatabase.objects.*;
import edu.ucsf.mousedatabase.servlets.ReportServlet;
import org.apache.commons.lang3.StringUtils;
public class DBConnect {
//set this to true for debugging
private static final boolean logQueries = false;
private static final String mouseRecordTableColumns =
"mouse.id, name, mousetype, modification_type," +
"transgenictype.transgenictype,regulatory_element_comment as 'regulatory element',"
+"expressedsequence.expressedsequence, reporter_comment as 'reporter', strain, " +
"general_comment, source, mta_required, repository_id, repository.repository, " +
"repository_catalog_number,gensat,other_comment, gene.mgi as 'gene MGI', " +
"gene.symbol as 'gene symbol', gene.fullname as 'gene name',cryopreserved," +
"status,endangered,submittedmouse_id, targetgenes.mgi as 'target gene MGI'," +
"targetgenes.symbol as 'target gene symbol', targetgenes.fullname as 'target gene name', official_name\r\n";
private static final String mouseRecordTableJoins =
" left join mousetype on mouse.mousetype_id=mousetype.id\r\n"
+" left join gene on mouse.gene_id=gene.id\r\n"
+" left join gene as targetgenes on mouse.target_gene_id=targetgenes.id\r\n"
+" left join transgenictype on mouse.transgenictype_id=transgenictype.id\r\n"
+" left join expressedsequence on mouse.expressedsequence_id=expressedsequence.id\r\n"
+" left join repository on mouse.repository_id=repository.id\r\n ";
private static final String mouseRecordQueryHeader =
"SELECT " +
mouseRecordTableColumns
+" FROM mouse\r\n"
+ mouseRecordTableJoins;
private static final String mouseRecordQueryCountHeader =
"SELECT count(*) as count"
+" FROM mouse\r\n"
+ mouseRecordTableJoins;
private static final String mouseSubmissionQueryHeader =
"SELECT submittedmouse.* , mouse.id as mouseRecordID\r\n"
+ " FROM submittedmouse left join mouse on submittedmouse.id=mouse.submittedmouse_id\r\n ";
private static final String changeRequestQueryHeader =
"SELECT changerequest.*, mouse.name\r\n" +
" FROM changerequest left join mouse on changerequest.mouse_id=mouse.id\r\n ";
private static final String holderQueryHeader =
"SELECT holder.*, (select count(*) \r\n" +
" FROM mouse_holder_facility left join mouse on mouse_holder_facility.mouse_id=mouse.id\r\n" +
" WHERE holder_id=holder.id and covert=0 and mouse.status='live') as 'mice held'\r\n" +
" FROM holder\r\n ";
private static final String facilityQueryHeader =
"SELECT id, facility, description, code" +
", (select count(*) from mouse_holder_facility where facility_id=facility.id) as 'mice held'\r\n" +
" FROM facility\r\n ";
private static final String mouseHolderQueryHeader =
"SELECT holder_id, facility_id, covert, cryo_live_status, firstname, lastname, " +
"department, email, alternate_email, tel, facility" +
"\r\n FROM mouse_holder_facility t1 left join holder on t1.holder_id=holder.id " +
"left join facility on t1.facility_id=facility.id \r\n";
private static final String geneQueryHeader = "SELECT id,fullname,symbol,mgi \r\n FROM gene\r\n ";
private static final String mouseIDSearchTermsRegex = "^(
private static Connection connect() throws Exception
{
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/mouse_inventory");
return ds.getConnection();
}
catch (Exception e)
{
Log.Error("Problem connecting",e);
throw e;
}
}
/*Comparator<Sub> comparator = new Comparator<Sub>(){
public int compare(Sub a, Sub b)
{
return HTMLGeneration.emptyIfNull(a.PIName)
.compareTo(HTMLGeneration.emptyIfNull(b.PIName));
}
};
Collections.sort(linesByRecipientPI,comparator);
*/
for (Sub sub : linesByRecipientPI) {
//TODO why don't we want the PIName as well??
result.append(sub.Line);
}
return result.toString();
} |
package eu.amidst.examples;
import COM.hugin.HAPI.*;
import COM.hugin.HAPI.Class;
import eu.amidst.core.database.Attributes;
import eu.amidst.core.database.DataBase;
import eu.amidst.core.database.DataInstance;
import eu.amidst.core.database.DataOnDisk;
import eu.amidst.core.database.filereaders.DynamicDataOnDiskFromFile;
import eu.amidst.core.database.filereaders.arffFileReader.ARFFDataReader;
import eu.amidst.core.huginlink.*;
import eu.amidst.core.learning.DynamicNaiveBayesClassifier;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DynamicBayesianNetwork;
import eu.amidst.core.utils.BayesianNetworkGenerator;
import eu.amidst.core.utils.BayesianNetworkSampler;
import eu.amidst.core.variables.DynamicVariables;
import eu.amidst.core.variables.Variable;
import java.io.IOException;
import java.util.*;
public class InferenceDemo {
public static void printBeliefs (Domain domainObject) throws ExceptionHugin {
domainObject.getNodes().stream().forEach((node) -> {
try {
System.out.print("\n" + node.getName()+ ": ");
int numStates = (int)((LabelledDCNode)node).getNumberOfStates();
for (int j=0;j<numStates;j++){
System.out.print(((LabelledDCNode) node).getBelief(j) + " ");
}
} catch (ExceptionHugin exceptionHugin) {
exceptionHugin.printStackTrace();
}
});
}
public static void demo() throws ExceptionHugin, IOException {
//Generate random data
// BayesianNetworkGenerator.setNumberOfContinuousVars(0);
// BayesianNetworkGenerator.setNumberOfDiscreteVars(3);
// BayesianNetworkGenerator.setNumberOfStates(2);
// BayesianNetwork bn = BayesianNetworkGenerator.generateNaiveBayes(new Random(0),2);
// int sampleSize = 20;
// BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn);
// sampler.setParallelMode(false);
// String file = "./datasets/randomdata.arff";
// sampler.sampleToAnARFFFile(file,sampleSize);
//String file = "./datasets/bank_data_small.arff";
String file = "./datasets/bank_data.arff";
//String file = "./datasets/randomdata2.arff";
DataBase data = new DynamicDataOnDiskFromFile(new ARFFDataReader(file));
System.out.println("ATTRIBUTES:");
data.getAttributes().getList().stream().forEach(a -> System.out.println(a.getName()));
DynamicNaiveBayesClassifier model = new DynamicNaiveBayesClassifier();
// -3 instead of -1 because we have to ignore TIME_ID and SEQUENCE_ID as they are not variables in the model.
model.setClassVarID(data.getAttributes().getNumberOfAttributes() - 3);
model.setParallelMode(true);
model.learn(data);
DynamicBayesianNetwork amidstDBN = model.getDynamicBNModel();
//We randomly initialize the parensets Time 0 because parameters are wrongly learnt due
//to the data sample only contains 1 data sequence.
Random rand = new Random(0);
amidstDBN.getDistributionsTime0().forEach(w -> w.randomInitialization(rand));
System.out.println(amidstDBN.toString());
Class huginDBN = DBNConverterToHugin.convertToHugin(amidstDBN);
String nameModel = "CajamarDBN";
huginDBN.setName(nameModel);
String outFile = new String("networks/" + nameModel + ".net");
huginDBN.saveAsNet(outFile);
System.out.println("Hugin network saved in \"" + outFile + "\"" + ".");
}
public static void main(String[] args) throws ExceptionHugin, IOException {
InferenceDemo.demo();
}
} |
package fr.eisti.web;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import fr.eisti.domain.Direction;
import fr.eisti.service.DirectionServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DirectionController {
@Autowired
private DirectionServiceImpl directionService;
@RequestMapping("directions/origin/lat/{origLat}/lng/{origLng}/destination/lat/{destLat}/lng/{destLng}/")
Direction getDirection(
@PathVariable("origLat") double origLat,
@PathVariable("origLng") double origLng,
@PathVariable("destLat") double destLat,
@PathVariable("destLng") double destLng
) {
GeometryFactory geometryFactory = new GeometryFactory();
Point origin = geometryFactory.createPoint(new Coordinate(origLat, origLng));
Point destination = geometryFactory.createPoint(new Coordinate(destLat, destLng));
return directionService.getDirection(origin, destination);
}
} |
package hr.vsite.mentor.user;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.inject.Inject;
import javax.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UserManager {
@Inject
public UserManager(Provider<Connection> connProvider) {
this.connProvider = connProvider;
}
/** Returns <code>User</code> with corresponding id, or <code>null</code> if such user does not exist. */
public User findById(UUID id) {
try (PreparedStatement statement = connProvider.get().prepareStatement("SELECT * FROM users WHERE user_id = ?")) {
statement.setObject(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
return resultSet.next() ? fromResultSet(resultSet) : null;
}
} catch (SQLException e) {
throw new RuntimeException("Unable to find user with id " + id, e);
}
}
/** Returns <code>User</code> with corresponding e-mail, or <code>null</code> if such user does not exist. */
public User findByEmail(String email) {
try (PreparedStatement statement = connProvider.get().prepareStatement("SELECT * FROM users WHERE email = lower(?)")) {
statement.setString(1, email);
try (ResultSet resultSet = statement.executeQuery()) {
return resultSet.next() ? fromResultSet(resultSet) : null;
}
} catch (SQLException e) {
throw new RuntimeException("Unable to find user with email " + email, e);
}
}
/** Returns all users known to application, unpaged. If there is a possibility for large number of users,
* use {@link #list(UserFilter, Integer, Integer)}*/
public List<User> list() {
return list(new UserFilter(), null, null);
}
/** Returns users that match given criteria, unpaged. If there is a possibility for large number of users,
* use {@link #list(UserFilter, Integer, Integer)}*/
public List<User> list(UserFilter filter) {
return list(filter, null, null);
}
/** Returns users that match given criteria, paged.*/
public List<User> list(UserFilter filter, Integer count, Integer offset) {
List<User> users = new ArrayList<>(count != null ? count : 10);
StringBuilder queryBuilder = new StringBuilder(1000);
queryBuilder.append("SELECT * FROM users WHERE true");
if (filter.getName() != null)
queryBuilder.append(" AND lower(user_name) LIKE '%' || lower(?) || '%'");
if (filter.getEmail() != null)
queryBuilder.append(" AND user_email = lower(?)");
if (count != null)
queryBuilder.append(" LIMIT ?");
if (offset != null)
queryBuilder.append(" OFFSET ?");
try (PreparedStatement statement = connProvider.get().prepareStatement(queryBuilder.toString())) {
int index = 0;
if (filter.getName() != null)
statement.setString(++index, filter.getName());
if (filter.getEmail() != null)
statement.setString(++index, filter.getEmail());
if (count != null)
statement.setInt(++index, count);
if (offset != null)
statement.setInt(++index, offset);
try (ResultSet resultSet = statement.executeQuery()) {
while(resultSet.next())
users.add(fromResultSet(resultSet));
}
} catch (SQLException e) {
throw new RuntimeException("Unable to list users", e);
}
return users;
}
/** Parses given ResultSet and extract User from it.
* If ResultSet had <code>NULL</code> in <code>author_id</code> column, <code>null</code> is returned. */
public User fromResultSet(ResultSet resultSet) {
User user = new User();
try {
user.setId(UUID.class.cast(resultSet.getObject("user_id")));
if (resultSet.wasNull())
return null;
user.setEmail(resultSet.getString("user_email"));
user.setName(resultSet.getString("user_name"));
} catch (SQLException e) {
throw new RuntimeException("Unable to resolve user from result set", e);
}
return user;
}
/** Gets logged in user.
*/
public User me() {
return null;
}
private static final Logger Log = LoggerFactory.getLogger(UserManager.class);
private final Provider<Connection> connProvider;
} |
package hudson.plugins.ec2;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import jenkins.slaves.iterators.api.NodeIterator;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.*;
import hudson.Extension;
import hudson.Util;
import hudson.model.*;
import hudson.model.Descriptor.FormException;
import hudson.model.labels.LabelAtom;
import hudson.plugins.ec2.util.DeviceMappingParser;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
/**
* Template of {@link EC2AbstractSlave} to launch.
*
* @author Kohsuke Kawaguchi
*/
public class SlaveTemplate implements Describable<SlaveTemplate> {
private static final Logger LOGGER = Logger.getLogger(SlaveTemplate.class.getName());
public String ami;
public final String description;
public final String zone;
public final SpotConfiguration spotConfig;
public final String securityGroups;
public final String remoteFS;
public final InstanceType type;
public final boolean ebsOptimized;
public final String labels;
public final Node.Mode mode;
public final String initScript;
public final String tmpDir;
public final String userData;
public final String numExecutors;
public final String remoteAdmin;
public final String jvmopts;
public final String subnetId;
public final String idleTerminationMinutes;
public final String iamInstanceProfile;
public final boolean useEphemeralDevices;
public final String customDeviceMapping;
public int instanceCap;
public final boolean stopOnTerminate;
private final List<EC2Tag> tags;
public final boolean usePrivateDnsName;
public final boolean associatePublicIp;
protected transient EC2Cloud parent;
public final boolean useDedicatedTenancy;
public AMITypeData amiType;
public int launchTimeout;
public boolean connectBySSHProcess;
public final boolean connectUsingPublicIp;
private transient/* almost final */Set<LabelAtom> labelSet;
private transient/* almost final */Set<String> securityGroupSet;
/*
* Necessary to handle reading from old configurations. The UnixData object is created in readResolve()
*/
@Deprecated
public transient String sshPort;
@Deprecated
public transient String rootCommandPrefix;
@DataBoundConstructor
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS,
InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript,
String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts,
boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes,
boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices,
boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping,
boolean connectBySSHProcess, boolean connectUsingPublicIp) {
this.ami = ami;
this.zone = zone;
this.spotConfig = spotConfig;
this.securityGroups = securityGroups;
this.remoteFS = remoteFS;
this.amiType = amiType;
this.type = type;
this.ebsOptimized = ebsOptimized;
this.labels = Util.fixNull(labelString);
this.mode = mode;
this.description = description;
this.initScript = initScript;
this.tmpDir = tmpDir;
this.userData = userData;
this.numExecutors = Util.fixNull(numExecutors).trim();
this.remoteAdmin = remoteAdmin;
this.jvmopts = jvmopts;
this.stopOnTerminate = stopOnTerminate;
this.subnetId = subnetId;
this.tags = tags;
this.idleTerminationMinutes = idleTerminationMinutes;
this.usePrivateDnsName = usePrivateDnsName;
this.associatePublicIp = associatePublicIp;
this.connectUsingPublicIp = connectUsingPublicIp;
this.useDedicatedTenancy = useDedicatedTenancy;
this.connectBySSHProcess = connectBySSHProcess;
if (null == instanceCapStr || instanceCapStr.isEmpty()) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = Integer.parseInt(instanceCapStr);
}
try {
this.launchTimeout = Integer.parseInt(launchTimeoutStr);
} catch (NumberFormatException nfe) {
this.launchTimeout = Integer.MAX_VALUE;
}
this.iamInstanceProfile = iamInstanceProfile;
this.useEphemeralDevices = useEphemeralDevices;
this.customDeviceMapping = customDeviceMapping;
readResolve(); // initialize
}
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS,
InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript,
String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts,
boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes,
boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices,
boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping,
boolean connectBySSHProcess) {
this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript,
tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags,
idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices,
useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, false);
}
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS,
InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript,
String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts,
boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes,
boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices,
boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping) {
this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript,
tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags,
idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices,
useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, false);
}
/**
* Backward compatible constructor for reloading previous version data
*/
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS,
String sshPort, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description,
String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix,
String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes,
boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices,
String launchTimeoutStr) {
this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript,
tmpDir, userData, numExecutors, remoteAdmin, new UnixData(rootCommandPrefix, sshPort), jvmopts, stopOnTerminate,
subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile,
useEphemeralDevices, false, launchTimeoutStr, false, null);
}
public boolean isConnectBySSHProcess() {
// See
// src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-connectBySSHProcess.html
return connectBySSHProcess;
}
public EC2Cloud getParent() {
return parent;
}
public String getLabelString() {
return labels;
}
public Node.Mode getMode() {
return mode;
}
public String getDisplayName() {
return description + " (" + ami + ")";
}
String getZone() {
return zone;
}
public String getSecurityGroupString() {
return securityGroups;
}
public Set<String> getSecurityGroupSet() {
return securityGroupSet;
}
public Set<String> parseSecurityGroups() {
if (securityGroups == null || "".equals(securityGroups.trim())) {
return Collections.emptySet();
} else {
return new HashSet<String>(Arrays.asList(securityGroups.split("\\s*,\\s*")));
}
}
public int getNumExecutors() {
try {
return Integer.parseInt(numExecutors);
} catch (NumberFormatException e) {
return EC2AbstractSlave.toNumExecutors(type);
}
}
public int getSshPort() {
try {
String sshPort = "";
if (amiType.isUnix()) {
sshPort = ((UnixData) amiType).getSshPort();
}
return Integer.parseInt(sshPort);
} catch (NumberFormatException e) {
return 22;
}
}
public String getRemoteAdmin() {
return remoteAdmin;
}
public String getRootCommandPrefix() {
return amiType.isUnix() ? ((UnixData) amiType).getRootCommandPrefix() : "";
}
public String getSubnetId() {
return subnetId;
}
public boolean getAssociatePublicIp() {
return associatePublicIp;
}
public boolean isConnectUsingPublicIp() {
return connectUsingPublicIp;
}
public List<EC2Tag> getTags() {
if (null == tags)
return null;
return Collections.unmodifiableList(tags);
}
public String getidleTerminationMinutes() {
return idleTerminationMinutes;
}
public boolean getUseDedicatedTenancy() {
return useDedicatedTenancy;
}
public Set<LabelAtom> getLabelSet() {
return labelSet;
}
public String getAmi() {
return ami;
}
public void setAmi(String ami) {
this.ami = ami;
}
public int getInstanceCap() {
return instanceCap;
}
public String getInstanceCapStr() {
if (instanceCap == Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(instanceCap);
}
}
public String getSpotMaxBidPrice() {
if (spotConfig == null)
return null;
return SpotConfiguration.normalizeBid(spotConfig.spotMaxBidPrice);
}
public String getIamInstanceProfile() {
return iamInstanceProfile;
}
enum ProvisionOptions { ALLOW_CREATE, FORCE_CREATE }
/**
* Provisions a new EC2 slave or starts a previously stopped on-demand instance.
*
* @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}.
*/
public EC2AbstractSlave provision(TaskListener listener, Label requiredLabel, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException {
if (this.spotConfig != null) {
if (provisionOptions.contains(ProvisionOptions.ALLOW_CREATE) || provisionOptions.contains(ProvisionOptions.FORCE_CREATE))
return provisionSpot(listener);
return null;
}
return provisionOndemand(listener, requiredLabel, provisionOptions);
}
/**
* Determines whether the AMI of the given instance matches the AMI of template and has the required label (if requiredLabel is non-null)
*/
private boolean checkInstance(PrintStream logger, Instance existingInstance, Label requiredLabel, EC2AbstractSlave[] returnNode) {
logProvision(logger, "checkInstance: " + existingInstance);
if (StringUtils.isNotBlank(getIamInstanceProfile())) {
if (existingInstance.getIamInstanceProfile() != null) {
if (!existingInstance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) {
logProvision(logger, " false - IAM Instance profile does not match");
return false;
}
// Match, fall through
} else {
logProvision(logger, " false - Null IAM Instance profile");
return false;
}
}
if (existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.Terminated.toString())
|| existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.ShuttingDown.toString())) {
logProvision(logger, " false - Instance is terminated or shutting down");
return false;
}
// See if we know about this and it has capacity
for (EC2AbstractSlave node : NodeIterator.nodes(EC2AbstractSlave.class)) {
if (node.getInstanceId().equals(existingInstance.getInstanceId())) {
logProvision(logger, "Found existing corresponding Jenkins slave: " + node.getInstanceId());
if (!node.toComputer().isPartiallyIdle()) {
logProvision(logger, " false - Node is not partially idle");
return false;
}
// REMOVEME - this was added to force provision to work, but might not allow
// stopped instances to be found - need to investigate further
else if (false && node.toComputer().isOffline()) {
logProvision(logger, " false - Node is offline");
return false;
} else if (requiredLabel != null && !requiredLabel.matches(node.getAssignedLabels())) {
logProvision(logger, " false - we need a Node having label " + requiredLabel);
return false;
} else {
logProvision(logger, " true - Node has capacity - can use it");
returnNode[0] = node;
return true;
}
}
}
logProvision(logger, " true - Instance has no node, but can be used");
return true;
}
private static void logProvision(PrintStream logger, String message) {
logger.println(message);
LOGGER.fine(message);
}
private static void logProvisionInfo(PrintStream logger, String message) {
logger.println(message);
LOGGER.info(message);
}
/**
* Provisions an On-demand EC2 slave by launching a new instance or starting a previously-stopped instance.
*/
private EC2AbstractSlave provisionOndemand(TaskListener listener, Label requiredLabel, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
try {
logProvisionInfo(logger, "Considering launching " + ami + " for template " + description);
KeyPair keyPair = getKeyPair(ec2);
RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1);
InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification();
riRequest.setEbsOptimized(ebsOptimized);
if (useEphemeralDevices) {
setupEphemeralDeviceMapping(riRequest);
} else {
setupCustomDeviceMapping(riRequest);
}
if(stopOnTerminate){
riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Stop);
logProvisionInfo(logger, "Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Stop");
}else{
riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate);
logProvisionInfo(logger, "Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Terminate");
}
List<Filter> diFilters = new ArrayList<Filter>();
diFilters.add(new Filter("image-id").withValues(ami));
if (StringUtils.isNotBlank(getZone())) {
Placement placement = new Placement(getZone());
if (getUseDedicatedTenancy()) {
placement.setTenancy("dedicated");
}
riRequest.setPlacement(placement);
diFilters.add(new Filter("availability-zone").withValues(getZone()));
}
if (StringUtils.isNotBlank(getSubnetId())) {
if (getAssociatePublicIp()) {
net.setSubnetId(getSubnetId());
} else {
riRequest.setSubnetId(getSubnetId());
}
diFilters.add(new Filter("subnet-id").withValues(getSubnetId()));
/*
* If we have a subnet ID then we can only use VPC security groups
*/
if (!securityGroupSet.isEmpty()) {
List<String> groupIds = getEc2SecurityGroups(ec2);
if (!groupIds.isEmpty()) {
if (getAssociatePublicIp()) {
net.setGroups(groupIds);
} else {
riRequest.setSecurityGroupIds(groupIds);
}
diFilters.add(new Filter("instance.group-id").withValues(groupIds));
}
}
} else {
/* No subnet: we can use standard security groups by name */
riRequest.setSecurityGroups(securityGroupSet);
if (!securityGroupSet.isEmpty()) {
diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet));
}
}
String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8));
riRequest.setUserData(userDataString);
riRequest.setKeyName(keyPair.getKeyName());
diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName()));
riRequest.setInstanceType(type.toString());
diFilters.add(new Filter("instance-type").withValues(type.toString()));
if (getAssociatePublicIp()) {
net.setAssociatePublicIpAddress(true);
net.setDeviceIndex(0);
riRequest.withNetworkInterfaces(net);
}
boolean hasCustomTypeTag = false;
HashSet<Tag> instTags = null;
if (tags != null && !tags.isEmpty()) {
instTags = new HashSet<Tag>();
for (EC2Tag t : tags) {
instTags.add(new Tag(t.getName(), t.getValue()));
diFilters.add(new Filter("tag:" + t.getName()).withValues(t.getValue()));
if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
hasCustomTypeTag = true;
}
}
}
if (!hasCustomTypeTag) {
if (instTags == null) {
instTags = new HashSet<Tag>();
}
// Append template description as well to identify slaves provisioned per template
instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue(
EC2Cloud.EC2_SLAVE_TYPE_DEMAND, description)));
}
DescribeInstancesRequest diRequest = new DescribeInstancesRequest();
diRequest.setFilters(diFilters);
logProvision(logger, "Looking for existing instances with describe-instance: " + diRequest);
DescribeInstancesResult diResult = ec2.describeInstances(diRequest);
EC2AbstractSlave[] ec2Node = new EC2AbstractSlave[1];
Instance existingInstance = null;
if (!provisionOptions.contains(ProvisionOptions.FORCE_CREATE)) {
reservationLoop:
for (Reservation reservation : diResult.getReservations()) {
for (Instance instance : reservation.getInstances()) {
if (checkInstance(logger, instance, requiredLabel, ec2Node)) {
existingInstance = instance;
logProvision(logger, "Found existing instance: " + existingInstance + ((ec2Node[0] != null) ? (" node: " + ec2Node[0].getInstanceId()) : ""));
break reservationLoop;
}
}
}
}
if (existingInstance == null) {
if (!provisionOptions.contains(ProvisionOptions.FORCE_CREATE) &&
!provisionOptions.contains(ProvisionOptions.ALLOW_CREATE)) {
logProvision(logger, "No existing instance found - but cannot create new instance");
return null;
}
if (StringUtils.isNotBlank(getIamInstanceProfile())) {
riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
}
// Have to create a new instance
Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0);
/* Now that we have our instance, we can set tags on it */
if (instTags != null) {
updateRemoteTags(ec2, instTags, "InvalidInstanceID.NotFound", inst.getInstanceId());
// That was a remote request - we should also update our
// local instance data.
inst.setTags(instTags);
}
logProvisionInfo(logger, "No existing instance found - created new instance: " + inst);
return newOndemandSlave(inst);
}
if (existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopping.toString())
|| existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopped.toString())) {
List<String> instances = new ArrayList<String>();
instances.add(existingInstance.getInstanceId());
StartInstancesRequest siRequest = new StartInstancesRequest(instances);
StartInstancesResult siResult = ec2.startInstances(siRequest);
logProvisionInfo(logger, "Found stopped instance - starting it: " + existingInstance + " result:" + siResult);
} else {
// Should be pending or running at this point, just let it come up
logProvisionInfo(logger, "Found existing pending or running: " + existingInstance.getState().getName() + " instance: " + existingInstance);
}
if (ec2Node[0] != null) {
logProvisionInfo(logger, "Using existing slave: " + ec2Node[0].getInstanceId());
return ec2Node[0];
}
// Existing slave not found
logProvision(logger, "Creating new slave for existing instance: " + existingInstance);
return newOndemandSlave(existingInstance);
} catch (FormException e) {
throw new AssertionError(e); // we should have discovered all
// configuration issues upfront
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
private List<BlockDeviceMapping> getNewEphemeralDeviceMapping() {
final List<BlockDeviceMapping> oldDeviceMapping = getAmiBlockDeviceMappings();
final Set<String> occupiedDevices = new HashSet<String>();
for (final BlockDeviceMapping mapping : oldDeviceMapping) {
occupiedDevices.add(mapping.getDeviceName());
}
final List<String> available = new ArrayList<String>(
Arrays.asList("ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3"));
final List<BlockDeviceMapping> newDeviceMapping = new ArrayList<BlockDeviceMapping>(4);
for (char suffix = 'b'; suffix <= 'z' && !available.isEmpty(); suffix++) {
final String deviceName = String.format("/dev/xvd%s", suffix);
if (occupiedDevices.contains(deviceName))
continue;
final BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(deviceName).withVirtualName(
available.get(0));
newDeviceMapping.add(newMapping);
available.remove(0);
}
return newDeviceMapping;
}
private void setupEphemeralDeviceMapping(RunInstancesRequest riRequest) {
riRequest.withBlockDeviceMappings(getNewEphemeralDeviceMapping());
}
private void setupEphemeralDeviceMapping(LaunchSpecification launchSpec) {
launchSpec.withBlockDeviceMappings(getNewEphemeralDeviceMapping());
}
private List<BlockDeviceMapping> getAmiBlockDeviceMappings() {
DescribeImagesRequest request = new DescribeImagesRequest().withImageIds(ami);
for (final Image image : getParent().connect().describeImages(request).getImages()) {
if (ami.equals(image.getImageId())) {
return image.getBlockDeviceMappings();
}
}
throw new AmazonClientException("Unable to get AMI device mapping for " + ami);
}
private void setupCustomDeviceMapping(RunInstancesRequest riRequest) {
if (StringUtils.isNotBlank(customDeviceMapping)) {
riRequest.setBlockDeviceMappings(DeviceMappingParser.parse(customDeviceMapping));
}
}
private void setupCustomDeviceMapping(LaunchSpecification launchSpec) {
if (StringUtils.isNotBlank(customDeviceMapping)) {
launchSpec.setBlockDeviceMappings(DeviceMappingParser.parse(customDeviceMapping));
}
}
/**
* Provision a new slave for an EC2 spot instance to call back to Jenkins
*/
private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
try {
logger.println("Launching " + ami + " for template " + description);
LOGGER.info("Launching " + ami + " for template " + description);
KeyPair keyPair = getKeyPair(ec2);
RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest();
// Validate spot bid before making the request
if (getSpotMaxBidPrice() == null) {
// throw new FormException("Invalid Spot price specified: " +
// getSpotMaxBidPrice(), "spotMaxBidPrice");
throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice());
}
spotRequest.setSpotPrice(getSpotMaxBidPrice());
spotRequest.setInstanceCount(1);
LaunchSpecification launchSpecification = new LaunchSpecification();
InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification();
launchSpecification.setImageId(ami);
launchSpecification.setInstanceType(type);
launchSpecification.setEbsOptimized(ebsOptimized);
if (StringUtils.isNotBlank(getZone())) {
SpotPlacement placement = new SpotPlacement(getZone());
launchSpecification.setPlacement(placement);
}
if (StringUtils.isNotBlank(getSubnetId())) {
if (getAssociatePublicIp()) {
net.setSubnetId(getSubnetId());
} else {
launchSpecification.setSubnetId(getSubnetId());
}
/*
* If we have a subnet ID then we can only use VPC security groups
*/
if (!securityGroupSet.isEmpty()) {
List<String> groupIds = getEc2SecurityGroups(ec2);
if (!groupIds.isEmpty()) {
if (getAssociatePublicIp()) {
net.setGroups(groupIds);
} else {
ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>();
for (String group_id : groupIds) {
GroupIdentifier group = new GroupIdentifier();
group.setGroupId(group_id);
groups.add(group);
}
if (!groups.isEmpty())
launchSpecification.setAllSecurityGroups(groups);
}
}
}
} else {
/* No subnet: we can use standard security groups by name */
if (!securityGroupSet.isEmpty()) {
launchSpecification.setSecurityGroups(securityGroupSet);
}
}
String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8));
launchSpecification.setUserData(userDataString);
launchSpecification.setKeyName(keyPair.getKeyName());
launchSpecification.setInstanceType(type.toString());
if (getAssociatePublicIp()) {
net.setAssociatePublicIpAddress(true);
net.setDeviceIndex(0);
launchSpecification.withNetworkInterfaces(net);
}
boolean hasCustomTypeTag = false;
HashSet<Tag> instTags = null;
if (tags != null && !tags.isEmpty()) {
instTags = new HashSet<Tag>();
for (EC2Tag t : tags) {
instTags.add(new Tag(t.getName(), t.getValue()));
if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
hasCustomTypeTag = true;
}
}
}
if (!hasCustomTypeTag) {
if (instTags == null) {
instTags = new HashSet<Tag>();
}
instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue(
EC2Cloud.EC2_SLAVE_TYPE_SPOT, description)));
}
if (StringUtils.isNotBlank(getIamInstanceProfile())) {
launchSpecification.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
}
if (useEphemeralDevices) {
setupEphemeralDeviceMapping(launchSpecification);
} else {
setupCustomDeviceMapping(launchSpecification);
}
spotRequest.setLaunchSpecification(launchSpecification);
// Make the request for a new Spot instance
RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest);
List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests();
if (reqInstances.isEmpty()) {
throw new AmazonClientException("No spot instances found");
}
SpotInstanceRequest spotInstReq = reqInstances.get(0);
if (spotInstReq == null) {
throw new AmazonClientException("Spot instance request is null");
}
String slaveName = spotInstReq.getSpotInstanceRequestId();
/* Now that we have our Spot request, we can set tags on it */
if (instTags != null) {
updateRemoteTags(ec2, instTags, "InvalidSpotInstanceRequestID.NotFound", spotInstReq.getSpotInstanceRequestId());
// That was a remote request - we should also update our local
// instance data.
spotInstReq.setTags(instTags);
}
logger.println("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId());
LOGGER.info("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId());
return newSpotSlave(spotInstReq, slaveName);
} catch (FormException e) {
throw new AssertionError(); // we should have discovered all
// configuration issues upfront
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
protected EC2OndemandSlave newOndemandSlave(Instance inst) throws FormException, IOException {
return new EC2OndemandSlave(inst.getInstanceId(), description, remoteFS, getNumExecutors(), labels, mode, initScript,
tmpDir, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, inst.getPublicDnsName(),
inst.getPrivateDnsName(), EC2Tag.fromAmazonTags(inst.getTags()), parent.name, usePrivateDnsName,
useDedicatedTenancy, getLaunchTimeout(), amiType);
}
protected EC2SpotSlave newSpotSlave(SpotInstanceRequest sir, String name) throws FormException, IOException {
return new EC2SpotSlave(name, sir.getSpotInstanceRequestId(), description, remoteFS, getNumExecutors(), mode, initScript,
tmpDir, labels, remoteAdmin, jvmopts, idleTerminationMinutes, EC2Tag.fromAmazonTags(sir.getTags()), parent.name,
usePrivateDnsName, getLaunchTimeout(), amiType);
}
/**
* Get a KeyPair from the configured information for the slave template
*/
private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException {
KeyPair keyPair = parent.getPrivateKey().find(ec2);
if (keyPair == null) {
throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?");
}
return keyPair;
}
/**
* Update the tags stored in EC2 with the specified information. Re-try 5 times if instances isn't up by
* catchErrorCode - e.g. InvalidSpotInstanceRequestID.NotFound or InvalidInstanceRequestID.NotFound
*
* @param ec2
* @param instTags
* @param catchErrorCode
* @param params
* @throws InterruptedException
*/
private void updateRemoteTags(AmazonEC2 ec2, Collection<Tag> instTags, String catchErrorCode, String... params)
throws InterruptedException {
for (int i = 0; i < 5; i++) {
try {
CreateTagsRequest tagRequest = new CreateTagsRequest();
tagRequest.withResources(params).setTags(instTags);
ec2.createTags(tagRequest);
break;
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals(catchErrorCode)) {
Thread.sleep(5000);
continue;
}
LOGGER.log(Level.SEVERE, e.getErrorMessage(), e);
}
}
}
/**
* Get a list of security group ids for the slave
*/
private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException {
List<String> groupIds = new ArrayList<String>();
DescribeSecurityGroupsResult groupResult = getSecurityGroupsBy("group-name", securityGroupSet, ec2);
if (groupResult.getSecurityGroups().size() == 0) {
groupResult = getSecurityGroupsBy("group-id", securityGroupSet, ec2);
}
for (SecurityGroup group : groupResult.getSecurityGroups()) {
if (group.getVpcId() != null && !group.getVpcId().isEmpty()) {
List<Filter> filters = new ArrayList<Filter>();
filters.add(new Filter("vpc-id").withValues(group.getVpcId()));
filters.add(new Filter("state").withValues("available"));
filters.add(new Filter("subnet-id").withValues(getSubnetId()));
DescribeSubnetsRequest subnetReq = new DescribeSubnetsRequest();
subnetReq.withFilters(filters);
DescribeSubnetsResult subnetResult = ec2.describeSubnets(subnetReq);
List<Subnet> subnets = subnetResult.getSubnets();
if (subnets != null && !subnets.isEmpty()) {
groupIds.add(group.getGroupId());
}
}
}
if (securityGroupSet.size() != groupIds.size()) {
throw new AmazonClientException("Security groups must all be VPC security groups to work in a VPC context");
}
return groupIds;
}
private DescribeSecurityGroupsResult getSecurityGroupsBy(String filterName, Set<String> filterValues, AmazonEC2 ec2) {
DescribeSecurityGroupsRequest groupReq = new DescribeSecurityGroupsRequest();
groupReq.withFilters(new Filter(filterName).withValues(filterValues));
return ec2.describeSecurityGroups(groupReq);
}
/**
* Provisions a new EC2 slave based on the currently running instance on EC2, instead of starting a new one.
*/
public EC2AbstractSlave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
try {
logger.println("Attaching to " + instanceId);
LOGGER.info("Attaching to " + instanceId);
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.setInstanceIds(Collections.singletonList(instanceId));
Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0);
return newOndemandSlave(inst);
} catch (FormException e) {
throw new AssertionError(); // we should have discovered all
// configuration issues upfront
}
}
/**
* Initializes data structure that we don't persist.
*/
protected Object readResolve() {
labelSet = Label.parse(labels);
securityGroupSet = parseSecurityGroups();
/**
* In releases of this plugin prior to 1.18, template-specific instance caps could be configured but were not
* enforced. As a result, it was possible to have the instance cap for a template be configured to 0 (zero) with
* no ill effects. Starting with version 1.18, template-specific instance caps are enforced, so if a
* configuration has a cap of zero for a template, no instances will be launched from that template. Since there
* is no practical value of intentionally setting the cap to zero, this block will override such a setting to a
* value that means 'no cap'.
*/
if (instanceCap == 0) {
instanceCap = Integer.MAX_VALUE;
}
if (amiType == null) {
amiType = new UnixData(rootCommandPrefix, sshPort);
}
return this;
}
public Descriptor<SlaveTemplate> getDescriptor() {
return Jenkins.getInstance().getDescriptor(getClass());
}
public int getLaunchTimeout() {
return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout;
}
public String getLaunchTimeoutStr() {
if (launchTimeout == Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(launchTimeout);
}
}
public boolean isWindowsSlave() {
return amiType.isWindows();
}
public boolean isUnixSlave() {
return amiType.isUnix();
}
public Secret getAdminPassword() {
return amiType.isWindows() ? ((WindowsData) amiType).getPassword() : Secret.fromString("");
}
public boolean isUseHTTPS() {
return amiType.isWindows() && ((WindowsData) amiType).isUseHTTPS();
}
@Extension
public static final class DescriptorImpl extends Descriptor<SlaveTemplate> {
@Override
public String getDisplayName() {
return null;
}
public List<Descriptor<AMITypeData>> getAMITypeDescriptors() {
return Jenkins.getInstance().<AMITypeData, Descriptor<AMITypeData>> getDescriptorList(AMITypeData.class);
}
/**
* Since this shares much of the configuration with {@link EC2Computer}, check its help page, too.
*/
@Override
public String getHelpFile(String fieldName) {
String p = super.getHelpFile(fieldName);
if (p == null)
p = Jenkins.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName);
if (p == null)
p = Jenkins.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName);
return p;
}
/***
* Check that the AMI requested is available in the cloud and can be used.
*/
public FormValidation doValidateAmi(@QueryParameter boolean useInstanceProfileForCredentials,
@QueryParameter String credentialsId, @QueryParameter String ec2endpoint,
@QueryParameter String region, final @QueryParameter String ami) throws IOException {
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials,
credentialsId);
AmazonEC2 ec2;
if (region != null) {
ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region));
} else {
ec2 = EC2Cloud.connect(credentialsProvider, new URL(ec2endpoint));
}
if (ec2 != null) {
try {
List<String> images = new LinkedList<String>();
images.add(ami);
List<String> owners = new LinkedList<String>();
List<String> users = new LinkedList<String>();
DescribeImagesRequest request = new DescribeImagesRequest();
request.setImageIds(images);
request.setOwners(owners);
request.setExecutableUsers(users);
List<Image> img = ec2.describeImages(request).getImages();
if (img == null || img.isEmpty()) {
// de-registered AMI causes an empty list to be
// returned. so be defensive
// against other possibilities
return FormValidation.error("No such AMI, or not usable with this accessId: " + ami);
}
String ownerAlias = img.get(0).getImageOwnerAlias();
return FormValidation.ok(img.get(0).getImageLocation() + (ownerAlias != null ? " by " + ownerAlias : ""));
} catch (AmazonClientException e) {
return FormValidation.error(e.getMessage());
}
} else
return FormValidation.ok(); // can't test
}
public FormValidation doCheckLabelString(@QueryParameter String value, @QueryParameter Node.Mode mode) {
if (mode == Node.Mode.EXCLUSIVE && (value == null || value.trim().isEmpty())) {
return FormValidation.warning("You may want to assign labels to this node;"
+ " it's marked to only run jobs that are exclusively tied to itself or a label.");
}
return FormValidation.ok();
}
public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) {
if (value == null || value.trim().isEmpty())
return FormValidation.ok();
try {
int val = Integer.parseInt(value);
if (val >= -59)
return FormValidation.ok();
} catch (NumberFormatException nfe) {
}
return FormValidation.error("Idle Termination time must be a greater than -59 (or null)");
}
public FormValidation doCheckInstanceCapStr(@QueryParameter String value) {
if (value == null || value.trim().isEmpty())
return FormValidation.ok();
try {
int val = Integer.parseInt(value);
if (val > 0)
return FormValidation.ok();
} catch (NumberFormatException nfe) {
}
return FormValidation.error("InstanceCap must be a non-negative integer (or null)");
}
public FormValidation doCheckLaunchTimeoutStr(@QueryParameter String value) {
if (value == null || value.trim().isEmpty())
return FormValidation.ok();
try {
int val = Integer.parseInt(value);
if (val >= 0)
return FormValidation.ok();
} catch (NumberFormatException nfe) {
}
return FormValidation.error("Launch Timeout must be a non-negative integer (or null)");
}
public ListBoxModel doFillZoneItems(@QueryParameter boolean useInstanceProfileForCredentials,
@QueryParameter String credentialsId, @QueryParameter String region)
throws IOException, ServletException {
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials,
credentialsId);
return EC2AbstractSlave.fillZoneItems(credentialsProvider, region);
}
/*
* Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001
*/
public FormValidation doCheckSpotMaxBidPrice(@QueryParameter String spotMaxBidPrice) {
if (SpotConfiguration.normalizeBid(spotMaxBidPrice) != null) {
return FormValidation.ok();
}
return FormValidation.error("Not a correct bid price");
}
// Retrieve the availability zones for the region
private ArrayList<String> getAvailabilityZones(AmazonEC2 ec2) {
ArrayList<String> availabilityZones = new ArrayList<String>();
DescribeAvailabilityZonesResult zones = ec2.describeAvailabilityZones();
List<AvailabilityZone> zoneList = zones.getAvailabilityZones();
for (AvailabilityZone z : zoneList) {
availabilityZones.add(z.getZoneName());
}
return availabilityZones;
}
/*
* Check the current Spot price of the selected instance type for the selected region
*/
public FormValidation doCurrentSpotPrice(@QueryParameter boolean useInstanceProfileForCredentials,
@QueryParameter String credentialsId, @QueryParameter String region,
@QueryParameter String type, @QueryParameter String zone) throws IOException, ServletException {
String cp = "";
String zoneStr = "";
// Connect to the EC2 cloud with the access id, secret key, and
// region queried from the created cloud
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials,
credentialsId);
AmazonEC2 ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region));
if (ec2 != null) {
try {
// Build a new price history request with the currently
// selected type
DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest();
// If a zone is specified, set the availability zone in the
// request
// Else, proceed with no availability zone which will result
// with the cheapest Spot price
if (getAvailabilityZones(ec2).contains(zone)) {
request.setAvailabilityZone(zone);
zoneStr = zone + " availability zone";
} else {
zoneStr = region + " region";
}
/*
* Iterate through the AWS instance types to see if can find a match for the databound String type.
* This is necessary because the AWS API needs the instance type string formatted a particular way
* to retrieve prices and the form gives us the strings in a different format. For example "T1Micro"
* vs "t1.micro".
*/
InstanceType ec2Type = null;
for (InstanceType it : InstanceType.values()) {
if (it.name().equals(type)) {
ec2Type = it;
break;
}
}
/*
* If the type string cannot be matched with an instance type, throw a Form error
*/
if (ec2Type == null) {
return FormValidation.error("Could not resolve instance type: " + type);
}
Collection<String> instanceType = new ArrayList<String>();
instanceType.add(ec2Type.toString());
request.setInstanceTypes(instanceType);
request.setStartTime(new Date());
// Retrieve the price history request result and store the
// current price
DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory(request);
if (!result.getSpotPriceHistory().isEmpty()) {
SpotPrice currentPrice = result.getSpotPriceHistory().get(0);
cp = currentPrice.getSpotPrice();
}
} catch (AmazonServiceException e) {
return FormValidation.error(e.getMessage());
}
}
/*
* If we could not return the current price of the instance display an error Else, remove the additional
* zeros from the current price and return it to the interface in the form of a message
*/
if (cp.isEmpty()) {
return FormValidation.error("Could not retrieve current Spot price");
} else {
cp = cp.substring(0, cp.length() - 3);
return FormValidation.ok("The current Spot price for a " + type + " in the " + zoneStr + " is $" + cp);
}
}
}
} |
package jenkins.plugins.play;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jenkins.model.Jenkins;
import jenkins.plugins.play.commands.PlayCommand;
import jenkins.plugins.play.version.Play1x;
import jenkins.plugins.play.version.PlayVersion;
import jenkins.plugins.play.version.PlayVersionDescriptor;
import jenkins.tasks.SimpleBuildStep;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Proc;
import hudson.model.AbstractProject;
import hudson.model.Run;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
/**
* Provides the several of the functionalities of Play!Framework in a Jenkins
* plugin. This class is responsible for the Play!Framework module in the job
* configuration.
*
*/
public class PlayBuilder extends Builder implements SimpleBuildStep {
/** The Play installation path selected by the user. */
private final String playToolHome;
/** Absolute or relative project path. */
private final String projectPath;
/** Play version used in the job. Indicates the command set available. */
private PlayVersion playVersion;
/**
* Constructor used by Jenkins to handle the Play! job.
*
* @param playToolHome Path of Play! installation.
* @param projectPath Project path.
* @param playVersion Play version.
*/
@DataBoundConstructor
public PlayBuilder(String playToolHome, String projectPath, PlayVersion playVersion) {
this.playToolHome = playToolHome;
this.projectPath = projectPath;
this.playVersion = playVersion;
}
/**
* Get the path of the Play! installation.
*
* @return the playToolHome
*/
public String getPlayToolHome() {
return playToolHome;
}
/**
* Get the project path.
*
* @return the projectPath
*/
public String getProjectPath() {
return projectPath;
}
/**
* @return the Play version.
*/
public final PlayVersion getPlayVersion() {
return playVersion;
}
/**
* Get the complete path of the Play! executable. First looks for a 'play' executable, then 'activator'.
*
* @param playToolHome Path of the Play tool home.
* @return the Play! executable path.
*/
public static File getPlayExecutable(String playToolHome) {
// Try play executable first
File playExecutable = new File(playToolHome + "/play");
if (playExecutable.exists())
return playExecutable;
// Try activator executable
playExecutable = new File(playToolHome + "/activator");
if (playExecutable.exists())
return playExecutable;
// There is no potential executor here. Return null.
return null;
}
/*
* (non-Javadoc)
*
* @see hudson.tasks.Builder#getDescriptor()
*/
@Override
public PlayDescriptor getDescriptor() {
return (PlayDescriptor) super.getDescriptor();
}
/**
* Generate the list of command parameters according to the user selection
* on Jenkins interface.
*
* @return List of parameters
*/
public List<String> generatePlayParameters() {
List<String> commandParameters = new ArrayList<String>();
// This parameter is always present to remove color formatting
// characters from the output. (Except for Play 1.x)
if (!(this.playVersion instanceof Play1x))
commandParameters.add("-Dsbt.log.noformat=true");
// add extension actions to command-line one by one
for (PlayCommand playExt : this.playVersion.getCommands()) {
// Every command parameter can be surrounded by quotes, have them
// additional parameters or not.
// HOWEVER, the launcher already adds quotes automatically
// whenever the parameter is composed of two or more strings.
// Therefore, no need to add the quotes here.
String command = playExt.getCommand() + " " + playExt.getParameter();
// Trim the String to remove leading and trailing whitespace (just
// esthetical reason)
// Add generated parameter to the array of parameters
commandParameters.add(command.trim());
}
return commandParameters;
}
/**
* Descriptor to capture and validate fields from the interface.
*/
@Extension
public static class PlayDescriptor extends
BuildStepDescriptor<Builder> {
/**
* Descriptor constructor.
*/
public PlayDescriptor() {
load();
}
public PlayDescriptor(Class<? extends Builder> clazz) {
super(clazz);
load();
}
/*
* (non-Javadoc)
*
* @see hudson.tasks.BuildStepDescriptor#isApplicable(java.lang.Class)
*/
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
/*
* (non-Javadoc)
*
* @see hudson.model.Descriptor#getDisplayName()
*/
@Override
public String getDisplayName() {
return "Invoke Play!Framework";
}
/**
* Get available Play! installations.
*
* @return Array of Play installations
*/
public PlayInstallation[] getInstallations() {
return Jenkins.getInstance()
.getDescriptorByType(PlayInstallation.PlayToolDescriptor.class)
.getInstallations();
}
/**
* Retrieve list of Play! versions.
* @return
*/
public List<PlayVersionDescriptor> getPlayVersion() {
return Jenkins.getInstance().getDescriptorList(PlayVersion.class);
}
/**
* Check if the project path field is not empty and exists.
*
* @param projectPath
* Project path
* @return Form validation
*/
public FormValidation doCheckProjectPath(@QueryParameter String projectPath) {
// If field is empty, notify
return FormValidation.validateRequired(projectPath);
}
}
@Override
public void perform(Run<?, ?> run, FilePath filepath, Launcher launcher,
TaskListener listener) throws InterruptedException, IOException {
// Create file from play path String
File playExecutable = PlayBuilder.getPlayExecutable(this.playToolHome);
filepath = new FilePath(filepath, projectPath);
// Check if play executable exists
if (playExecutable == null) {
listener.getLogger().println("ERROR! Play executable not found!");
run.setResult(Result.FAILURE);
return;
}
// Check if project folder exists
if (!filepath.exists()) {
listener.getLogger().println("ERROR! Project path not found!");
run.setResult(Result.FAILURE);
return;
}
// Creates the complete list of parameters including goals
List<String> commandParameters = generatePlayParameters();
// Validated that there are commands set up
if (commandParameters == null) {
listener.getLogger().println("ERROR! No commands were provided.");
run.setResult(Result.FAILURE);
return;
}
for (String comm : commandParameters) {
listener.getLogger().println("Command detected: " + comm);
}
// Play 1.x is not able to execute several commands in sequence.
// Instead, it should call the 'play' executable for every command
// separately.
if (this.getPlayVersion() instanceof Play1x) {
// For each command...
for (String comm : commandParameters) {
// In Play1x, commands should not have quotes. Since the
// launcher automatically adds quotes if the command contains
// whitespace, it is necessary to split the command in the
// whitespaces first and provide them to the launcher as an
// array.
// ... run it in a new process.
Proc proc = launcher.launch()
.cmds(playExecutable, comm.split(" ")).pwd(filepath)
.writeStdin().stdout(listener.getLogger())
.stderr(listener.getLogger()).start();
int result = proc.join();
// Immediately stop the build process when a command results in
// error.
if (result != 0) {
listener.getLogger().println(
"ERROR! Failed to execute the Play! command.");
run.setResult(Result.FAILURE);
return;
}
}
// Every command ran successfully
run.setResult(Result.SUCCESS);
}
// Play 2.x (sbt) is able to execute all commands at once
else {
// Launch Play!Framework
Proc proc = launcher
.launch()
.cmds(playExecutable,
commandParameters
.toArray(new String[commandParameters
.size()])).pwd(filepath)
.writeStdin().stdout(listener.getLogger())
.stderr(listener.getLogger()).start();
if (proc.join() == 0)
run.setResult(Result.SUCCESS);
else run.setResult(Result.FAILURE);
}
}
} |
package link.webarata3.poi;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
/**
* Apache POI
*
* @author webarata3
*/
public class BenrippoiUtil {
/**
* Excel
*
* @param fileName Excel
* @return Excel Workbook
* @throws IOException
* @throws InvalidFormatException
*/
public static Workbook open(String fileName) throws IOException, InvalidFormatException {
InputStream is = Files.newInputStream(Paths.get(fileName));
return open(is);
}
/**
* Excel
*
* @param is ExcelInputStream
* @return Excel Workbook
* @throws IOException
* @throws InvalidFormatException
*/
public static Workbook open(InputStream is) throws IOException, InvalidFormatException {
return WorkbookFactory.create(is);
}
/**
* ExcelA1B2
*
* @param x 0
* @param y 0
* @return
*/
public static String cellIndexToCellLabel(int x, int y) {
String cellName = dec26(x, 0);
return cellName + (y + 1);
}
private static String dec26(int num, int first) {
return (num > 25 ? dec26(num / 26, 1) : "") + String.valueOf((char) ('A' + (num - first) % 26));
}
/**
* Row
*
* @param sheet
* @param y 0
* @return Row
*/
public static Row getRow(Sheet sheet, int y) {
Row row = sheet.getRow(y);
if (row != null) {
return row;
}
return sheet.createRow(y);
}
/**
* Cell
*
* @param sheet
* @param x 0
* @param y 0
* @return Cell
*/
public static Cell getCell(Sheet sheet, int x, int y) {
Row row = sheet.getRow(y);
Cell cell = row.getCell(x);
if (cell != null) {
return cell;
}
return row.createCell(x, CellType.BLANK);
}
/**
* A1B2
*
* @param sheet
* @param cellLabel A1B2
* @return Cell
*/
public static Cell getCell(Sheet sheet, String cellLabel) {
Pattern p1 = Pattern.compile("([a-zA-Z]+)([0-9]+)");
Matcher matcher = p1.matcher(cellLabel);
matcher.find();
String reverseString = new StringBuilder(matcher.group(1).toUpperCase()).reverse().toString();
int x = IntStream.range(0, reverseString.length()).map((i) -> {
int delta = reverseString.charAt(i) - 'A' + 1;
return delta * (int) Math.pow(26.0, (double) i);
}).reduce(-1, (v1, v2) -> v1 + v2);
return getCell(sheet, x, Integer.parseInt(matcher.group(2)) - 1);
}
/**
*
*
* @param numeric
* @return
*/
public static String normalizeNumericString(double numeric) {
// 44.044
// int
if (numeric == Math.ceil(numeric)) {
return String.valueOf((int) numeric);
}
return String.valueOf(numeric);
}
/**
*
*
* @param cell
* @return CellValue
*/
public static CellValue getFomulaCellValue(Cell cell) {
Workbook wb = cell.getSheet().getWorkbook();
CreationHelper helper = wb.getCreationHelper();
FormulaEvaluator evaluator = helper.createFormulaEvaluator();
return evaluator.evaluate(cell);
}
/**
* String
*
* @param cell
* @return String
*/
public static String cellToString(Cell cell) {
switch (cell.getCellTypeEnum()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
return normalizeNumericString(cell.getNumericCellValue());
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case BLANK:
return "";
case FORMULA:
CellValue cellValue = getFomulaCellValue(cell);
switch (cellValue.getCellTypeEnum()) {
case STRING:
return cellValue.getStringValue();
case NUMERIC:
return normalizeNumericString(cellValue.getNumberValue());
case BOOLEAN:
return String.valueOf(cellValue.getBooleanValue());
case BLANK:
return "";
default: // _NONE, ERROR
throw new PoiIllegalAccessException("cellString");
}
default: // _NONE, ERROR
throw new PoiIllegalAccessException("cellString");
}
}
private static int stringToInt(String value) {
try {
return (int) Double.parseDouble(value);
} catch (NumberFormatException e) {
throw new IllegalStateException("cellint");
}
}
/**
* int
*
* @param cell
* @return int
*/
public static int cellToInt(Cell cell) {
switch (cell.getCellTypeEnum()) {
case STRING:
return stringToInt(cell.getStringCellValue());
case NUMERIC:
return (int) cell.getNumericCellValue();
case FORMULA:
CellValue cellValue = getFomulaCellValue(cell);
switch (cellValue.getCellTypeEnum()) {
case STRING:
return stringToInt(cellValue.getStringValue());
case NUMERIC:
return (int) cellValue.getNumberValue();
default:
throw new PoiIllegalAccessException("cellint");
}
default:
throw new PoiIllegalAccessException("cellint");
}
}
private static double stringToDouble(String value) {
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
throw new PoiIllegalAccessException("celldouble");
}
}
/**
* double
*
* @param cell
* @return double
*/
public static double cellToDouble(Cell cell) {
switch (cell.getCellTypeEnum()) {
case STRING:
return stringToDouble(cell.getStringCellValue());
case NUMERIC:
return cell.getNumericCellValue();
case FORMULA:
CellValue cellValue = getFomulaCellValue(cell);
switch (cellValue.getCellTypeEnum()) {
case STRING:
return stringToDouble(cell.getStringCellValue());
case NUMERIC:
return cell.getNumericCellValue();
default:
throw new PoiIllegalAccessException("celldouble");
}
default:
throw new PoiIllegalAccessException("celldouble");
}
}
} |
package lv.ctco.scm.mobile.utils;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp;
import org.apache.commons.compress.archivers.zip.X7875_NewUnix;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipExtraField;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
public final class ZipUtil {
private static final Logger logger = Logging.getLogger(ZipUtil.class);
private static final List<String> DEFAULT_EXCLUDES = Collections.singletonList(".DS_Store");
private ZipUtil() {}
public static List<String> getEntryNames(File sourceZip) throws IOException {
List<String> entryNames = new ArrayList<>();
try (ZipFile zipFile = new ZipFile(sourceZip)) {
List<ZipArchiveEntry> zipArchiveEntries = Collections.list(zipFile.getEntries());
for (ZipArchiveEntry zipArchiveEntry : zipArchiveEntries) {
entryNames.add(zipArchiveEntry.getName());
}
}
return entryNames;
}
public static void extractAll(File sourceZip, File outputDir) throws IOException {
try (ZipFile zipFile = new ZipFile(sourceZip)) {
List<ZipArchiveEntry> zipArchiveEntries = Collections.list(zipFile.getEntries());
for (ZipArchiveEntry zipArchiveEntry : zipArchiveEntries) {
extract(zipArchiveEntry, zipFile, outputDir);
}
}
}
public static void extract(String zipArchiveEntryName, File sourceZip, File outputDir) throws IOException {
try (ZipFile zipFile = new ZipFile(sourceZip)) {
ZipArchiveEntry zipArchiveEntry = zipFile.getEntry(zipArchiveEntryName);
extract(zipArchiveEntry, zipFile, outputDir);
}
}
private static void extract(ZipArchiveEntry zipArchiveEntry, ZipFile zipFile, File outputDir) throws IOException {
File extractedFile = new File(outputDir, zipArchiveEntry.getName());
FileUtils.forceMkdir(extractedFile.getParentFile());
if (zipArchiveEntry.isUnixSymlink()) {
if (PosixUtil.isPosixFileStore(outputDir)) {
logger.debug("Extracting [l] "+zipArchiveEntry.getName());
String symlinkTarget = zipFile.getUnixSymlink(zipArchiveEntry);
Files.createSymbolicLink(extractedFile.toPath(), new File(symlinkTarget).toPath());
} else {
logger.debug("Skipping ! [l] "+zipArchiveEntry.getName());
}
} else if (zipArchiveEntry.isDirectory()) {
logger.debug("Extracting [d] "+zipArchiveEntry.getName());
FileUtils.forceMkdir(extractedFile);
} else {
logger.debug("Extracting [f] "+zipArchiveEntry.getName());
try (
InputStream in = zipFile.getInputStream(zipArchiveEntry);
OutputStream out = new FileOutputStream(extractedFile)
) {
IOUtils.copy(in, out);
}
}
updatePermissions(extractedFile, zipArchiveEntry.getUnixMode());
}
private static void updatePermissions(File file, int unixMode) throws IOException {
if (!Files.isSymbolicLink(file.toPath()) && PosixUtil.isPosixFileStore(file)) {
Set<PosixFilePermission> permissions = PosixUtil.getPosixPermissionsAsSet(unixMode);
if (!permissions.isEmpty()) {
Files.setPosixFilePermissions(file.toPath(), permissions);
}
}
}
public static void compressDirectory(File rootDir, boolean includeAsRoot, File output) throws IOException {
if (!rootDir.isDirectory()) {
throw new IOException("Provided file is not a directory");
}
FileUtils.touch(output);
try (OutputStream archiveStream = new FileOutputStream(output);
ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream)) {
String rootName = "";
if (includeAsRoot) {
insertDirectory(rootDir, rootDir.getName(), archive);
rootName = rootDir.getName()+"/";
}
Collection<File> fileCollection = FileUtils.listFilesAndDirs(rootDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE);
for (File file : fileCollection) {
String relativePath = getRelativePath(rootDir, file);
String entryName = rootName+relativePath;
if (!relativePath.isEmpty() && !"/".equals(relativePath)) {
insertObject(file, entryName, archive);
}
}
archive.finish();
} catch (IOException | ArchiveException e) {
throw new IOException(e);
}
}
private static void insertObject(File file, String entryName, ArchiveOutputStream archive) throws IOException {
if (Files.isSymbolicLink(file.toPath())) {
insertSymlink(file, entryName, Files.readSymbolicLink(file.toPath()).toString(), archive);
} else if (file.isDirectory()) {
insertDirectory(file, entryName, archive);
} else if (file.isFile()) {
insertFile(file, entryName, archive);
}
}
private static void insertSymlink(File file, String entryName, String linkTarget, ArchiveOutputStream archive) throws IOException {
if (Files.isSymbolicLink(file.toPath())) {
ZipArchiveEntry newEntry = new ZipArchiveEntry(entryName);
setExtraFields(file.toPath(), UnixStat.LINK_FLAG, newEntry);
archive.putArchiveEntry(newEntry);
archive.write(linkTarget.getBytes());
archive.closeArchiveEntry();
} else {
throw new IOException("Provided file is not a symlink");
}
}
private static void insertDirectory(File dir, String entryName, ArchiveOutputStream archive) throws IOException {
if (dir.isDirectory()) {
ZipArchiveEntry newEntry = new ZipArchiveEntry(entryName+"/");
setExtraFields(dir.toPath(), UnixStat.DIR_FLAG, newEntry);
archive.putArchiveEntry(newEntry);
archive.closeArchiveEntry();
} else {
throw new IOException("Provided file is not a directory");
}
}
private static void insertFile(File file, String entryName, ArchiveOutputStream archive) throws IOException {
if (DEFAULT_EXCLUDES.contains(file.getName())) {
logger.debug("Skipping ! [l] {}", entryName);
return;
}
if (file.isFile()) {
ZipArchiveEntry newEntry = new ZipArchiveEntry(entryName);
setExtraFields(file.toPath(), UnixStat.FILE_FLAG, newEntry);
archive.putArchiveEntry(newEntry);
BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
IOUtils.copy(input, archive);
input.close();
archive.closeArchiveEntry();
} else {
throw new IOException("Provided file is not a file");
}
}
private static void setExtraFields(Path filePath, int fileType, ZipArchiveEntry entry) throws IOException {
if (PosixUtil.isPosixFileStore(filePath)) {
Set<PosixFilePermission> perms = Files.getPosixFilePermissions(filePath);
entry.setUnixMode(fileType | PosixUtil.getPosixPermissionsAsInt(perms));
X5455_ExtendedTimestamp x5455 = getX5455(filePath);
X7875_NewUnix x7875 = getX7875(filePath);
if (x5455 != null && x7875 != null) {
entry.setExtraFields(new ZipExtraField[] {x5455, x7875});
}
}
}
private static X5455_ExtendedTimestamp getX5455(Path filePath) throws IOException {
X5455_ExtendedTimestamp x5455 = null;
if (PosixUtil.isPosixFileStore(filePath)) {
Map<String, Object> fileAttr = getFileAttributes(filePath);
if (fileAttr.get("lastModifiedTime") != null && fileAttr.get("lastAccessTime") != null) {
x5455 = new X5455_ExtendedTimestamp();
x5455.setModifyJavaTime(new Date(((FileTime)fileAttr.get("lastModifiedTime")).toMillis()));
x5455.setAccessJavaTime(new Date(((FileTime)fileAttr.get("lastAccessTime")).toMillis()));
}
}
return x5455;
}
private static X7875_NewUnix getX7875(Path filePath) throws IOException {
X7875_NewUnix x7875 = null;
if (PosixUtil.isPosixFileStore(filePath)) {
Map<String, Object> fileAttr = getFileAttributes(filePath);
if (fileAttr.get("gid") != null && fileAttr.get("uid") != null) {
x7875 = new X7875_NewUnix();
x7875.setGID(Long.valueOf(fileAttr.get("gid").toString()));
x7875.setUID(Long.valueOf(fileAttr.get("uid").toString()));
}
}
return x7875;
}
private static Map<String, Object> getFileAttributes(Path path) throws IOException {
return Files.readAttributes(path, "unix:*", LinkOption.NOFOLLOW_LINKS);
}
private static String getRelativePath(File base, File path) {
return base.toPath().relativize(path.toPath()).toString().replace("\\", "/");
}
} |
package net.alpenblock.bungeeperms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.config.ServerInfo;
/**
* The Class Group.
*/
public class Group implements Comparable<Group>
{
private Map<String,List<String>> cachedPerms;
private String name;
private List<String> inheritances;
private List<String> perms;
private Map<String,Server> servers;
private int rank;
private String ladder;
private boolean isdefault;
private String display;
private String prefix;
private String suffix;
public Group(String name, List<String> inheritances, List<String> perms, Map<String,Server> servers, int rank, String ladder, boolean isdefault, String display, String prefix, String suffix)
{
cachedPerms=new HashMap<>();
this.isdefault = isdefault;
this.name = name;
this.perms = perms;
this.servers = servers;
this.rank = rank;
this.ladder = ladder;
this.inheritances = inheritances;
this.display = display;
this.prefix = prefix;
this.suffix = suffix;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getInheritances() {
return inheritances;
}
public void setInheritances(List<String> inheritances) {
this.inheritances = inheritances;
}
public List<String> getPerms() {
return perms;
}
public void setPerms(List<String> perms) {
this.perms = perms;
}
public Map<String, Server> getServers() {
return servers;
}
public void setServers(Map<String, Server> servers) {
this.servers = servers;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getLadder() {
return ladder;
}
public void setLadder(String ladder) {
this.ladder = ladder;
}
public boolean isDefault() {
return isdefault;
}
public void setIsdefault(boolean isdefault) {
this.isdefault = isdefault;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public List<String> getEffectivePerms()
{
List<String> effperms=cachedPerms.get("global");
if(effperms==null)
{
effperms=calcEffectivePerms();
cachedPerms.put("global", effperms);
}
return effperms;
}
public List<String> getEffectivePerms(ServerInfo server)
{
List<String> effperms=cachedPerms.get(server.getName().toLowerCase());
if(effperms==null)
{
effperms=calcEffectivePerms(server);
cachedPerms.put(server.getName().toLowerCase(), effperms);
}
return effperms;
}
public List<String> getEffectivePerms(ServerInfo server,String world)
{
List<String> effperms=cachedPerms.get(server.getName().toLowerCase()+";"+world.toLowerCase());
if(effperms==null)
{
effperms=calcEffectivePerms(server,world);
cachedPerms.put(server.getName().toLowerCase()+";"+world.toLowerCase(), effperms);
}
return effperms;
}
public List<String> calcEffectivePerms()
{
List<String> ret=new ArrayList<>();
for(Group g:BungeePerms.getInstance().getPermissionsManager().getGroups())
{
if(inheritances.contains(g.getName()))
{
List<String> gperms=g.getEffectivePerms();
for(String perm:gperms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(perm))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+perm))
{
ret.set(i,perm);
added=true;
break;
}
else if(perm.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(perm);
}
}
}
}
for(String s:perms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(s))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+s))
{
ret.set(i,s);
added=true;
break;
}
else if(s.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(s);
}
}
return ret;
}
public List<String> calcEffectivePerms(ServerInfo server)
{
List<String> ret=new ArrayList<>();
for(Group g:BungeePerms.getInstance().getPermissionsManager().getGroups())
{
if(inheritances.contains(g.getName()))
{
List<String> gperms=g.getEffectivePerms(server);
for(String perm:gperms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(perm))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+perm))
{
ret.set(i,perm);
added=true;
break;
}
else if(perm.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(perm);
}
}
}
//per server perms
// Server srv=g.getServers().get(server.getName());
// if(srv==null)
// srv=new Server(server.getName(),new ArrayList<String>(),new HashMap<String,World>(),"","","");
// List<String> serverperms=srv.getPerms();
// for(String perm:serverperms)
// boolean added=false;
// for(int i=0;i<ret.size();i++)
// if(ret.get(i).equalsIgnoreCase(perm))
// added=true;
// break;
// else if(ret.get(i).equalsIgnoreCase("-"+perm))
// ret.set(i,perm);
// added=true;
// break;
// else if(perm.equalsIgnoreCase("-"+ret.get(i)))
// ret.remove(i);
// added=true;
// break;
// if(!added)
// ret.add(perm);
}
for(String s:perms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(s))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+s))
{
ret.set(i,s);
added=true;
break;
}
else if(s.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(s);
}
}
//per server perms
Server srv=servers.get(server.getName().toLowerCase());
if(srv==null)
{
srv=new Server(server.getName().toLowerCase(),new ArrayList<String>(),new HashMap<String,World>(),"","","");
}
List<String> perserverperms=srv.getPerms();
for(String perm:perserverperms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(perm))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+perm))
{
ret.set(i,perm);
added=true;
break;
}
else if(perm.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(perm);
}
}
return ret;
}
public List<String> calcEffectivePerms(ServerInfo server,String world)
{
List<String> ret=new ArrayList<>();
for(Group g:BungeePerms.getInstance().getPermissionsManager().getGroups())
{
if(inheritances.contains(g.getName()))
{
for(String perm:g.getEffectivePerms(server,world))
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(perm))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+perm))
{
ret.set(i,perm);
added=true;
break;
}
else if(perm.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(perm);
}
}
//per server perms
// Server srv=g.getServers().get(server.getName());
// if(srv==null)
// srv=new Server(server.getName(),new ArrayList<String>(),new HashMap<String,World>(),"","","");
// List<String> serverperms=srv.getPerms();
// for(String perm:serverperms)
// boolean added=false;
// for(int i=0;i<ret.size();i++)
// if(ret.get(i).equalsIgnoreCase(perm))
// added=true;
// break;
// else if(ret.get(i).equalsIgnoreCase("-"+perm))
// ret.set(i,perm);
// added=true;
// break;
// else if(perm.equalsIgnoreCase("-"+ret.get(i)))
// ret.remove(i);
// added=true;
// break;
// if(!added)
// ret.add(perm);
// //per server world perms
// World w=srv.getWorlds().get(world);
// if(w==null)
// w=new World(server.getName(),new ArrayList<String>(),"","","");
// List<String> serverworldperms=w.getPerms();
// for(String perm:serverworldperms)
// boolean added=false;
// for(int i=0;i<ret.size();i++)
// if(ret.get(i).equalsIgnoreCase(perm))
// added=true;
// break;
// else if(ret.get(i).equalsIgnoreCase("-"+perm))
// ret.set(i,perm);
// added=true;
// break;
// else if(perm.equalsIgnoreCase("-"+ret.get(i)))
// ret.remove(i);
// added=true;
// break;
// if(!added)
// ret.add(perm);
}
}
for(String s:perms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(s))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+s))
{
ret.set(i,s);
added=true;
break;
}
else if(s.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(s);
}
}
//per server perms
Server srv=servers.get(server.getName().toLowerCase());
if(srv==null)
{
srv=new Server(server.getName().toLowerCase(),new ArrayList<String>(),new HashMap<String,World>(),"","","");
}
List<String> perserverperms=srv.getPerms();
for(String perm:perserverperms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(perm))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+perm))
{
ret.set(i,perm);
added=true;
break;
}
else if(perm.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(perm);
}
}
//per server world perms
World w=srv.getWorlds().get(world.toLowerCase());
if(w==null)
{
w=new World(world.toLowerCase(),new ArrayList<String>(),"","","");
}
List<String> serverworldperms=w.getPerms();
for(String perm:serverworldperms)
{
boolean added=false;
for(int i=0;i<ret.size();i++)
{
if(ret.get(i).equalsIgnoreCase(perm))
{
added=true;
break;
}
else if(ret.get(i).equalsIgnoreCase("-"+perm))
{
ret.set(i,perm);
added=true;
break;
}
else if(perm.equalsIgnoreCase("-"+ret.get(i)))
{
ret.remove(i);
added=true;
break;
}
}
if(!added)
{
ret.add(perm);
}
}
return ret;
}
public boolean has(String perm)
{
List<String> perms=getEffectivePerms();
boolean has=false;
for(String p:perms)
{
if(p.equalsIgnoreCase(perm))
{
has=true;
}
else if(p.equalsIgnoreCase("-"+perm))
{
has=false;
}
else if(p.endsWith("*"))
{
List<String> lp=Statics.toList(p, ".");
List<String> lperm=Statics.toList(perm, ".");
int index=0;
try
{
while(true)
{
if(index==0)
{
if( lperm.get(0).equalsIgnoreCase(lp.get(0))|
lp.get(0).equalsIgnoreCase("-"+lperm.get(0)))
{
index++;
}
else
{
break;
}
}
else
{
if(lperm.get(index).equalsIgnoreCase(lp.get(index)))
{
index++;
}
else
{
break;
}
}
}
if(lp.get(index).equalsIgnoreCase("*"))
{
has=!lp.get(0).startsWith("-");
}
}
catch(Exception e){}
}
}
return has;
}
public boolean hasOnServer(String perm,ServerInfo server)
{
List<String> perms=getEffectivePerms(server);
boolean has=false;
for(String p:perms)
{
if(p.equalsIgnoreCase(perm))
{
has=true;
}
else if(p.equalsIgnoreCase("-"+perm))
{
has=false;
}
else if(p.endsWith("*"))
{
List<String> lp=Statics.toList(p, ".");
List<String> lperm=Statics.toList(perm, ".");
int index=0;
try
{
while(true)
{
if(index==0)
{
if( lperm.get(0).equalsIgnoreCase(lp.get(0))|
lp.get(0).equalsIgnoreCase("-"+lperm.get(0)))
{
index++;
}
else
{
break;
}
}
else
{
if(lperm.get(index).equalsIgnoreCase(lp.get(index)))
{
index++;
}
else
{
break;
}
}
}
if(lp.get(index).equalsIgnoreCase("*"))
{
has=!lp.get(0).startsWith("-");
}
}
catch(Exception e){}
}
}
return has;
}
public boolean hasOnServerInWorld(String perm,ServerInfo server,String world)
{
List<String> perms=getEffectivePerms(server,world);
boolean has=false;
for(String p:perms)
{
if(p.equalsIgnoreCase(perm))
{
has=true;
}
else if(p.equalsIgnoreCase("-"+perm))
{
has=false;
}
else if(p.endsWith("*"))
{
List<String> lp=Statics.toList(p, ".");
List<String> lperm=Statics.toList(perm, ".");
int index=0;
try
{
while(true)
{
if(index==0)
{
if( lperm.get(0).equalsIgnoreCase(lp.get(0))|
lp.get(0).equalsIgnoreCase("-"+lperm.get(0)))
{
index++;
}
else
{
break;
}
}
else
{
if(lperm.get(index).equalsIgnoreCase(lp.get(index)))
{
index++;
}
else
{
break;
}
}
}
if(lp.get(index).equalsIgnoreCase("*"))
{
has=!lp.get(0).startsWith("-");
}
}
catch(Exception e){}
}
}
return has;
}
public void recalcPerms()
{
for(Map.Entry<String, List<String>> e:cachedPerms.entrySet())
{
String where=e.getKey();
List<String> l=Statics.toList(where, ";");
String server=l.get(0);
if(l.size()==1)
{
if(server.equalsIgnoreCase("global"))
{
cachedPerms.put("global", calcEffectivePerms());
}
else
{
ServerInfo si=BungeeCord.getInstance().config.getServers().get(server);
List<String> effperms=calcEffectivePerms(si);
cachedPerms.put(si.getName().toLowerCase(), effperms);
}
}
else if(l.size()==2)
{
String world=l.get(1);
recalcPerms(server,world);
}
}
}
public void recalcPerms(String server)
{
for(Map.Entry<String, List<String>> e:cachedPerms.entrySet())
{
String where=e.getKey();
List<String> l=Statics.toList(where, ";");
String lserver=l.get(0);
if(lserver.equalsIgnoreCase(server))
{
if(l.size()==1)
{
ServerInfo si=BungeeCord.getInstance().config.getServers().get(lserver);
List<String> effperms=calcEffectivePerms(si);
cachedPerms.put(si.getName().toLowerCase(), effperms);
}
else if(l.size()==2)
{
String world=l.get(1);
recalcPerms(server,world);
}
}
}
}
public void recalcPerms(String server,String world)
{
ServerInfo si=BungeeCord.getInstance().config.getServers().get(server);
List<String> effperms=calcEffectivePerms(si,world);
cachedPerms.put(si.getName().toLowerCase()+";"+world.toLowerCase(), effperms);
}
public List<BPPermission> getPermsWithOrigin(String server, String world)
{
List<BPPermission> ret=new ArrayList<>();
//add inherited groups' perms
for(Group g:BungeePerms.getInstance().getPermissionsManager().getGroups())
{
if(inheritances.contains(g.getName()))
{
List<BPPermission> inheritgroupperms=g.getPermsWithOrigin(server, world);
for(BPPermission perm:inheritgroupperms)
{
// if(perm.getOrigin().equalsIgnoreCase(g.getName()))
ret.add(perm);
}
}
}
for(String s:perms)
{
BPPermission perm=new BPPermission(s,name,true,null,null);
ret.add(perm);
}
//per server perms
for(Map.Entry<String, Server> srv:servers.entrySet())
{
//check for server
if(server!=null && !srv.getKey().equalsIgnoreCase(server))
{
continue;
}
List<String> perserverperms=srv.getValue().getPerms();
for(String s:perserverperms)
{
BPPermission perm=new BPPermission(s,name,true,srv.getKey(),null);
ret.add(perm);
}
//per server world perms
for(Map.Entry<String, World> w:srv.getValue().getWorlds().entrySet())
{
//check for world
if(world!=null && !w.getKey().equalsIgnoreCase(world))
{
continue;
}
List<String> perserverworldperms=w.getValue().getPerms();
for(String s:perserverworldperms)
{
BPPermission perm=new BPPermission(s,name,true,srv.getKey(),w.getKey());
ret.add(perm);
}
}
}
return ret;
}
@Override
public int compareTo(Group g)
{
return -Integer.compare(rank, g.getRank());
}
@Override
public String toString()
{
String string="name="+name+" "
+ "inheritances="+inheritances+" "
+ "perms="+perms+" "
+ "servers="+servers+" "
+ "rank="+rank+" "
+ "ladder="+ladder+" "
+ "isdefault="+isdefault+" "
+ "display="+display+" "
+ "prefix="+prefix+" "
+ "suffix="+suffix;
return string;
}
} |
package no.javazone.speaker;
import org.joda.time.DateTime;
import java.util.Date;
public class SpeakerBilde {
private static final int CACHELEVETID_MINUTTER = 60;
public static final int SMALL = 48;
public static final int LARGE = 240;
private final byte[] smallPhoto;
private final byte[] largePhoto;
private final DateTime hentet;
private final Date lastModified;
public SpeakerBilde(final byte[] uskalertBilde, Date lastModified) {
this.lastModified = lastModified;
byte[] firkantBilde = BildeSkalerer.cropTilFirkant(uskalertBilde);
smallPhoto = BildeSkalerer.skalerPngBilde(firkantBilde, SMALL, SMALL);
largePhoto = BildeSkalerer.skalerPngBilde(firkantBilde, LARGE, LARGE);
hentet = DateTime.now();
}
public byte[] getLiteBilde() {
return smallPhoto;
}
public byte[] getStortBilde() {
return largePhoto;
}
public boolean erGammelt() {
return hentet.isBefore(DateTime.now().minusMinutes(CACHELEVETID_MINUTTER));
}
} |
package org.blitzortung.android.app;
import android.app.ActionBar;
import android.app.Dialog;
import android.content.*;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.*;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.*;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import org.blitzortung.android.alarm.AlarmLabelHandler;
import org.blitzortung.android.alarm.AlarmManager;
import org.blitzortung.android.alarm.AlarmResult;
import org.blitzortung.android.app.controller.ButtonColumnHandler;
import org.blitzortung.android.app.controller.HistoryController;
import org.blitzortung.android.app.controller.LocationHandler;
import org.blitzortung.android.app.view.AlarmView;
import org.blitzortung.android.app.view.HistogramView;
import org.blitzortung.android.app.view.LegendView;
import org.blitzortung.android.app.view.PreferenceKey;
import org.blitzortung.android.app.view.components.StatusComponent;
import org.blitzortung.android.data.DataHandler;
import org.blitzortung.android.data.DataListener;
import org.blitzortung.android.data.Parameters;
import org.blitzortung.android.data.beans.RasterParameters;
import org.blitzortung.android.data.provider.DataResult;
import org.blitzortung.android.dialogs.*;
import org.blitzortung.android.map.OwnMapActivity;
import org.blitzortung.android.map.OwnMapView;
import org.blitzortung.android.map.overlay.FadeOverlay;
import org.blitzortung.android.map.overlay.OwnLocationOverlay;
import org.blitzortung.android.map.overlay.ParticipantsOverlay;
import org.blitzortung.android.map.overlay.StrokesOverlay;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Main extends OwnMapActivity implements DataListener, OnSharedPreferenceChangeListener, DataService.DataServiceStatusListener,
AlarmManager.AlarmListener {
public static final String LOG_TAG = "BO_ANDROID";
protected StatusComponent statusComponent;
private FadeOverlay fadeOverlay;
protected StrokesOverlay strokesOverlay;
private ParticipantsOverlay participantsOverlay;
private AlarmManager alarmManager;
private LocationHandler locationHandler;
private DataHandler dataHandler;
private OwnLocationOverlay ownLocationOverlay;
private Persistor persistor;
private boolean clearData;
private final Set<DataListener> dataListeners = new HashSet<DataListener>();
private final Set<String> androidIdsForExtendedFunctionality = new HashSet<String>(Arrays.asList("e72d101ce1bcdee3", "6d1b9a3da993af2d"));
private PackageInfo pInfo;
private ButtonColumnHandler<ImageButton> buttonColumnHandler;
private HistoryController historyController;
private DataService dataService;
private ServiceConnection serviceConnection;
private LegendView legendView;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
} catch (NoClassDefFoundError e) {
Log.e(Main.LOG_TAG, e.toString());
Toast toast = Toast.makeText(getBaseContext(), "bad android version", 1000);
toast.show();
}
updatePackageInfo();
setContentView(isDebugBuild() ? R.layout.main_debug : R.layout.main);
OwnMapView mapView = (OwnMapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
setMapView(mapView);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.registerOnSharedPreferenceChangeListener(this);
if (getLastNonConfigurationInstance() == null) {
Log.i(Main.LOG_TAG, "Main.onCreate(): create new persistor");
persistor = new Persistor(this, preferences, pInfo);
} else {
Log.i(Main.LOG_TAG, "Main.onCreate(): reuse persistor");
persistor = (Persistor) getLastNonConfigurationInstance();
}
persistor.updateContext(this);
locationHandler = persistor.getLocationHandler();
strokesOverlay = persistor.getStrokesOverlay();
participantsOverlay = persistor.getParticipantsOverlay();
mapView.addZoomListener(new OwnMapView.ZoomListener() {
@Override
public void onZoom(int zoomLevel) {
strokesOverlay.updateZoomLevel(zoomLevel);
participantsOverlay.updateZoomLevel(zoomLevel);
}
});
fadeOverlay = new FadeOverlay(strokesOverlay.getColorHandler());
ownLocationOverlay = new OwnLocationOverlay(getBaseContext(), persistor.getLocationHandler(), getMapView());
addOverlays(fadeOverlay, strokesOverlay, participantsOverlay, ownLocationOverlay);
dataHandler = persistor.getDataHandler();
strokesOverlay.setIntervalDuration(dataHandler.getIntervalDuration());
statusComponent = new StatusComponent(this);
setHistoricStatusString();
alarmManager = persistor.getAlarmManager();
if (alarmManager.isAlarmEnabled()) {
onAlarmResult(alarmManager.getAlarmResult());
}
buttonColumnHandler = new ButtonColumnHandler<ImageButton>();
if (Build.VERSION.SDK_INT >= 14) {
ViewConfiguration config = ViewConfiguration.get(this);
if (!config.hasPermanentMenuKey()) {
ImageButton menuButton = (ImageButton) findViewById(R.id.menu);
menuButton.setVisibility(View.VISIBLE);
menuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openOptionsMenu();
}
});
buttonColumnHandler.addElement(menuButton);
}
//noinspection EmptyCatchBlock
try {
Method getActionBar = Main.class.getMethod("getActionBar");
Object actionBar;
actionBar = getActionBar.invoke(this);
if (actionBar != null) {
Method hide = actionBar.getClass().getMethod("hide");
hide.invoke(actionBar);
}
} catch (NoSuchMethodException e) {
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
}
historyController = new HistoryController(this, dataHandler);
historyController.setButtonHandler(buttonColumnHandler);
if (persistor.hasCurrentResult()) {
historyController.setRealtimeData(persistor.getCurrentResult().containsRealtimeData());
}
buttonColumnHandler.addAllElements(historyController.getButtons());
setupDebugModeButton();
buttonColumnHandler.updateButtonColumn();
setupCustomViews();
onSharedPreferenceChanged(preferences, PreferenceKey.MAP_TYPE, PreferenceKey.MAP_FADE, PreferenceKey.SHOW_LOCATION,
PreferenceKey.NOTIFICATION_DISTANCE_LIMIT, PreferenceKey.SIGNALING_DISTANCE_LIMIT, PreferenceKey.DO_NOT_SLEEP, PreferenceKey.SHOW_PARTICIPANTS);
createAndBindToDataService();
getMapView().invalidate();
}
private void createAndBindToDataService() {
final Intent serviceIntent = new Intent(this, DataService.class);
startService(serviceIntent);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
dataService = ((DataService.DataServiceBinder) iBinder).getService();
Log.i(Main.LOG_TAG, "Main.ServiceConnection.onServiceConnected() " + dataService);
dataService.setListener(Main.this);
dataService.setDataHandler(dataHandler);
if (!persistor.hasCurrentResult()) {
dataService.restart();
}
dataService.onResume();
historyController.setDataService(dataService);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
bindService(serviceIntent, serviceConnection, 0);
}
private void setupDebugModeButton() {
final String androidId = Settings.Secure.getString(getBaseContext().getContentResolver(), Settings.Secure.ANDROID_ID);
if (isDebugBuild() || (androidId != null && androidIdsForExtendedFunctionality.contains(androidId))) {
ImageButton rasterToggle = (ImageButton) findViewById(R.id.toggleExtendedMode);
rasterToggle.setEnabled(true);
rasterToggle.setVisibility(View.VISIBLE);
rasterToggle.getDrawable().setAlpha(40);
rasterToggle.getBackground().setAlpha(40);
rasterToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonColumnHandler.disableButtonColumn();
dataHandler.toggleExtendedMode();
onDataReset();
}
});
buttonColumnHandler.addElement(rasterToggle);
}
}
private void setupCustomViews() {
legendView = (LegendView) findViewById(R.id.legend_view);
legendView.setStrokesOverlay(strokesOverlay);
legendView.setAlpha(150);
legendView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(R.layout.settings_dialog);
Log.v(LOG_TAG, "LegendView.onClick()");
}
});
AlarmView alarmView = (AlarmView) findViewById(R.id.alarm_view);
alarmView.setAlarmManager(alarmManager);
alarmView.setColorHandler(strokesOverlay.getColorHandler(), strokesOverlay.getIntervalDuration());
alarmView.setBackgroundColor(Color.TRANSPARENT);
alarmView.setAlpha(200);
alarmView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (alarmManager.isAlarmEnabled()) {
final Location currentLocation = alarmManager.getCurrentLocation();
if (currentLocation != null) {
float radius = alarmManager.getMaxDistance();
final AlarmResult alarmResult = alarmManager.getAlarmResult();
if (alarmResult != null) {
radius = Math.max(Math.min(alarmResult.getClosestStrokeDistance() * 1.2f, radius), 50f);
}
float diameter = 1.5f * 2f * radius;
animateToLocationAndVisibleSize(currentLocation.getLongitude(), currentLocation.getLatitude(), diameter);
}
}
}
});
HistogramView histogramView = (HistogramView) findViewById(R.id.histogram_view);
histogramView.setStrokesOverlay(strokesOverlay);
if (persistor.hasCurrentResult()) {
histogramView.onDataUpdate(persistor.getCurrentResult());
}
addDataListener(histogramView);
histogramView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (persistor.hasCurrentResult()) {
final DataResult currentResult = persistor.getCurrentResult();
if (currentResult.hasRasterParameters()) {
final RasterParameters rasterParameters = currentResult.getRasterParameters();
animateToLocationAndVisibleSize(rasterParameters.getRectCenterLongitude(), rasterParameters.getRectCenterLatitude(), 5000f);
} else {
animateToLocationAndVisibleSize(0, 0, 20000f);
}
}
}
});
}
private void animateToLocationAndVisibleSize(double longitude, double latitude, float diameter) {
Log.d(Main.LOG_TAG, String.format("Main.animateAndZoomTo() %.4f, %.4f, %.0fkm", longitude, latitude, diameter));
final OwnMapView mapView = getMapView();
final MapController controller = mapView.getController();
final int startZoomLevel = mapView.getZoomLevel();
final int targetZoomLevel = mapView.calculateTargetZoomLevel(diameter * 1000f);
controller.animateTo(new GeoPoint((int) (latitude * 1e6), (int) (longitude * 1e6)), new Runnable() {
@Override
public void run() {
if (startZoomLevel != targetZoomLevel) {
final boolean zoomOut = targetZoomLevel - startZoomLevel < 0;
final int zoomCount = Math.abs(targetZoomLevel - startZoomLevel);
Handler handler = new Handler();
long delay = 0;
for (int i = 0; i < zoomCount; i++) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (zoomOut) {
controller.zoomOut();
} else {
controller.zoomIn();
}
}
}, delay);
delay += 150;
}
}
}
});
}
private void addDataListener(DataListener listener) {
dataListeners.add(listener);
}
@Override
public Object onRetainNonConfigurationInstance() {
strokesOverlay.clearPopup();
participantsOverlay.clearPopup();
return persistor;
}
public boolean isDebugBuild() {
boolean dbg = false;
try {
PackageManager pm = getPackageManager();
PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
dbg = ((pi.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
} catch (Exception ignored) {
}
return dbg;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_info:
showDialog(R.id.info_dialog);
break;
case R.id.menu_alarms:
showDialog(R.id.alarm_dialog);
break;
/*case R.id.menu_layers:
showDialog(R.id.layer_dialog);
break;*/
case R.id.menu_preferences:
startActivity(new Intent(this, Preferences.class));
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
Log.d(Main.LOG_TAG, "Main.onResume()");
if (dataService != null) {
dataService.onResume();
}
locationHandler.onResume();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.getBoolean(PreferenceKey.SHOW_LOCATION.toString(), false)) {
ownLocationOverlay.enableOwnLocation();
}
}
@Override
public void onPause() {
super.onPause();
if (dataService == null || dataService.onPause()) {
Log.d(Main.LOG_TAG, "Main.onPause() disable location handler");
locationHandler.onPause();
} else {
Log.d(Main.LOG_TAG, "Main.onPause()");
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.getBoolean(PreferenceKey.SHOW_LOCATION.toString(), false)) {
ownLocationOverlay.disableOwnLocation();
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "Main: onDestroy()");
unbindService(serviceConnection);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
public void onBeforeDataUpdate() {
buttonColumnHandler.disableButtonColumn();
statusComponent.startProgress();
}
@Override
public void onDataUpdate(DataResult result) {
Log.d(Main.LOG_TAG, "Main.onDataUpdate() " + result);
if (result.isBackground()) {
alarmManager.checkStrokes(result.getStrokes(), result.containsRealtimeData());
} else {
statusComponent.indicateError(false);
historyController.setRealtimeData(result.containsRealtimeData());
Parameters resultParameters = result.getParameters();
persistor.setCurrentResult(result);
clearDataIfRequested();
if (result.containsStrokes()) {
strokesOverlay.setRasterParameters(result.getRasterParameters());
strokesOverlay.setRegion(resultParameters.getRegion());
strokesOverlay.setReferenceTime(result.getReferenceTime());
strokesOverlay.setIntervalDuration(resultParameters.getIntervalDuration());
strokesOverlay.setIntervalOffset(resultParameters.getIntervalOffset());
if (result.containsIncrementalData()) {
strokesOverlay.expireStrokes();
} else {
strokesOverlay.clear();
}
strokesOverlay.addStrokes(result.getStrokes());
alarmManager.checkStrokes(strokesOverlay.getStrokes(), result.containsRealtimeData());
strokesOverlay.refresh();
}
if (!result.containsRealtimeData()) {
dataService.disable();
setHistoricStatusString();
}
if (participantsOverlay != null && result.containsParticipants()) {
participantsOverlay.setParticipants(result.getStations());
participantsOverlay.refresh();
}
for (DataListener listener : dataListeners) {
listener.onDataUpdate(result);
}
statusComponent.stopProgress();
buttonColumnHandler.enableButtonColumn();
getMapView().invalidate();
legendView.invalidate();
}
if (dataService != null) {
dataService.releaseWakeLock();
}
}
private void clearDataIfRequested() {
if (clearData) {
clearData = false;
strokesOverlay.clear();
if (participantsOverlay != null) {
participantsOverlay.clear();
}
}
}
@Override
public void onDataReset() {
dataService.reloadData();
clearData = true;
for (DataListener listener : dataListeners) {
listener.onDataReset();
}
}
@Override
public void onDataError() {
statusComponent.indicateError(true);
statusComponent.stopProgress();
buttonColumnHandler.enableButtonColumn();
}
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch (id) {
case R.id.info_dialog:
dialog = new InfoDialog(this, pInfo);
break;
case R.id.alarm_dialog:
dialog = new AlarmDialog(this, alarmManager, new AlarmDialogColorHandler(PreferenceManager.getDefaultSharedPreferences(this)), strokesOverlay.getIntervalDuration());
break;
case R.id.layer_dialog:
dialog = new LayerDialog(this, getMapView());
break;
case R.id.settings_dialog:
dialog = new SettingsDialog(this);
break;
default:
dialog = null;
}
return dialog;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String keyString) {
onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(keyString));
}
private void onSharedPreferenceChanged(SharedPreferences sharedPreferences, PreferenceKey... keys) {
for (PreferenceKey key : keys) {
onSharedPreferenceChanged(sharedPreferences, key);
}
}
private void onSharedPreferenceChanged(SharedPreferences sharedPreferences, PreferenceKey key) {
switch (key) {
case MAP_TYPE:
String mapTypeString = sharedPreferences.getString(key.toString(), "SATELLITE");
getMapView().setSatellite(mapTypeString.equals("SATELLITE"));
strokesOverlay.refresh();
if (participantsOverlay != null) {
participantsOverlay.refresh();
}
break;
case SHOW_PARTICIPANTS:
boolean showParticipants = sharedPreferences.getBoolean(key.toString(), true);
participantsOverlay.setEnabled(showParticipants);
updateOverlays();
break;
case COLOR_SCHEME:
strokesOverlay.refresh();
if (participantsOverlay != null) {
participantsOverlay.refresh();
}
break;
case MAP_FADE:
int alphaValue = Math.round(255.0f / 100.0f * sharedPreferences.getInt(key.toString(), 40));
fadeOverlay.setAlpha(alphaValue);
break;
case DO_NOT_SLEEP:
boolean doNotSleep = sharedPreferences.getBoolean(key.toString(), false);
int flag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
if (doNotSleep) {
getWindow().addFlags(flag);
} else {
getWindow().clearFlags(flag);
}
break;
}
}
public void onDataServiceStatusUpdate(String dataServiceStatus) {
setStatusString(dataServiceStatus);
}
protected void setHistoricStatusString() {
if (!strokesOverlay.hasRealtimeData()) {
long referenceTime = strokesOverlay.getReferenceTime() + strokesOverlay.getIntervalOffset() * 60 * 1000;
String timeString = (String) DateFormat.format("@ kk:mm", referenceTime);
setStatusString(timeString);
}
}
protected void setStatusString(String runStatus) {
int numberOfStrokes = strokesOverlay.getTotalNumberOfStrokes();
String statusText = getResources().getQuantityString(R.plurals.stroke, numberOfStrokes, numberOfStrokes);
statusText += "/";
int intervalDuration = strokesOverlay.getIntervalDuration();
statusText += getResources().getQuantityString(R.plurals.minute, intervalDuration, intervalDuration);
statusText += " " + runStatus;
statusComponent.setText(statusText);
}
@Override
public void onAlarmResult(AlarmResult alarmResult) {
AlarmLabelHandler alarmLabelHandler = new AlarmLabelHandler(statusComponent, getResources());
alarmLabelHandler.apply(alarmResult);
}
@Override
public void onAlarmClear() {
statusComponent.setAlarmText("");
}
private void updatePackageInfo() {
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
throw new IllegalStateException(e);
}
}
} |
package org.decimal4j.util;
import java.math.RoundingMode;
import java.util.Objects;
import org.decimal4j.api.DecimalArithmetic;
import org.decimal4j.scale.ScaleMetrics;
import org.decimal4j.scale.Scales;
/**
* Utility class to round double values to an arbitrary decimal precision between 0 and 18. The rounding is efficient
* and garbage free.
*/
public final class DoubleRounder {
private final ScaleMetrics scaleMetrics;
private final double ulp;
public DoubleRounder(int precision) {
this(toScaleMetrics(precision));
}
/**
* Creates a rounder with the given scale metrics defining the decimal precision.
*
* @param scaleMetrics
* the scale metrics determining the rounding precision
* @throws NullPointerException
* if scale metrics is null
*/
public DoubleRounder(ScaleMetrics scaleMetrics) {
this.scaleMetrics = Objects.requireNonNull(scaleMetrics, "scaleMetrics cannot be null");
this.ulp = scaleMetrics.getRoundingHalfEvenArithmetic().toDouble(1);
}
/**
* Returns the precision of this rounder, a value between zero and 18.
*
* @return this rounder's decimal precision
*/
public int getPrecision() {
return scaleMetrics.getScale();
}
/**
* Rounds the given double value to the decimal precision of this rounder using {@link RoundingMode#HALF_UP HALF_UP}
* rounding.
*
* @param value
* the value to round
* @return the rounded value
* @see #getPrecision()
*/
public double round(double value) {
return round(value, scaleMetrics.getDefaultArithmetic(), scaleMetrics.getRoundingHalfEvenArithmetic(), ulp);
}
/**
* Rounds the given double value to the decimal precision of this rounder using the specified rounding mode.
*
* @param value
* the value to round
* @param roundingMode
* the rounding mode indicating how the least significant returned decimal digit of the result is to be
* calculated
* @return the rounded value
* @see #getPrecision()
*/
public double round(double value, RoundingMode roundingMode) {
return round(value, roundingMode, scaleMetrics.getRoundingHalfEvenArithmetic(), ulp);
}
/**
* Returns a hash code for this <tt>DoubleRounder</tt> instance.
*
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
return scaleMetrics.hashCode();
}
/**
* Returns true if {@code obj} is a <tt>DoubleRounder</tt> with the same precision as {@code this} rounder instance.
*
* @param obj
* the reference object with which to compare
* @return true for a double rounder with the same precision as this instance
*/
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null)
return false;
if (obj instanceof DoubleRounder) {
return scaleMetrics.equals(((DoubleRounder) obj).scaleMetrics);
}
return false;
}
/**
* Returns a string consisting of the simple class name and the precision.
*
* @return a string like "DoubleRounder[precision=7]"
*/
@Override
public String toString() {
return "DoubleRounder[precision=" + getPrecision() + "]";
}
/**
* Rounds the given double value to the specified decimal {@code precision} using {@link RoundingMode#HALF_UP
* HALF_UP} rounding.
*
* @param value
* the value to round
* @param precision
* the decimal precision to round to (aka decimal places)
* @return the rounded value
*/
public static final double round(double value, int precision) {
final ScaleMetrics sm = toScaleMetrics(precision);
final DecimalArithmetic halfEvenArith = sm.getRoundingHalfEvenArithmetic();
return round(value, sm.getDefaultArithmetic(), halfEvenArith, halfEvenArith.toDouble(1));
}
/**
* Rounds the given double value to the specified decimal {@code precision} using the specified rounding mode.
*
* @param value
* the value to round
* @param precision
* the decimal precision to round to (aka decimal places)
* @param roundingMode
* the rounding mode indicating how the least significant returned decimal digit of the result is to be
* calculated
* @return the rounded value
*/
public static final double round(double value, int precision, RoundingMode roundingMode) {
final ScaleMetrics sm = toScaleMetrics(precision);
final DecimalArithmetic halfEvenArith = sm.getRoundingHalfEvenArithmetic();
return round(value, roundingMode, halfEvenArith, halfEvenArith.toDouble(1));
}
private static final double round(double value, RoundingMode roundingMode, DecimalArithmetic halfEvenArith, double ulp) {
if (roundingMode == RoundingMode.UNNECESSARY) {
return checkRoundingUnnecessary(value, halfEvenArith, ulp);
}
return round(value, halfEvenArith.deriveArithmetic(roundingMode), halfEvenArith, ulp);
}
private static final double round(double value, DecimalArithmetic roundingArith, DecimalArithmetic halfEvenArith, double ulp) {
if (!isFinite(value) || 2 * ulp <= Math.ulp(value)) {
return value;
}
final long uDecimal = roundingArith.fromDouble(value);
return halfEvenArith.toDouble(uDecimal);
}
private static final double checkRoundingUnnecessary(double value, DecimalArithmetic halfEvenArith, double ulp) {
if (isFinite(value) && 2 * ulp > Math.ulp(value)) {
final long uDecimal = halfEvenArith.fromDouble(value);
if (halfEvenArith.toDouble(uDecimal) != value) {
throw new ArithmeticException(
"Rounding necessary for precision " + halfEvenArith.getScale() + ": " + value);
}
}
return value;
}
private static final ScaleMetrics toScaleMetrics(int precision) {
if (precision < Scales.MIN_SCALE | precision > Scales.MAX_SCALE) {
throw new IllegalArgumentException(
"Precision must be in [" + Scales.MIN_SCALE + "," + Scales.MAX_SCALE + "] but was " + precision);
}
return Scales.getScaleMetrics(precision);
}
/**
* Java-7 port of {@code Double#isFinite(double)}.
* <p>
* Returns {@code true} if the argument is a finite floating-point value; returns {@code false} otherwise (for NaN
* and infinity arguments).
*
* @param d
* the {@code double} value to be tested
* @return {@code true} if the argument is a finite floating-point value, {@code false} otherwise.
*/
private static boolean isFinite(double d) {
return Math.abs(d) <= Double.MAX_VALUE;
}
} |
package org.dita.dost.writer;
import static java.util.Arrays.asList;
import static javax.xml.XMLConstants.NULL_NS_URI;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.util.XMLUtils.toList;
import java.io.File;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.DITAOTLogger;
import org.dita.dost.log.MessageBean;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.util.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* Filter for processing key reference elements in DITA files.
* Instances are reusable but not thread-safe.
*/
public final class KeyrefPaser extends AbstractXMLFilter {
/**
* Set of attributes which should not be copied from
* key definition to key reference which is {@code <topicref>}.
*/
private static final Set<String> no_copy;
static {
final Set<String> nc = new HashSet<>();
nc.add(ATTRIBUTE_NAME_ID);
nc.add(ATTRIBUTE_NAME_CLASS);
nc.add(ATTRIBUTE_NAME_XTRC);
nc.add(ATTRIBUTE_NAME_XTRF);
nc.add(ATTRIBUTE_NAME_HREF);
nc.add(ATTRIBUTE_NAME_KEYS);
nc.add(ATTRIBUTE_NAME_TOC);
nc.add(ATTRIBUTE_NAME_PROCESSING_ROLE);
no_copy = Collections.unmodifiableSet(nc);
}
/**
* Set of attributes which should not be copied from
* key definition to key reference which is not {@code <topicref>}.
*/
private static final Set<String> no_copy_topic;
static {
final Set<String> nct = new HashSet<>();
nct.addAll(no_copy);
nct.add("query");
nct.add("search");
nct.add(ATTRIBUTE_NAME_TOC);
nct.add(ATTRIBUTE_NAME_PRINT);
nct.add(ATTRIBUTE_NAME_COPY_TO);
nct.add(ATTRIBUTE_NAME_CHUNK);
nct.add(ATTRIBUTE_NAME_NAVTITLE);
no_copy_topic = Collections.unmodifiableSet(nct);
}
/** List of key reference element definitions. */
private final static List<KeyrefInfo> keyrefInfos;
static {
final List<KeyrefInfo> ki = new ArrayList<>();
ki.add(new KeyrefInfo(TOPIC_AUTHOR, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(TOPIC_DATA, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(TOPIC_DATA_ABOUT, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(TOPIC_IMAGE, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(TOPIC_LINK, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(TOPIC_LQ, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(MAP_NAVREF, "mapref", true, false));
ki.add(new KeyrefInfo(TOPIC_PUBLISHER, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(TOPIC_SOURCE, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(MAP_TOPICREF, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_XREF, ATTRIBUTE_NAME_HREF, false, true));
ki.add(new KeyrefInfo(TOPIC_CITE, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_DT, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_KEYWORD, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_TERM, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_PH, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_INDEXTERM, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_INDEX_BASE, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_INDEXTERMREF, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_LONGQUOTEREF, ATTRIBUTE_NAME_HREF, false, false));
final Map<String, String> objectAttrs = new HashMap<>();
objectAttrs.put(ATTRIBUTE_NAME_ARCHIVEKEYREFS, ATTRIBUTE_NAME_ARCHIVE);
objectAttrs.put(ATTRIBUTE_NAME_CLASSIDKEYREF, ATTRIBUTE_NAME_CLASSID);
objectAttrs.put(ATTRIBUTE_NAME_CODEBASEKEYREF, ATTRIBUTE_NAME_CODEBASE);
objectAttrs.put(ATTRIBUTE_NAME_DATAKEYREF, ATTRIBUTE_NAME_DATA);
ki.add(new KeyrefInfo(TOPIC_OBJECT, objectAttrs, true, false));
final Map<String, String> paramAttrs = new HashMap<>();
paramAttrs.put(ATTRIBUTE_NAME_KEYREF, ATTRIBUTE_NAME_VALUE);
ki.add(new KeyrefInfo(TOPIC_PARAM, paramAttrs, true, false));
keyrefInfos = Collections.unmodifiableList(ki);
}
private final static List<String> KEYREF_ATTRIBUTES = Collections.unmodifiableList(asList(
ATTRIBUTE_NAME_KEYREF,
ATTRIBUTE_NAME_ARCHIVEKEYREFS,
ATTRIBUTE_NAME_CLASSIDKEYREF,
ATTRIBUTE_NAME_CODEBASEKEYREF,
ATTRIBUTE_NAME_DATAKEYREF
));
private KeyScope definitionMap;
/**
* Stack used to store the place of current element
* relative to the key reference element.
*/
private final Deque<Integer> keyrefLevalStack;
/**
* Used to store the place of current element
* relative to the key reference element. If it is out of range of key
* reference element it is zero, otherwise it is positive number.
* It is also used to indicate whether current element is descendant of the
* key reference element.
*/
private int keyrefLevel;
/**
* Indicates whether the keyref is valid.
* The descendant element should know whether keyref is valid because keyrefs can be nested.
*/
private final Deque<Boolean> validKeyref;
/**
* Flag indicating whether the key reference element is empty,
* if it is empty, it should pull matching content from the key definition.
*/
private boolean empty;
/** Stack of element names of the element containing keyref attribute. */
private final Deque<String> elemName;
/** Current element keyref info, {@code null} if not keyref type element. */
private KeyrefInfo currentElement;
private boolean hasChecked;
/** Flag stack to indicate whether key reference element has sub-elements. */
private final Deque<Boolean> hasSubElem;
/** Current key definition. */
private KeyDef keyDef;
/** Set of link targets which are not resource-only */
private Set<URI> normalProcessingRoleTargets;
private MergeUtils mergeUtils;
/**
* Constructor.
*/
public KeyrefPaser() {
keyrefLevel = 0;
keyrefLevalStack = new ArrayDeque<>();
validKeyref = new ArrayDeque<>();
empty = true;
elemName = new ArrayDeque<>();
hasSubElem = new ArrayDeque<>();
mergeUtils = new MergeUtils();
}
@Override
public void setLogger(final DITAOTLogger logger) {
super.setLogger(logger);
mergeUtils.setLogger(logger);
}
public void setKeyDefinition(final KeyScope definitionMap) {
this.definitionMap = definitionMap;
}
/**
* Get set of link targets which have normal processing role. Paths are relative to current file.
*/
public Set<URI> getNormalProcessingRoleTargets() {
return Collections.unmodifiableSet(normalProcessingRoleTargets);
}
/**
* Process key references.
*
* @param filename file to process
* @throws DITAOTException if key reference resolution failed
*/
@Override
public void write(final File filename) throws DITAOTException {
assert filename.isAbsolute();
super.write(new File(currentFile));
}
@Override
public void startDocument() throws SAXException {
normalProcessingRoleTargets = new HashSet<>();
getContentHandler().startDocument();
}
@Override
public void characters(final char[] ch, final int start, final int length) throws SAXException {
if (keyrefLevel != 0 && (length == 0 || new String(ch,start,length).trim().isEmpty())) {
if (!hasChecked) {
empty = true;
}
} else {
hasChecked = true;
empty = false;
}
getContentHandler().characters(ch, start, length);
}
@Override
public void endElement(final String uri, final String localName, final String name) throws SAXException {
if (keyrefLevel != 0 && empty && !elemName.peek().equals(MAP_TOPICREF.localName)) {
// If current element is in the scope of key reference element
// and the element is empty
if (!validKeyref.isEmpty() && validKeyref.peek()) {
final Element elem = keyDef.element;
// Key reference is valid,
// need to pull matching content from the key definition
// If current element name doesn't equal the key reference element
// just grab the content from the matching element of key definition
if (!name.equals(elemName.peek())) {
final NodeList nodeList = elem.getElementsByTagName(name);
if (nodeList.getLength() > 0) {
final Element node = (Element) nodeList.item(0);
final NodeList nList = node.getChildNodes();
for (int index = 0; index < nList.getLength(); index++) {
final Node n = nList.item(index);
if (n.getNodeType() == Node.TEXT_NODE) {
final char[] ch = n.getNodeValue().toCharArray();
getContentHandler().characters(ch, 0, ch.length);
break;
}
}
}
} else {
// Current element name equals the key reference element
// grab keyword or term from key definition
if (!hasSubElem.peek() && currentElement != null) {
final List<Element> keywords = toList(elem.getElementsByTagName(TOPIC_KEYWORD.localName));
final List<Element> keywordsInKeywords = keywords.stream()
.filter(item -> TOPIC_KEYWORDS.matches(item.getParentNode()))
.collect(Collectors.toList());
// XXX: No need to look for term as content model for keywords doesn't allow it
// if (nodeList.getLength() == 0 ) {
// nodeList = elem.getElementsByTagName(TOPIC_TERM.localName);
if (!keywordsInKeywords.isEmpty()) {
if (!currentElement.hasNestedElements) {
// only one keyword or term is used.
if (!currentElement.isEmpty) {
domToSax(keywordsInKeywords.get(0), false);
}
} else {
// If the key reference element carries href attribute
// all keyword or term are used.
if (TOPIC_LINK.matches(currentElement.type)) {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts);
} else if (TOPIC_IMAGE.matches(currentElement.type)) {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_ALT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_ALT.localName, TOPIC_ALT.localName, atts);
}
if (!currentElement.isEmpty) {
for (final Element onekeyword: keywordsInKeywords) {
domToSax(onekeyword, true);
}
}
if (TOPIC_LINK.matches(currentElement.type)) {
getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName);
} else if (TOPIC_IMAGE.matches(currentElement.type)) {
getContentHandler().endElement(NULL_NS_URI, TOPIC_ALT.localName, TOPIC_ALT.localName);
}
}
} else {
if (TOPIC_LINK.matches(currentElement.type)) {
// If the key reference element is link or its specialization,
// should pull in the linktext
final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName);
if (linktext.getLength() > 0) {
domToSax((Element) linktext.item(0), true);
} else if (fallbackToNavtitleOrHref(elem)) {
final NodeList navtitleElement = elem.getElementsByTagName(TOPIC_NAVTITLE.localName);
if (navtitleElement.getLength() > 0) {
writeLinktext((Element) navtitleElement.item(0));
} else {
final String navtitle = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE);
if (!navtitle.trim().isEmpty()) {
writeLinktext(navtitle);
} else {
final String hrefAtt = elem.getAttribute(ATTRIBUTE_NAME_HREF);
if (!hrefAtt.trim().isEmpty()) {
writeLinktext(hrefAtt);
}
}
}
}
} else if (TOPIC_IMAGE.matches(currentElement.type)) {
// If the key reference element is an image or its specialization,
// should pull in the linktext
final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName);
if (linktext.getLength() > 0) {
writeAlt((Element) linktext.item(0));
} else if (fallbackToNavtitleOrHref(elem)) {
final NodeList navtitleElement = elem.getElementsByTagName(TOPIC_NAVTITLE.localName);
if (navtitleElement.getLength() > 0) {
writeAlt((Element) navtitleElement.item(0));
} else {
final String navtitle = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE);
if (!navtitle.trim().isEmpty()) {
writeAlt(navtitle);
}
}
}
} else if (fallbackToNavtitleOrHref(elem)) {
final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName);
if (linktext.getLength() > 0) {
domToSax((Element) linktext.item(0), false);
} else {
final NodeList navtitleElement = elem.getElementsByTagName(TOPIC_NAVTITLE.localName);
if (navtitleElement.getLength() > 0) {
domToSax((Element) navtitleElement.item(0), false);
} else {
final String navtitle = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE);
if (!navtitle.trim().isEmpty()) {
final char[] ch = navtitle.toCharArray();
getContentHandler().characters(ch, 0, ch.length);
} else {
final String hrefAtt = elem.getAttribute(ATTRIBUTE_NAME_HREF);
if (!hrefAtt.trim().isEmpty()) {
final char[] ch = hrefAtt.toCharArray();
getContentHandler().characters(ch, 0, ch.length);
}
}
}
}
}
}
}
}
}
}
if (keyrefLevel != 0) {
keyrefLevel
empty = false;
}
if (keyrefLevel == 0 && !keyrefLevalStack.isEmpty()) {
// To the end of key reference, pop the stacks.
keyrefLevel = keyrefLevalStack.pop();
validKeyref.pop();
elemName.pop();
hasSubElem.pop();
}
getContentHandler().endElement(uri, localName, name);
}
/**
* Write linktext element
*
* @param srcElem element content
*/
private void writeLinktext(Element srcElem) throws SAXException {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts);
domToSax(srcElem, false);
getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName);
}
/**
* Write linktext element
*
* @param navtitle element text content
*/
private void writeLinktext(final String navtitle) throws SAXException {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts);
final char[] ch = navtitle.toCharArray();
getContentHandler().characters(ch, 0, ch.length);
getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName);
}
/**
* Write alt element
*
* @param srcElem element content
*/
private void writeAlt(Element srcElem) throws SAXException {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_ALT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_ALT.localName, TOPIC_ALT.localName, atts);
domToSax(srcElem, false);
getContentHandler().endElement(NULL_NS_URI, TOPIC_ALT.localName, TOPIC_ALT.localName);
}
/**
* Write alt element
*
* @param navtitle element text content
*/
private void writeAlt(final String navtitle) throws SAXException {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_ALT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_ALT.localName, TOPIC_ALT.localName, atts);
final char[] ch = navtitle.toCharArray();
getContentHandler().characters(ch, 0, ch.length);
getContentHandler().endElement(NULL_NS_URI, TOPIC_ALT.localName, TOPIC_ALT.localName);
}
@Override
public void startElement(final String uri, final String localName, final String name,
final Attributes atts) throws SAXException {
currentElement = null;
final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS);
for (final KeyrefInfo k : keyrefInfos) {
if (k.type.matches(cls)) {
currentElement = k;
}
}
Attributes resAtts = atts;
hasChecked = false;
empty = true;
if (!hasKeyref(atts)) {
// If the keyrefLevel doesn't equal 0, it means that current element is under the key reference element
if (keyrefLevel != 0) {
keyrefLevel++;
hasSubElem.pop();
hasSubElem.push(true);
}
} else {
elemName.push(name);
if (keyrefLevel != 0) {
keyrefLevalStack.push(keyrefLevel);
hasSubElem.pop();
hasSubElem.push(true);
}
hasSubElem.push(false);
keyrefLevel = 1;
resAtts = processElement(atts);
}
getContentHandler().startElement(uri, localName, name, resAtts);
}
private Attributes processElement(final Attributes atts) {
final AttributesImpl resAtts = new AttributesImpl(atts);
boolean valid = false;
for (final Map.Entry<String, String> attrPair: currentElement.attrs.entrySet()) {
final String keyrefAttr = attrPair.getKey();
final String refAttr = attrPair.getValue();
final String keyrefValue = atts.getValue(keyrefAttr);
if (keyrefValue != null) {
final int slashIndex = keyrefValue.indexOf(SLASH);
String keyName = keyrefValue;
String elementId = "";
if (slashIndex != -1) {
keyName = keyrefValue.substring(0, slashIndex);
elementId = keyrefValue.substring(slashIndex);
}
keyDef = definitionMap.get(keyName);
final Element elem = keyDef != null ? keyDef.element : null;
// If definition is not null
if (keyDef != null) {
if (currentElement != null) {
final NamedNodeMap attrs = elem.getAttributes();
final URI href = keyDef.href;
if (href != null && !href.toString().isEmpty()) {
if (TOPIC_IMAGE.matches(currentElement.type)) {
valid = true;
final URI target = keyDef.source.resolve(href);
final URI relativeTarget = URLUtils.getRelativePath(currentFile, target);
final URI targetOutput = normalizeHrefValue(relativeTarget, elementId);
XMLUtils.addOrSetAttribute(resAtts, refAttr, targetOutput.toString());
} else if (isLocalDita(elem) && keyDef.source != null) {
valid = true;
final URI target = keyDef.source.resolve(href);
final URI topicFile = currentFile.resolve(stripFragment(target));
final URI relativeTarget = setFragment(URLUtils.getRelativePath(currentFile, topicFile), target.getFragment());
String topicId = null;
if (relativeTarget.getFragment() == null && !"".equals(elementId)) {
topicId = getFirstTopicId(topicFile);
}
final URI targetOutput = normalizeHrefValue(relativeTarget, elementId, topicId);
XMLUtils.addOrSetAttribute(resAtts, refAttr, targetOutput.toString());
if (keyDef.scope != null && !keyDef.scope.equals(ATTR_SCOPE_VALUE_LOCAL)) {
XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_SCOPE, keyDef.scope);
} else {
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
}
if (keyDef.format != null && !keyDef.format.equals(ATTR_FORMAT_VALUE_DITA)) {
XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_FORMAT, keyDef.format);
} else {
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
}
// TODO: This should be a separate SAX filter
if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE))) {
final URI f = currentFile.resolve(targetOutput);
normalProcessingRoleTargets.add(f);
}
} else {
valid = true;
final URI targetOutput = normalizeHrefValue(href, elementId);
XMLUtils.addOrSetAttribute(resAtts, refAttr, targetOutput.toString());
if (keyDef.scope != null && !keyDef.scope.equals(ATTR_SCOPE_VALUE_LOCAL)) {
XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_SCOPE, keyDef.scope);
} else {
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
}
if (keyDef.format != null && !keyDef.format.equals(ATTR_FORMAT_VALUE_DITA)) {
XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_FORMAT, keyDef.format);
} else {
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
}
}
} else if (href == null || href.toString().isEmpty()) {
// Key definition does not carry an href or href equals "".
valid = true;
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
} else {
// key does not exist.
final MessageBean m = definitionMap.name == null
? MessageUtils.getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF))
: MessageUtils.getMessage("DOTJ048I", atts.getValue(ATTRIBUTE_NAME_KEYREF), definitionMap.name);
logger.info(m.setLocation(atts).toString());
}
if (valid) {
if (MAP_TOPICREF.matches(currentElement.type)) {
for (int index = 0; index < attrs.getLength(); index++) {
final Attr attr = (Attr) attrs.item(index);
if (!no_copy.contains(attr.getNodeName())) {
XMLUtils.removeAttribute(resAtts, attr.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, attr);
}
}
} else {
for (int index = 0; index < attrs.getLength(); index++) {
final Attr attr = (Attr) attrs.item(index);
if (!no_copy_topic.contains(attr.getNodeName())
&& (attr.getNodeName().equals(refAttr) || resAtts.getIndex(attr.getNodeName()) == -1)) {
XMLUtils.removeAttribute(resAtts, attr.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, attr);
}
}
}
}
}
} else {
// key does not exist
final MessageBean m = definitionMap.name == null
? MessageUtils.getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF))
: MessageUtils.getMessage("DOTJ048I", atts.getValue(ATTRIBUTE_NAME_KEYREF), definitionMap.name);
logger.info(m.setLocation(atts).toString());
}
validKeyref.push(valid);
}
}
return resAtts;
}
private boolean hasKeyref(final Attributes atts) {
if (TOPIC_PARAM.matches(atts) && (atts.getValue(ATTRIBUTE_NAME_VALUETYPE) != null
&& !atts.getValue(ATTRIBUTE_NAME_VALUETYPE).equals(ATTRIBUTE_VALUETYPE_VALUE_REF))) {
return false;
}
for (final String attr: KEYREF_ATTRIBUTES) {
if (atts.getIndex(attr) != -1) {
return true;
}
}
return false;
}
private boolean isLocalDita(final Element elem ) {
final String scopeValue = elem.getAttribute(ATTRIBUTE_NAME_SCOPE);
final String formatValue = elem.getAttribute(ATTRIBUTE_NAME_FORMAT);
return ("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)) &&
("".equals(formatValue) || ATTR_FORMAT_VALUE_DITA.equals(formatValue) || ATTR_FORMAT_VALUE_DITAMAP.equals(formatValue));
}
/**
* Return true when keyref text resolution should use navtitle as a final fallback.
* @param elem Key definition element
* @return
*/
private boolean fallbackToNavtitleOrHref(final Element elem) {
final String hrefValue = elem.getAttribute(ATTRIBUTE_NAME_HREF);
final String locktitleValue = elem.getAttribute(ATTRIBUTE_NAME_LOCKTITLE);
return ((ATTRIBUTE_NAME_LOCKTITLE_VALUE_YES.equals(locktitleValue)) ||
("".equals(hrefValue)) ||
!(isLocalDita(elem)));
}
/**
* Serialize DOM node into a SAX stream.
*
* @param elem element to serialize
* @param retainElements {@code true} to serialize elements, {@code false} to only serialize text nodes.
*/
private void domToSax(final Element elem, final boolean retainElements) throws SAXException {
if (retainElements) {
final AttributesImpl atts = new AttributesImpl();
final NamedNodeMap attrs = elem.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
final Attr a = (Attr) attrs.item(i);
if (a.getNodeName().equals(ATTRIBUTE_NAME_CLASS)) {
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, changeclassValue(a.getNodeValue()));
} else {
XMLUtils.addOrSetAttribute(atts, a);
}
}
getContentHandler().startElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName(), atts);
}
final NodeList nodeList = elem.getChildNodes();
for (int i = 0; i<nodeList.getLength(); i++) {
final Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
final Element e = (Element) node;
// retain tm and text elements
if (TOPIC_TM.matches(e) || TOPIC_TEXT.matches(e)) {
domToSax(e, true);
} else {
domToSax(e, retainElements);
}
} else if (node.getNodeType() == Node.TEXT_NODE) {
final char[] ch = node.getNodeValue().toCharArray();
getContentHandler().characters(ch, 0, ch.length);
}
}
if (retainElements) {
getContentHandler().endElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName());
}
}
/**
* Change map type to topic type.
*/
private String changeclassValue(final String classValue) {
final DitaClass cls = new DitaClass(classValue);
if (cls.equals(MAP_LINKTEXT)) {
return TOPIC_LINKTEXT.toString();
} else if (cls.equals(MAP_SEARCHTITLE)) {
return TOPIC_SEARCHTITLE.toString();
} else if (cls.equals(MAP_SHORTDESC)) {
return TOPIC_SHORTDESC.toString();
} else {
return cls.toString();
}
}
/**
* change elementId into topicId if there is no topicId in key definition.
*/
private static URI normalizeHrefValue(final URI keyName, final String tail) {
if (keyName.getFragment() == null) {
return toURI(keyName + tail.replaceAll(SLASH, SHARP));
}
return toURI(keyName + tail);
}
/**
* Get first topic id
*/
private String getFirstTopicId(final URI topicFile) {
return mergeUtils.getFirstTopicId(topicFile, false);
}
/**
* Insert topic id into href
*/
private static URI normalizeHrefValue(final URI fileName, final String tail, final String topicId) {
//Insert first topic id only when topicid is not set in keydef
//and keyref has elementid
if (fileName.getFragment() == null && !"".equals(tail)) {
return setFragment(fileName, topicId + tail);
}
return toURI(fileName + tail);
}
private static final class KeyrefInfo {
/** DITA class. */
final DitaClass type;
/** Map of key reference to reference attributes. */
final Map<String, String> attrs;
/** Element has nested elements. */
final boolean hasNestedElements;
/** Element is empty. */
final boolean isEmpty;
/**
* Construct a new key reference info object.
*
* @param type element type
* @param attrs Map of key reference to reference attributes
* @param isEmpty flag if element is empty
* @param hasNestedElements element is a reference type
*/
KeyrefInfo(final DitaClass type, final Map<String, String> attrs, final boolean isEmpty, final boolean hasNestedElements) {
this.type = type;
this.attrs = attrs;
this.isEmpty = isEmpty;
this.hasNestedElements = hasNestedElements;
}
/**
* Construct a new key reference info object.
*
* @param type element type
* @param refAttr reference attribute name
* @param isEmpty flag if element is empty
* @param hasNestedElements element is a reference type
*/
KeyrefInfo(final DitaClass type, final String refAttr, final boolean isEmpty, final boolean hasNestedElements) {
final Map<String, String> attrs = new HashMap<>();
attrs.put(ATTRIBUTE_NAME_KEYREF, refAttr);
this.type = type;
this.attrs = attrs;
this.isEmpty = isEmpty;
this.hasNestedElements = hasNestedElements;
}
}
} |
package org.f1x.v1;
import org.f1x.api.session.SessionStatus;
import org.gflogger.GFLog;
import org.gflogger.GFLogFactory;
import java.io.IOException;
import java.util.TimerTask;
// TODO: add disconnect logic
final class SessionMonitoringTask extends TimerTask {
private static final GFLog LOGGER = GFLogFactory.getLog(SessionMonitoringTask.class);
private final FixCommunicator communicator;
private final int heartbeatInterval;
public SessionMonitoringTask(FixCommunicator communicator) {
this.communicator = communicator;
heartbeatInterval = communicator.getSettings().getHeartBeatIntervalSec() * 1000;
}
@Override
public void run() {
SessionStatus currentStatus = communicator.getSessionStatus();
if (currentStatus == SessionStatus.ApplicationConnected) {
long currentTime = communicator.timeSource.currentTimeMillis();
checkInbound(currentTime);
checkOutbound(currentTime);
}
}
private void checkInbound(long currentTime) {
if (communicator.getSessionStatus() == SessionStatus.ApplicationConnected) {
long lastReceivedMessageTimestamp = communicator.getSessionState().getLastReceivedMessageTimestamp();
if (lastReceivedMessageTimestamp < currentTime - heartbeatInterval) {
LOGGER.debug().append("Haven't heard from the other side for a while. Sending TEST(1) message to validate connection.").commit();
try {
communicator.sendTestRequest("Are you there?"); // TODO: testReqId Generator?
} catch (IOException e) {
LOGGER.warn().append("Error sending TEST(1)").append(e).commit();
}
}
}
}
private void checkOutbound(long currentTime) {
long lastSentMessageTimestamp = communicator.getSessionState().getLastSentMessageTimestamp();
if (lastSentMessageTimestamp < currentTime - heartbeatInterval) {
LOGGER.debug().append("Connection is idle. Sending HEARTBEAT(0) to confirm connection.").commit();
try {
communicator.sendHeartbeat(null);
} catch (IOException e) {
LOGGER.warn().append("Error sending HEARTBEAT(0)").append(e).commit();
}
}
}
} |
package org.gitlab4j.api;
import java.util.List;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.MergeRequest;
/**
* This class implements the client side API for the GitLab merge request calls.
*/
public class MergeRequestApi extends AbstractApi {
public MergeRequestApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get all merge requests for the specified project.
*
* GET /projects/:id/merge_requests
*
* @param projectId the project ID to get the merge requests for
* @return all merge requests for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<MergeRequest> getMergeRequests(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "merge_requests");
return (response.readEntity(new GenericType<List<MergeRequest>>() {}));
}
/**
* Get all merge requests for the specified project.
*
* GET /projects/:id/merge_requests
*
* @param projectId the project ID to get the merge requests for
* @param page the page to get
* @param perPage the number of MergeRequest instances per page
* @return all merge requests for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<MergeRequest> getMergeRequests(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "merge_requests");
return (response.readEntity(new GenericType<List<MergeRequest>>() {}));
}
/**
* Get all merge requests for the specified project.
*
* GET /projects/:id/merge_requests
*
* @param projectId the project ID to get the merge requests for
* @param itemsPerPage the number of MergeRequest instances that will be fetched per page
* @return all merge requests for the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<MergeRequest> getMergeRequests(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<MergeRequest>(this, MergeRequest.class, itemsPerPage, null, "projects", projectId, "merge_requests"));
}
/**
* Get information about a single merge request.
*
* GET /projects/:id/merge_requests/:merge_request_id
*
* @param projectId the project ID of the merge request
* @param mergeRequestId the ID of the merge request
* @return the specified MergeRequest instance
* @throws GitLabApiException if any exception occurs
*/
public MergeRequest getMergeRequest(Integer projectId, Integer mergeRequestId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "merge_requests", mergeRequestId);
return (response.readEntity(MergeRequest.class));
}
/**
* Get a list of merge request commits.
*
* GET /projects/:id/merge_requests/:merge_request_iid/commits
*
* @param projectId the project ID for the merge request
* @param mergeRequestId the ID of the merge request
* @return a list containing the commits for the specified merge request
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public List<Commit> getCommits(int projectId, int mergeRequestId) throws GitLabApiException {
return (getCommits(projectId, mergeRequestId, 1, getDefaultPerPage()));
}
/**
* Get a list of merge request commits.
*
* GET /projects/:id/merge_requests/:merge_request_iid/commits
*
* @param projectId the project ID for the merge request
* @param mergeRequestId the ID of the merge request
* @param page the page to get
* @param perPage the number of commits per page
* @return a list containing the commits for the specified merge request
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public List<Commit> getCommits(int projectId, int mergeRequestId, int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("owned", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects", projectId, "merge_requests", mergeRequestId, "commits");
return (response.readEntity(new GenericType<List<Commit>>() {}));
}
/**
* Get a Pager of merge request commits.
*
* GET /projects/:id/merge_requests/:merge_request_iid/commits
*
* @param projectId the project ID for the merge request
* @param mergeRequestId the ID of the merge request
* @param itemsPerPage the number of Commit instances that will be fetched per page
* @return a Pager containing the commits for the specified merge request
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public Pager<Commit> getCommits(int projectId, int mergeRequestId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Commit>(this, Commit.class, itemsPerPage, null,
"projects", projectId, "merge_requests", mergeRequestId, "commits"));
}
/**
* Creates a merge request and optionally assigns a reviewer to it.
*
* POST /projects/:id/merge_requests
*
* @param projectId the ID of a project, required
* @param sourceBranch the source branch, required
* @param targetBranch the target branch, required
* @param title the title for the merge request, required
* @param description the description of the merge request
* @param assigneeId the Assignee user ID, optional
* @return the created MergeRequest instance
* @throws GitLabApiException if any exception occurs
*/
public MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title, String description, Integer assigneeId)
throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
Form formData = new Form();
addFormParam(formData, "source_branch", sourceBranch, true);
addFormParam(formData, "target_branch", targetBranch, true);
addFormParam(formData, "title", title, true);
addFormParam(formData, "description", description, false);
addFormParam(formData, "assignee_id", assigneeId, false);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "merge_requests");
return (response.readEntity(MergeRequest.class));
}
/**
* Updates an existing merge request. You can change branches, title, or even close the MR.
*
* PUT /projects/:id/merge_requests/:merge_request_id
*
* @param projectId the ID of a project
* @param mergeRequestId the internal ID of the merge request to update
* @param targetBranch the target branch, optional
* @param title the title for the merge request
* @param assigneeId the Assignee user ID, optional
* @param description the description of the merge request, optional
* @param stateEvent new state for the merge request, optional
* @param labels comma separated list of labels, optional
* @param milestoneId the ID of a milestone, optional
* @return the updated merge request
* @throws GitLabApiException if any exception occurs
*/
public MergeRequest updateMergeRequest(Integer projectId, Integer mergeRequestId, String targetBranch,
String title, Integer assigneeId, String description, StateEvent stateEvent, String labels,
Integer milestoneId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Form formData = new GitLabApiForm()
.withParam("target_branch", targetBranch)
.withParam("title", title)
.withParam("assignee_id", assigneeId)
.withParam("description", description)
.withParam("state_event", stateEvent)
.withParam("labels", labels)
.withParam("milestone_id", milestoneId);
Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "merge_requests", mergeRequestId);
return (response.readEntity(MergeRequest.class));
}
/**
* Updates an existing merge request. You can change branches, title, or even close the MR.
*
* PUT /projects/:id/merge_requests/:merge_request_id
*
* @param projectId the ID of a project
* @param mergeRequestId the ID of the merge request to update
* @param sourceBranch the source branch
* @param targetBranch the target branch
* @param title the title for the merge request
* @param description the description of the merge request
* @param assigneeId the Assignee user ID, optional
* @return the updated merge request
* @throws GitLabApiException if any exception occurs
* @deprecated as of release 4.4.3
*/
@Deprecated
public MergeRequest updateMergeRequest(Integer projectId, Integer mergeRequestId, String sourceBranch, String targetBranch, String title, String description,
Integer assigneeId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Form formData = new Form();
addFormParam(formData, "source_branch", sourceBranch, false);
addFormParam(formData, "target_branch", targetBranch, false);
addFormParam(formData, "title", title, false);
addFormParam(formData, "description", description, false);
addFormParam(formData, "assignee_id", assigneeId, false);
Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "merge_requests", mergeRequestId);
return (response.readEntity(MergeRequest.class));
}
/**
* Only for admins and project owners. Soft deletes the specified merge.
*
* DELETE /projects/:id/merge_requests/:merge_request_iid
*
* @param projectId the ID of a project
* @param mergeRequestId the internal ID of the merge request\
* @throws GitLabApiException if any exception occurs
*/
public void deleteMergeRequest(Integer projectId, Integer mergeRequestId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects", projectId, "merge_requests", mergeRequestId);
}
public MergeRequest acceptMergeRequest(Integer projectId, Integer mergeRequestId,
String mergeCommitMessage, Boolean shouldRemoveSourceBranch, Boolean mergeWhenPipelineSucceeds)
throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Form formData = new GitLabApiForm()
.withParam("merge_commit_message", mergeCommitMessage)
.withParam("should_remove_source_branch", shouldRemoveSourceBranch)
.withParam("merge_when_pipeline_succeeds", mergeWhenPipelineSucceeds);
Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "merge_requests", mergeRequestId, "merge");
return (response.readEntity(MergeRequest.class));
}
public MergeRequest cancelMergeRequest(Integer projectId, Integer mergeRequestId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Response response = put(Response.Status.OK, null, "projects", projectId, "merge_requests", mergeRequestId, "cancel_merge_when_pipeline_succeeds");
return (response.readEntity(MergeRequest.class));
}
/**
* Get the merge request with approval information.
*
* Note: This API endpoint is only available on 8.9 EE and above.
*
* GET /projects/:id/merge_requests/:merge_request_iid/approvals
*
* @param projectId the project ID of the merge request
* @param mergeRequestId the internal ID of the merge request
* @return a MergeRequest instance with approval information included
* @throws GitLabApiException if any exception occurs
*/
public MergeRequest getMergeRequestApprovals(Integer projectId, Integer mergeRequestId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Response response = get(Response.Status.OK, null, "projects", projectId, "merge_requests", mergeRequestId, "approvals");
return (response.readEntity(MergeRequest.class));
}
/**
* Approve a merge request.
*
* Note: This API endpoint is only available on 8.9 EE and above.
*
* POST /projects/:id/merge_requests/:merge_request_iid/approve
*
* @param projectId the project ID of the merge request
* @param mergeRequestId the internal ID of the merge request
* @param sha the HEAD of the merge request, optional
* @return a MergeRequest instance with approval information included
* @throws GitLabApiException if any exception occurs
*/
public MergeRequest approveMergeRequest(Integer projectId, Integer mergeRequestId, String sha) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = post(Response.Status.OK, formData, "projects", projectId, "merge_requests", mergeRequestId, "approve");
return (response.readEntity(MergeRequest.class));
}
/**
* Unapprove a merge request.
*
* Note: This API endpoint is only available on 8.9 EE and above.
*
* POST /projects/:id/merge_requests/:merge_request_iid/unapprove
*
* @param projectId the project ID of the merge request
* @param mergeRequestId the internal ID of the merge request
* @return a MergeRequest instance with approval information included
* @throws GitLabApiException if any exception occurs
*/
public MergeRequest unapproveMergeRequest(Integer projectId, Integer mergeRequestId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
Response response = post(Response.Status.OK, (Form)null, "projects", projectId, "merge_requests", mergeRequestId, "unapprove");
return (response.readEntity(MergeRequest.class));
}
} |
package org.jenetics;
import static java.lang.Math.abs;
import static org.jenetics.util.ArrayUtils.sum;
import static org.jenetics.util.BitUtils.ulpDistance;
import static org.jenetics.util.Validator.nonNull;
import java.util.Random;
import org.jenetics.util.RandomRegistry;
public abstract class ProbabilitySelector<G extends Gene<?, G>, C extends Comparable<C>>
implements Selector<G, C>
{
private static final long serialVersionUID = -2980541308499034709L;
private static final long MAX_ULP_DISTANCE = (long)Math.pow(10, 10);
protected ProbabilitySelector() {
}
@Override
public Population<G, C> select(
final Population<G, C> population,
final int count,
final Optimize opt
) {
nonNull(population, "Population");
nonNull(opt, "Optimization");
if (count < 0) {
throw new IllegalArgumentException(String.format(
"Selection count must be greater or equal then zero, but was %s.",
count
));
}
final Population<G, C> selection = new Population<G, C>(count);
if (count > 0) {
final double[] probabilities = probabilities(population, count, opt);
assert (population.size() == probabilities.length) :
"Population size and probability length are not equal.";
assert (check(probabilities)) : "Probabilities doesn't sum to one.";
final Random random = RandomRegistry.getRandom();
for (int i = 0; i < count; ++i) {
selection.add(population.get(nextIndex(probabilities, random)));
}
assert (count == selection.size());
}
return selection;
}
/**
* This method takes the probabilities from the
* {@link #probabilities(Population, int)} method and inverts it if needed.
*
* @param population The population.
* @param count The number of phenotypes to select.
* @param opt Determines whether the individuals with higher fitness values
* or lower fitness values must be selected. This parameter determines
* whether the GA maximizes or minimizes the fitness function.
* @return Probability array.
*/
protected final double[] probabilities(
final Population<G, C> population,
final int count,
final Optimize opt
) {
final double[] probabilities = probabilities(population, count);
if (opt == Optimize.MINIMUM) {
invert(probabilities);
}
return probabilities;
}
private static void invert(final double[] probabilities) {
for (int i = 0; i < probabilities.length; ++i) {
probabilities[i] = 1.0 - probabilities[i];
}
}
/**
* Return an Probability array, which corresponds to the given Population.
* The probability array and the population must have the same size. The
* population is not sorted. If a subclass needs a sorted population, the
* subclass is responsible to sort the population.
* <p/>
* The implementor always assumes that higher fitness values are better. The
* base class inverts the probabilities ({@code p = 1.0 - p }) if the GA is
* supposed to minimize the fitness function.
*
* @param population The <em>unsorted</em> population.
* @param count The number of phenotypes to select. <i>This parameter is not
* needed for most implementations.</i>
* @return Probability array. The returned probability array must have the
* length {@code population.size()} and <strong>must</strong> sum to
* one. The returned value is checked with
* {@code assert(Math.abs(ArrayUtils.sum(probabilities) - 1.0) < 0.0001)}
* in the base class.
*/
protected abstract double[] probabilities(
final Population<G, C> population,
final int count
);
protected static boolean check(final double[] probabilities) {
final double sum = sum(probabilities);
boolean check = abs(ulpDistance(sum, 1.0)) < MAX_ULP_DISTANCE;
// if (!check) {
// System.out.println("Sum: " + sum + " " + probabilities.length);
// System.out.println(Arrays.toString(probabilities));
return check;
}
/**
* Return the next random index. The index probability is given by the
* {@code probabilities} array. The values of the {@code probabilities} array
* must sum to one.
*
* @param probabilities the probabilities array (must sum to one).
* @param random the random number generator.
* @return the random index.
*/
static int nextIndex(final double[] probabilities, final Random random) {
final double prop = random.nextDouble();
int j = 0;
double sum = 0;
for (int i = 0; sum < prop && i < probabilities.length; ++i) {
sum += probabilities[i];
j = i;
}
return j;
}
} |
package org.jtrfp.trcl.flow;
import java.util.List;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.Tunnel;
import org.jtrfp.trcl.beh.ChangesBehaviorWhenTargeted;
import org.jtrfp.trcl.beh.CustomNAVTargetableBehavior;
import org.jtrfp.trcl.beh.DamageableBehavior;
import org.jtrfp.trcl.beh.RemovesNAVObjectiveOnDeath;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.Location3D;
import org.jtrfp.trcl.file.NAVFile.BOS;
import org.jtrfp.trcl.file.NAVFile.CHK;
import org.jtrfp.trcl.file.NAVFile.DUN;
import org.jtrfp.trcl.file.NAVFile.NAVSubObject;
import org.jtrfp.trcl.file.NAVFile.TGT;
import org.jtrfp.trcl.file.NAVFile.TUN;
import org.jtrfp.trcl.file.NAVFile.XIT;
import org.jtrfp.trcl.file.TDFFile.ExitMode;
import org.jtrfp.trcl.file.TDFFile.TunnelLogic;
import org.jtrfp.trcl.obj.Checkpoint;
import org.jtrfp.trcl.obj.DEFObject;
import org.jtrfp.trcl.obj.TunnelEntranceObject;
import org.jtrfp.trcl.obj.TunnelEntranceObject.TunnelEntranceBehavior;
import org.jtrfp.trcl.obj.TunnelExitObject;
import org.jtrfp.trcl.obj.WorldObject;
public abstract class NAVObjective {
private static final double CHECKPOINT_HEIGHT_PADDING=70000;
public abstract String getDescription();
public abstract WorldObject getTarget();
protected NAVObjective(Factory f){
f.tr.getReporter().report("org.jtrfp.trcl.flow.NAVObjective."+f.counter+".desc", getDescription());
final double [] loc = getTarget().getPosition();
if(getTarget()!=null)f.tr.getReporter().report("org.jtrfp.trcl.flow.NAVObjective."+f.counter+".loc", "X="+loc[0]+" Y="+loc[1]+" Z="+loc[2]);
f.counter++;
}
public static class Factory{
private TR tr;//for debug
private Tunnel currentTunnel;
int counter;
private WorldObject worldBossObject,bossChamberExitShutoffTrigger;
public Factory(TR tr){
this.tr=tr;
}//end constructor
public void create(TR tr, NAVSubObject navSubObject, List<NAVObjective>indexedNAVObjectiveList){
final OverworldSystem overworld=tr.getOverworldSystem();
final List<DEFObject> defs = overworld.getDefList();
if(navSubObject instanceof TGT){
TGT tgt = (TGT)navSubObject;
int [] targs = tgt.getTargets();
for(int i=0; i<targs.length;i++){
final WorldObject targ = defs.get(targs[i]);
final NAVObjective objective = new NAVObjective(this){
@Override
public String getDescription() {
return "Destroy Target";
}
@Override
public WorldObject getTarget() {
return targ;
}
};//end new NAVObjective
indexedNAVObjectiveList.add(objective);
targ.addBehavior(new RemovesNAVObjectiveOnDeath(objective,tr.getCurrentMission()));
}//end for(targs)
} else if(navSubObject instanceof TUN){
TUN tun = (TUN)navSubObject;
//Entrance and exit locations are already set up.
final Location3D loc3d = tun.getLocationOnMap();
currentTunnel = tr.getCurrentMission().getTunnelWhoseEntranceClosestTo(loc3d.getX(),loc3d.getY(),loc3d.getZ());
final TunnelEntranceObject tunnelEntrance
= currentTunnel.getEntranceObject();
final double [] entPos=tunnelEntrance.getPosition();
entPos[0]=TR.legacy2Modern(loc3d.getZ());
entPos[1]=TR.legacy2Modern(loc3d.getY());
entPos[2]=TR.legacy2Modern(loc3d.getX());
entPos[1]=tr.getAltitudeMap().heightAt(
TR.legacy2MapSquare(loc3d.getZ()),
TR.legacy2MapSquare(loc3d.getX()))*(tr.getWorld().sizeY/2);
entPos[1]-=7000;//nudge
tunnelEntrance.notifyPositionChange();
final NAVObjective enterObjective = new NAVObjective(this){
@Override
public String getDescription() {
return "Enter Tunnel";
}
@Override
public WorldObject getTarget() {
return tunnelEntrance;
}
};//end new NAVObjective tunnelEnrance
tunnelEntrance.setNavObjectiveToRemove(enterObjective,true);
indexedNAVObjectiveList.add(enterObjective);
final TunnelExitObject tunnelExit = currentTunnel.getExitObject();
final NAVObjective exitObjective = new NAVObjective(this){
@Override
public String getDescription() {
return "Exit Tunnel";
}
@Override
public WorldObject getTarget() {
return tunnelExit;
}
};//end new NAVObjective tunnelExit
indexedNAVObjectiveList.add(exitObjective);
tunnelExit.setNavObjectiveToRemove(exitObjective);
tunnelExit.setMirrorTerrain(currentTunnel.getSourceTunnel().getExitMode()==ExitMode.exitToChamber);
if(currentTunnel.getSourceTunnel().getEntranceLogic()==TunnelLogic.visibleUnlessBoss){
bossChamberExitShutoffTrigger.addBehavior(new CustomNAVTargetableBehavior(new Runnable(){
@Override
public void run() {
tunnelEntrance.getBehavior().probeForBehavior(TunnelEntranceBehavior.class).setEnable(false);}
}));
worldBossObject.addBehavior(new CustomDeathBehavior(new Runnable(){
@Override
public void run(){
tunnelEntrance.getBehavior().probeForBehavior(TunnelEntranceBehavior.class).setEnable(true);
}
}));
}//end if(visibleUnlessBoss)
} else if(navSubObject instanceof BOS){
final Mission mission = tr.getCurrentMission();
final BOS bos = (BOS)navSubObject;
boolean first=true;
for(final int target:bos.getTargets()){
final WorldObject shieldGen = defs.get(target);
final NAVObjective objective = new NAVObjective(this){
@Override
public String getDescription() {
return "Destroy Shield Gen";
}
@Override
public WorldObject getTarget() {
return shieldGen;
}
};//end new NAVObjective
if(first){
bossChamberExitShutoffTrigger=shieldGen;
first=false;
}//end if(first)
shieldGen.addBehavior(new RemovesNAVObjectiveOnDeath(objective,mission));
bossChamberExitShutoffTrigger.addBehavior(new CustomNAVTargetableBehavior(new Runnable(){
@Override
public void run() {
shieldGen.getBehavior().probeForBehavior(DamageableBehavior.class).setEnable(true);
shieldGen.setActive(true);
}
}));
indexedNAVObjectiveList.add(objective);
}//end for(targets)
final WorldObject bossObject = defs.get(bos.getBossIndex());
final NAVObjective objective = new NAVObjective(this){
@Override
public String getDescription() {
return "Destroy Boss";
}
@Override
public WorldObject getTarget() {
return bossObject;
}
};//end new NAVObjective
indexedNAVObjectiveList.add(objective);
bossObject.addBehavior(new RemovesNAVObjectiveOnDeath(objective,mission));
bossObject.addBehavior(new ChangesBehaviorWhenTargeted(true,DamageableBehavior.class));
if(bos.getTargets().length==0){
bossChamberExitShutoffTrigger=bossObject;}
worldBossObject = bossObject;
bossChamberExitShutoffTrigger.addBehavior(new CustomNAVTargetableBehavior(new Runnable(){
@Override
public void run() {
bossObject.setActive(true);}
}));
} else if(navSubObject instanceof CHK){
final CHK cp = (CHK)navSubObject;
final Location3D loc3d = cp.getLocationOnMap();
final Checkpoint chk = new Checkpoint(tr);
final double [] chkPos = chk.getPosition();
chkPos[0]=TR.legacy2Modern(loc3d.getZ());
chkPos[1]=TR.legacy2Modern(loc3d.getY()+CHECKPOINT_HEIGHT_PADDING);
chkPos[2]=TR.legacy2Modern(loc3d.getX());
chk.notifyPositionChange();
chk.setIncludeYAxisInCollision(false);
final NAVObjective objective = new NAVObjective(this){
@Override
public String getDescription() {
return "Checkpoint";
}
@Override
public WorldObject getTarget() {
return chk;
}
};//end new NAVObjective
chk.setObjectiveToRemove(objective,tr.getCurrentMission());
overworld.add(chk);
indexedNAVObjectiveList.add(objective);
} else if(navSubObject instanceof XIT){
XIT xit = (XIT)navSubObject;
Location3D loc3d = xit.getLocationOnMap();
currentTunnel.getExitObject().setExitLocation(
new Vector3D(TR.legacy2Modern(loc3d.getZ()),TR.legacy2Modern(loc3d.getY()),TR.legacy2Modern(loc3d.getX())));
} else if(navSubObject instanceof DUN){
final DUN xit = (DUN)navSubObject;
final Location3D loc3d = xit.getLocationOnMap();
final Checkpoint chk = new Checkpoint(tr);
final double [] chkPos = chk.getPosition();
chkPos[0]=TR.legacy2Modern(loc3d.getZ());
chkPos[1]=TR.legacy2Modern(loc3d.getY());
chkPos[2]=TR.legacy2Modern(loc3d.getX());
chk.notifyPositionChange();
chk.setVisible(false);
try{//Start placing the jump zone.
WorldObject jumpZone = new WorldObject(tr,tr.getResourceManager().getBINModel("JUMP-PNT.BIN", tr.getGlobalPalette(), tr.getGPU().getGl()));
jumpZone.setPosition(chk.getPosition());
jumpZone.setVisible(true);
overworld.add(jumpZone);
final NAVObjective objective = new NAVObjective(this){
@Override
public String getDescription() {
return "Fly To Jump Zone";
}
@Override
public WorldObject getTarget() {
return chk;
}
};//end new NAVObjective
chk.setObjectiveToRemove(objective,tr.getCurrentMission());
chk.setIncludeYAxisInCollision(false);
overworld.add(chk);
indexedNAVObjectiveList.add(objective);
}catch(Exception e){e.printStackTrace();}
}else{System.err.println("Unrecognized NAV objective: "+navSubObject);}
}//end create()
}//end Factory
}//end NAVObjective |
package org.mastodon.trackmate;
import java.util.Map;
import org.mastodon.HasErrorMessage;
import org.mastodon.detection.mamut.SpotDetectorOp;
import org.mastodon.graph.algorithm.RootFinder;
import org.mastodon.linking.mamut.SpotLinkerOp;
import org.mastodon.revised.model.mamut.Link;
import org.mastodon.revised.model.mamut.Model;
import org.mastodon.revised.model.mamut.ModelGraph;
import org.mastodon.revised.model.mamut.Spot;
import org.scijava.Cancelable;
import org.scijava.app.StatusService;
import org.scijava.command.ContextCommand;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import bdv.spimdata.SpimDataMinimal;
import net.imagej.ops.Op;
import net.imagej.ops.OpService;
import net.imagej.ops.special.hybrid.Hybrids;
import net.imagej.ops.special.inplace.Inplaces;
public class TrackMate extends ContextCommand implements HasErrorMessage
{
@Parameter
private OpService ops;
@Parameter
private StatusService statusService;
@Parameter
LogService log;
private final Settings settings;
private final Model model;
private Op currentOp;
private boolean succesful;
private String errorMessage;
public TrackMate( final Settings settings )
{
this.settings = settings;
this.model = createModel();
}
public TrackMate( final Settings settings, final Model model )
{
this.settings = settings;
this.model = model;
}
protected Model createModel()
{
return new Model();
}
public Model getModel()
{
return model;
}
public Settings getSettings()
{
return settings;
}
public boolean execDetection()
{
succesful = true;
errorMessage = null;
if ( isCanceled() )
return true;
final ModelGraph graph = model.getGraph();
final SpimDataMinimal spimData = settings.values.getSpimData();
if ( null == spimData )
{
errorMessage = "Cannot start detection: SpimData object is null.\n";
log.error( errorMessage + '\n' );
succesful = false;
return false;
}
/*
* Clear previous content.
*/
for ( final Spot spot : model.getGraph().vertices() )
model.getGraph().remove( spot );
/*
* Exec detection.
*/
final long start = System.currentTimeMillis();
final Class< ? extends SpotDetectorOp > cl = settings.values.getDetector();
final Map< String, Object > detectorSettings = settings.values.getDetectorSettings();
final SpotDetectorOp detector = ( SpotDetectorOp ) Hybrids.unaryCF( ops, cl,
graph, spimData,
detectorSettings );
this.currentOp = detector;
log.info( "Detection with " + cl.getSimpleName() + '\n' );
detector.compute( spimData, graph );
if ( !detector.isSuccessful() )
{
log.error( "Detection failed:\n" + detector.getErrorMessage() + '\n' );
succesful = false;
errorMessage = detector.getErrorMessage();
return false;
}
currentOp = null;
model.getGraphFeatureModel().declareFeature( detector.getQualityFeature() );
final long end = System.currentTimeMillis();
log.info( String.format( "Detection completed in %.1f s.\n", ( end - start ) / 1000. ) );
log.info( "Found " + graph.vertices().size() + " spots.\n" );
model.getGraph().notifyGraphChanged();
return true;
}
public boolean execParticleLinking()
{
succesful = true;
errorMessage = null;
if ( isCanceled() )
return true;
/*
* Clear previous content.
*/
for ( final Link link : model.getGraph().edges() )
model.getGraph().remove( link );
/*
* Exec particle linking.
*/
final long start = System.currentTimeMillis();
final Class< ? extends SpotLinkerOp > linkerCl = settings.values.getLinker();
final Map< String, Object > linkerSettings = settings.values.getLinkerSettings();
final SpotLinkerOp linker =
( SpotLinkerOp ) Inplaces.binary1( ops, linkerCl, model.getGraph(), model.getSpatioTemporalIndex(),
linkerSettings, model.getGraphFeatureModel() );
log.info( "Particle-linking with " + linkerCl.getSimpleName() + '\n' );
this.currentOp = linker;
linker.mutate1( model.getGraph(), model.getSpatioTemporalIndex() );
if ( !linker.isSuccessful() )
{
log.error( "Particle-linking failed:\n" + linker.getErrorMessage() + '\n' );
succesful = false;
errorMessage = linker.getErrorMessage();
return false;
}
currentOp = null;
model.getGraphFeatureModel().declareFeature( linker.getLinkCostFeature() );
final long end = System.currentTimeMillis();
log.info( String.format( "Particle-linking completed in %.1f s.\n", ( end - start ) / 1000. ) );
final int nTracks = RootFinder.getRoots( model.getGraph() ).size();
log.info( String.format( "Found %d tracks.\n", nTracks ) );
model.getGraph().notifyGraphChanged();
return true;
}
@Override
public void run()
{
if ( execDetection() && execParticleLinking() )
;
}
// -- Cancelable methods --
/** Reason for cancelation, or null if not canceled. */
private String cancelReason;
@Override
public void cancel( final String reason )
{
cancelReason = reason;
if ( null != currentOp && ( currentOp instanceof Cancelable ) )
{
final Cancelable cancelable = ( Cancelable ) currentOp;
cancelable.cancel( reason );
}
}
@Override
public boolean isCanceled()
{
return cancelReason != null;
}
@Override
public String getCancelReason()
{
return cancelReason;
}
@Override
public String getErrorMessage()
{
return errorMessage;
}
@Override
public boolean isSuccessful()
{
return succesful;
}
} |
package org.mmog2048.verticles;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.sockjs.BridgeOptions;
import io.vertx.ext.web.handler.sockjs.PermittedOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.mmog2048.dao.RedisDAO;
import org.mmog2048.utils.RedisUtils;
import java.util.Date;
import java.util.UUID;
public class WebServer extends AbstractVerticle {
private static final Logger LOG = LoggerFactory.getLogger(WebServer.class);
@Override
public void start(Future<Void> future) {
try {
JsonObject config = context.config();
RedisOptions redisOptions = RedisUtils.createRedisOptions(config.getJsonObject("redis"));
RedisClient redisClient = RedisClient.create(vertx, redisOptions);
// Clear db on restart
redisClient.flushall(event2 -> System.out.println(event2.result()));
redisClient.info(event1 -> System.out.println(event1.result()));
RedisDAO redisDAO = new RedisDAO(redisClient);
EventBus eb = vertx.eventBus();
vertx.setPeriodic(
500, event -> {
String now = DateFormatUtils.ISO_DATETIME_FORMAT.format(new Date());
System.out.println(now);
redisDAO.getTopScores(GameEngine.contest, event1 -> {
eb.publish("org.mmog2048:game-state",
new JsonObject().put("boards", event1));
});
eb.publish("org.mmog2048:status-message", "Hello " + RandomStringUtils.randomAlphabetic(10) + " " + now);
}
);
eb.consumer("org.mmog2048:register", event -> {
String name = ((JsonObject)event.body()).getString("name");
JsonObject board = new JsonObject().put("tiles", new JsonArray(
"[0,0,0,0," +
"0,2,0,0," +
"0,0,0,0," +
"0,0,4,0]"))
.put("name", name);
String uuid = UUID.randomUUID().toString();
redisDAO.saveBoardInfo(GameEngine.contest, uuid, board, event1 -> {});
// Register this specific game channel to receive moves
eb.consumer("org.mmog2048:move:" + uuid, eventMove -> {
JsonObject eventMoveJson = ((JsonObject) eventMove.body());
String move = eventMoveJson.getString("move");
GameEngine.updateGame(uuid, move, redisDAO, boardInfo -> eventMove.reply(
new JsonObject().put("board", boardInfo)
));
});
JsonObject reply = new JsonObject();
reply.put("token", uuid);
reply.put("board", board);
event.reply(reply);
});
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
BridgeOptions options = new BridgeOptions();
PermittedOptions permitted = new PermittedOptions(); /* allow everything, we don't care for the demo */
options.addOutboundPermitted(permitted);
options.addInboundPermitted(permitted);
sockJSHandler.bridge(options);
Router router = Router.router(vertx);
StaticHandler assetHandler = StaticHandler
.create()
.setDirectoryListing(true); |
package org.myrobotlab.service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.alicebot.ab.AIMLMap;
import org.alicebot.ab.AIMLSet;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Category;
import org.alicebot.ab.Chat;
import org.alicebot.ab.Predicates;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.programab.ChatData;
import org.myrobotlab.programab.OOBPayload;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class ProgramAB extends Service implements TextListener, TextPublisher {
transient public final static Logger log = LoggerFactory.getLogger(ProgramAB.class);
public static class Response {
public String session;
public String msg;
transient public List<OOBPayload> payloads;
// FIXME - timestamps are usually longs System.currentTimeMillis()
public Date timestamp;
public Response(String session, String msg, List<OOBPayload> payloads, Date timestamp) {
this.session = session;
this.msg = msg;
this.payloads = payloads;
this.timestamp = timestamp;
}
public String toString() {
return String.format("%d %s %s", timestamp.getTime(), session, msg);
}
}
transient Bot bot = null;
HashSet<String> bots = new HashSet<String>();
private String path = "ProgramAB";
public boolean aimlError = false;
/**
* botName - is un-initialized to preserve serialization stickyness
*/
// String botName;
// This is the username that is chatting with the bot.
// String currentSession = "default";
// Session is a user and a bot. so the key to the session should be the
// username, and the bot name.
transient HashMap<String, ChatData> sessions = new HashMap<String, ChatData>();
// TODO: better parsing than a regex...
transient Pattern oobPattern = Pattern.compile("<oob>.*?</oob>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
transient Pattern mrlPattern = Pattern.compile("<mrl>.*?</mrl>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
// a guaranteed bot we have
private String currentBotName = "alice2";
// this is the username that is chatting with the bot.
private String currentUserName = "default";
public boolean loading = false;
static final long serialVersionUID = 1L;
static int savePredicatesInterval = 60 * 1000 * 5; // every 5 minutes
public String wasCleanyShutdowned;
public ProgramAB(String name) {
super(name);
// Tell programAB to persist it's learned predicates about people
// every 30 seconds.
addTask("savePredicates", savePredicatesInterval, 0, "savePredicates");
// TODO: Lazy load this!
// look for local bots defined
File programAbDir = new File(String.format("%s/bots", getPath()));
if (!programAbDir.exists() || !programAbDir.isDirectory()) {
log.info("%s does not exist !!!");
} else {
File[] listOfFiles = programAbDir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
// System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
bots.add(listOfFiles[i].getName());
}
}
}
}
public void addOOBTextListener(TextListener service) {
addListener("publishOOBText", service.getName(), "onOOBText");
}
public void addResponseListener(Service service) {
addListener("publishResponse", service.getName(), "onResponse");
}
public void addTextListener(TextListener service) {
addListener("publishText", service.getName(), "onText");
}
public void addTextPublisher(TextPublisher service) {
subscribe(service.getName(), "publishText");
}
private void cleanOutOfDateAimlIFFiles(String botName) {
String aimlPath = getPath() + File.separator + "bots" + File.separator + botName + File.separator + "aiml";
String aimlIFPath = getPath() + File.separator + "bots" + File.separator + botName + File.separator + "aimlif";
aimlError = false;
log.info("AIML FILES:");
File folder = new File(aimlPath);
File folderaimlIF = new File(aimlIFPath);
if (!folder.exists()) {
log.error("{} does not exist", aimlPath);
aimlError = true;
return;
}
if (wasCleanyShutdowned == null || wasCleanyShutdowned.isEmpty()) {
wasCleanyShutdowned = "firstStart";
}
if (wasCleanyShutdowned.equals("nok")) {
if (folderaimlIF.exists()) {
// warn("Bad previous shutdown, ProgramAB need to recompile AimlIf
// files. Don't worry.");
log.info("Bad previous shutdown, ProgramAB need to recompile AimlIf files. Don't worry.");
for (File f : folderaimlIF.listFiles()) {
f.delete();
}
}
}
log.info(folder.getAbsolutePath());
HashMap<String, Long> modifiedDates = new HashMap<String, Long>();
for (File f : folder.listFiles()) {
log.info(f.getAbsolutePath());
// TODO: better stripping of the file extension
String aiml = f.getName().replace(".aiml", "");
modifiedDates.put(aiml, f.lastModified());
}
log.info("AIMLIF FILES:");
folderaimlIF = new File(aimlIFPath);
if (!folderaimlIF.exists()) {
// TODO: throw an exception warn / log ?
log.info("aimlif directory missing,creating it. " + folderaimlIF.getAbsolutePath());
folderaimlIF.mkdirs();
return;
}
for (File f : folderaimlIF.listFiles()) {
log.info(f.getAbsolutePath());
// TODO: better stripping of the file extension
String aimlIF = f.getName().replace(".aiml.csv", "");
Long lastMod = modifiedDates.get(aimlIF);
if (lastMod != null) {
if (f.lastModified() < lastMod) {
// the AIMLIF file is newer than the AIML file.
// delete the AIMLIF file so ProgramAB recompiles it
// properly.
log.info("Deleteing AIMLIF file because the original AIML file was modified. {}", aimlIF);
f.delete();
// edit moz4r : we need to change the last modification date to aiml
// folder for recompilation
sleep(1000);
String fil = aimlPath + File.separator + "folder_updated";
File file = new File(fil);
file.delete();
try {
PrintWriter writer = new PrintWriter(fil, "UTF-8");
writer.println(lastMod.toString());
writer.close();
} catch (IOException e) {
// do something
}
}
}
}
}
private String createSessionPredicateFilename(String username, String botName) {
// TODO: sanitize the session label so it can be safely used as a filename
String predicatePath = getPath() + File.separator + "bots" + File.separator + botName + File.separator + "config";
// just in case the directory doesn't exist.. make it.
File predDir = new File(predicatePath);
if (!predDir.exists()) {
predDir.mkdirs();
}
predicatePath += File.separator + username + ".predicates.txt";
return predicatePath;
}
public int getMaxConversationDelay() {
return sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).maxConversationDelay;
}
public Response getResponse(String text) {
return getResponse(getCurrentUserName(), text);
}
/**
*
* @param text
* - the query string to the bot brain
* @param username
* - the user that is sending the query
* @param botName
* - the name of the bot you which to get the response from
* @return the response for a user from a bot given the input text.
*/
public Response getResponse(String username, String botName, String text) {
this.setCurrentBotName(botName);
return getResponse(username, text);
}
public Response getResponse(String username, String text) {
log.info("Get Response for : user {} bot {} : {}", username, getCurrentBotName(), text);
if (bot == null) {
String error = "ERROR: Core not loaded, please load core before chatting.";
error(error);
return new Response(username, error, null, new Date());
}
if (text.isEmpty()) {
return new Response(username, "", null, new Date());
}
String sessionKey = resolveSessionKey(username, getCurrentBotName());
if (!sessions.containsKey(sessionKey)) {
startSession(getPath(), username, getCurrentBotName());
}
ChatData chatData = sessions.get(sessionKey);
String res = getChat(username, getCurrentBotName()).multisentenceRespond(text);
// grab and update the time when this response came in.
chatData.lastResponseTime = new Date();
// Check the AIML response to see if there is OOB (out of band data)
// If so, publish that data independent of the text response.
List<OOBPayload> payloads = null;
if (chatData.processOOB) {
payloads = processOOB(res);
}
// OOB text should not be published as part of the response text.
Matcher matcher = oobPattern.matcher(res);
res = matcher.replaceAll("").trim();
Response response = new Response(username, res, payloads, chatData.lastResponseTime);
// Now that we've said something, lets create a timer task to wait for N
// seconds
// and if nothing has been said.. try say something else.
// TODO: trigger a task to respond with something again
// if the humans get bored
if (chatData.enableAutoConversation) {
// schedule one future reply. (always get the last word in..)
// int numExecutions = 1;
// TODO: we need a way for the task to just execute one time
// it'd be good to have access to the timer here, but it's transient
addTask("getResponse", chatData.maxConversationDelay, 0, "getResponse", username, text);
}
// EEK! clean up the API!
invoke("publishResponse", response);
invoke("publishResponseText", response);
invoke("publishText", response.msg);
info("to: %s - %s", username, res);
// if (log.isDebugEnabled()) {
// for (String key : sessions.get(session).predicates.keySet()) {
// log.debug(session + " " + key + " " +
// sessions.get(session).predicates.get(key));
// TODO: wire this in so the gui updates properly. ??
// broadcastState();
return response;
}
public String resolveSessionKey(String username, String botname) {
return username + "-" + botname;
}
public void repetition_count(int val) {
org.alicebot.ab.MagicNumbers.repetition_count = val;
}
public Chat getChat(String userName, String botName) {
String sessionKey = resolveSessionKey(userName, botName);
if (!sessions.containsKey(sessionKey)) {
error("%s session does not exist", sessionKey);
return null;
} else {
return sessions.get(sessionKey).chat;
}
}
public void removePredicate(String userName, String predicateName) {
removePredicate(userName, getCurrentBotName(), predicateName);
}
public void removePredicate(String userName, String botName, String predicateName) {
Predicates preds = getChat(userName, botName).predicates;
preds.remove(predicateName);
}
public void addToSet(String setName, String setValue) {
// add to the set for the bot.
AIMLSet updateSet = bot.setMap.get(setName);
setValue = setValue.toUpperCase().trim();
if (updateSet != null) {
updateSet.add(setValue);
// persist to disk.
updateSet.writeAIMLSet();
} else {
log.info("Unknown AIML set: {}. A new set will be created. ", setName);
// TODO: should we create a new set ? or just log this warning?
// The AIML Set doesn't exist. Lets create a new one
AIMLSet newSet = new AIMLSet(setName, bot);
newSet.add(setValue);
newSet.writeAIMLSet();
}
}
public void addToMap(String mapName, String mapKey, String mapValue) {
// add an entry to the map.
AIMLMap updateMap = bot.mapMap.get(mapName);
mapKey = mapKey.toUpperCase().trim();
if (updateMap != null) {
updateMap.put(mapKey, mapValue);
// persist to disk!
updateMap.writeAIMLMap();
} else {
log.info("Unknown AIML map: {}. A new MAP will be created. ", mapName);
// dynamically create new maps?!
AIMLMap newMap = new AIMLMap(mapName, bot);
newMap.put(mapKey, mapValue);
newMap.writeAIMLMap();
}
}
public void setPredicate(String username, String predicateName, String predicateValue) {
Predicates preds = getChat(username, getCurrentBotName()).predicates;
preds.put(predicateName, predicateValue);
}
public void unsetPredicate(String username, String predicateName) {
Predicates preds = getChat(username, getCurrentBotName()).predicates;
preds.remove(predicateName);
}
public String getPredicate(String username, String predicateName) {
Predicates preds = getChat(username, getCurrentBotName()).predicates;
return preds.get(predicateName);
}
/**
* Only respond if the last response was longer than delay ms ago
*
* @param session
* - current session/username
* @param text
* - text to get a response for
* @param delay
* - min amount of time that must have transpired since the last
* response.
* @return the response
*/
public Response getResponse(String session, String text, Long delay) {
ChatData chatData = sessions.get(session);
long delta = System.currentTimeMillis() - chatData.lastResponseTime.getTime();
if (delta > delay) {
return getResponse(session, text);
} else {
return null;
}
}
public boolean isEnableAutoConversation() {
return sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).enableAutoConversation;
}
public boolean isProcessOOB() {
return sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).processOOB;
}
/**
* Return a list of all patterns that the AIML Bot knows to match against.
*
* @param botName
* the bots name from which to return it's patterns.
* @return a list of all patterns loaded into the aiml brain
*/
public ArrayList<String> listPatterns(String botName) {
ArrayList<String> patterns = new ArrayList<String>();
for (Category c : bot.brain.getCategories()) {
patterns.add(c.getPattern());
}
return patterns;
}
/**
* Return the number of milliseconds since the last response was given -1 if a
* response has never been given.
*
* @return milliseconds
*/
public long millisecondsSinceLastResponse() {
ChatData chatData = sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName()));
if (chatData.lastResponseTime == null) {
return -1;
}
long delta = System.currentTimeMillis() - chatData.lastResponseTime.getTime();
return delta;
}
@Override
public void onText(String text) {
// What else should we do here? seems reasonable to just do this.
// this should actually call getResponse
// on input, get the proper response
// Response resp = getResponse(text);
getResponse(text);
// push that to the next end point.
// invoke("publishText", resp.msg);
}
private OOBPayload parseOOB(String oobPayload) {
// TODO: fix the damn double encoding issue.
// we have user entered text in the service/method
// and params values.
// grab the service
Pattern servicePattern = Pattern.compile("<service>(.*?)</service>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
Matcher serviceMatcher = servicePattern.matcher(oobPayload);
serviceMatcher.find();
String serviceName = serviceMatcher.group(1);
Pattern methodPattern = Pattern.compile("<method>(.*?)</method>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
Matcher methodMatcher = methodPattern.matcher(oobPayload);
methodMatcher.find();
String methodName = methodMatcher.group(1);
Pattern paramPattern = Pattern.compile("<param>(.*?)</param>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
Matcher paramMatcher = paramPattern.matcher(oobPayload);
ArrayList<String> params = new ArrayList<String>();
while (paramMatcher.find()) {
// We found some OOB text.
// assume only one OOB in the text?
String param = paramMatcher.group(1);
params.add(param);
}
OOBPayload payload = new OOBPayload(serviceName, methodName, params);
// log.info(payload.toString());
return payload;
// JAXB stuff blows up because the response from program ab is already
// xml decoded!
// JAXBContext jaxbContext;
// try {
// jaxbContext = JAXBContext.newInstance(OOBPayload.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
// log.info("OOB PAYLOAD :" + oobPayload);
// Reader r = new StringReader(oobPayload);
// OOBPayload oobMsg = (OOBPayload) jaxbUnmarshaller.unmarshal(r);
// return oobMsg;
// } catch (JAXBException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// log.info("OOB tag found, but it's not an MRL tag. {}", oobPayload);
// return null;
}
private List<OOBPayload> processOOB(String text) {
// Find any oob tags
ArrayList<OOBPayload> payloads = new ArrayList<OOBPayload>();
Matcher oobMatcher = oobPattern.matcher(text);
while (oobMatcher.find()) {
// We found some OOB text.
// assume only one OOB in the text?
String oobPayload = oobMatcher.group(0);
Matcher mrlMatcher = mrlPattern.matcher(oobPayload);
while (mrlMatcher.find()) {
String mrlPayload = mrlMatcher.group(0);
OOBPayload payload = parseOOB(mrlPayload);
payloads.add(payload);
// TODO: maybe we dont' want this?
// Notifiy endpoints
invoke("publishOOBText", mrlPayload);
// grab service and invoke method.
ServiceInterface s = Runtime.getService(payload.getServiceName());
if (s == null) {
log.warn("Service name in OOB/MRL tag unknown. {}", mrlPayload);
return null;
}
// TODO: should you be able to be synchronous for this
// execution?
Object result = null;
if (payload.getParams() != null) {
result = s.invoke(payload.getMethodName(), payload.getParams().toArray());
} else {
result = s.invoke(payload.getMethodName());
}
log.info("OOB PROCESSING RESULT: {}", result);
}
}
if (payloads.size() > 0) {
return payloads;
} else {
return null;
}
}
/*
* If a response comes back that has an OOB Message, publish that separately
*/
public String publishOOBText(String oobText) {
return oobText;
}
/*
* publishing method of the pub sub pair - with addResponseListener allowing
* subscriptions pub/sub routines have the following pattern
*
* publishing routine -> publishX - must be invoked to provide data to
* subscribers subscription routine -> addXListener - simply adds a Service
* listener to the notify framework any service which subscribes must
* implement -> onX(data) - this is where the data will be sent (the
* call-back)
*
*/
public Response publishResponse(Response response) {
return response;
}
/*
* Test only publishing point - for simple consumers
*/
public String publishResponseText(Response response) {
return response.msg;
}
@Override
public String publishText(String text) {
// clean up whitespaces & cariage return
text = text.replaceAll("\\n", " ");
text = text.replaceAll("\\r", " ");
text = text.replaceAll("\\s{2,}", " ");
return text;
}
public void reloadSession(String session, String botName) {
reloadSession(getPath(), session, botName);
}
public void reloadSession(String path, String username, String botname) {
reloadSession(path, username, botname, false);
}
public void reloadSession(String path, String username, String botname, Boolean killAimlIf) {
loading = true;
broadcastState();
// kill the bot
writeAndQuit(killAimlIf);
// kill the session
String sessionKey = resolveSessionKey(username, botname);
if (sessions.containsKey(sessionKey)) {
// TODO: will garbage collection clean up the bot now ?
// Or are there other handles to it?
sessions.remove(sessionKey);
}
bot = null;
// TODO: we should make sure we keep the same path as before.
startSession(path, username, getCurrentBotName());
}
/**
* Persist the predicates for all known sessions in the robot.
*
*/
public void savePredicates() throws IOException {
for (String session : sessions.keySet()) {
// TODO: better parsing of this.
String[] parts = session.split("-");
String username = parts[0];
String botname = session.substring(username.length() + 1);
String sessionPredicateFilename = createSessionPredicateFilename(username, botname);
File sessionPredFile = new File(sessionPredicateFilename);
Chat chat = getChat(username, botname);
// overwrite the original file , this should always be a full set.
log.info("Writing predicate file for session {}", session);
FileWriter predWriter = new FileWriter(sessionPredFile, false);
for (String predicate : chat.predicates.keySet()) {
String value = chat.predicates.get(predicate);
predWriter.write(predicate + ":" + value + "\n");
}
predWriter.close();
}
log.info("Done saving predicates.");
}
public void setEnableAutoConversation(boolean enableAutoConversation) {
sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).enableAutoConversation = enableAutoConversation;
}
public void setMaxConversationDelay(int maxConversationDelay) {
sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).maxConversationDelay = maxConversationDelay;
}
public void setProcessOOB(boolean processOOB) {
sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).processOOB = processOOB;
}
public void startSession() {
startSession(null);
}
public void startSession(String session) {
startSession(session, getCurrentBotName());
}
public Set<String> getSessionNames() {
return sessions.keySet();
}
/**
* Load the AIML 2.0 Bot config and start a chat session. This must be called
* after the service is created.
*
* @param session
* - The new session name
* @param botName
* - The name of the bot to load. (example: alice2)
*/
public void startSession(String session, String botName) {
startSession(getPath(), session, botName);
}
public void startSession(String path, String userName, String botName) {
loading = true;
this.setPath(path);
info("starting Chat Session path:%s username:%s botname:%s", path, userName, botName);
this.setCurrentBotName(botName);
this.setCurrentUserName(userName);
broadcastState();
// Session is between a user and a bot. key is compound.
String sessionKey = resolveSessionKey(userName, botName);
if (sessions.containsKey(sessionKey)) {
warn("session %s already created", sessionKey);
return;
}
if (!getSessionNames().isEmpty()) {
wasCleanyShutdowned = "ok";
}
cleanOutOfDateAimlIFFiles(botName);
wasCleanyShutdowned = "nok";
// TODO: manage the bots in a collective pool/hash map.
if (bot == null) {
bot = new Bot(botName, path);
} else if (!botName.equalsIgnoreCase(bot.name)) {
bot = new Bot(botName, path);
}
Chat chat = new Chat(bot);
// for (Category c : bot.brain.getCategories()) {
// log.info(c.getPattern());
// String resp = chat.multisentenceRespond("hello");
// load session specific predicates, these override the default ones.
String sessionPredicateFilename = createSessionPredicateFilename(userName, botName);
chat.predicates.getPredicateDefaults(sessionPredicateFilename);
sessions.put(resolveSessionKey(getCurrentUserName(), getCurrentBotName()), new ChatData(chat));
// lets test if the robot knows the name of the person in the session
String name = chat.predicates.get("name").trim();
// TODO: this implies that the default value for "name" is default
// "Friend"
if (name == null || "Friend".equalsIgnoreCase(name) || "unknown".equalsIgnoreCase(name)) {
// TODO: find another interface that's simpler to use for this
// create a string that represents the predicates file
String inputPredicateStream = "name:" + userName;
// load those predicates
chat.predicates.getPredicateDefaultsFromInputStream(FileIO.toInputStream(inputPredicateStream));
}
// this.currentBotName = botName;
// String userName = chat.predicates.get("name");
log.info("Started session for bot name:{} , username:{}", botName, userName);
// TODO: to make sure if the start session is updated, that the button
// updates in the gui ?
this.save();
loading = false;
broadcastState();
}
public void setPath(String path) {
this.path = path;
}
public void setCurrentBotName(String currentBotName) {
this.currentBotName = currentBotName;
}
/**
* setUsername will check if username correspond to current session If no, a
* new session is started
*
* @param username
* - The new username
* @return boolean - True if username changed
* @throws IOException
*/
public boolean setUsername(String username) {
if (username.isEmpty()) {
log.error("chatbot username is empty");
return false;
}
if (getSessionNames().isEmpty()) {
log.info(username + " first session started");
startSession(username);
return false;
}
try {
savePredicates();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (username.equalsIgnoreCase(this.getCurrentUserName())) {
log.info(username + " already connected");
return false;
}
if (!username.equalsIgnoreCase(this.getCurrentUserName())) {
startSession(this.getPath(), username, this.getCurrentBotName());
setPredicate(username, "name", username);
setPredicate("default", "lastUsername", username);
// robot name is stored inside default.predicates, not inside system.prop
setPredicate(username, "botname", getPredicate("default", "botname"));
try {
savePredicates();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info(username + " session started");
return true;
}
return false;
}
public void writeAIML() {
bot.writeAIMLFiles();
}
public void writeAIMLIF() {
bot.writeAIMLIFFiles();
}
public void writeAndQuit() {
writeAndQuit(false);
}
/**
* writeAndQuit will clean shutdown BOT so next stratup is sync & faaaast
*
* @param killAimlIf
* - Delete aimlif and restart bot from aiml - Useful to push aiml
* modifications in realtime - Without restart whole script
*/
public void writeAndQuit(Boolean killAimlIf) {
if (bot == null) {
log.info("no bot - don't need to write and quit");
return;
}
try {
savePredicates();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String fil = bot.aimlif_path + File.separator + "folder_updated";
if (!killAimlIf) {
bot.writeQuit();
wasCleanyShutdowned = "ok";
// edit moz4r : we need to change the last modification date to aimlif
// folder because at this time all is compilated.
// so programAb don't need to load AIML at startup
sleep(1000);
File folder = new File(bot.aimlif_path);
for (File f : folder.listFiles()) {
f.setLastModified(System.currentTimeMillis());
}
} else {
fil = bot.aiml_path + File.separator + "folder_updated";
}
File file = new File(fil);
file.delete();
try {
PrintWriter writer = new PrintWriter(fil, "UTF-8");
writer.println("");
writer.close();
} catch (IOException e) {
log.error("PrintWriter error");
}
}
public void attach(Attachable attachable) {
if (attachable instanceof TextPublisher) {
addTextPublisher((TextPublisher) attachable);
} else if (attachable instanceof TextListener){
addListener("publishText", attachable.getName(), "onText");
} else {
log.error("don't know how to attach a {}", attachable.getName());
}
}
@Override
public void stopService() {
try {
savePredicates();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writeAndQuit();
super.stopService();
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(ProgramAB.class.getCanonicalName());
meta.addDescription("AIML 2.0 Reference interpreter based on Program AB");
meta.addCategory("intelligence");
meta.addDependency("program-ab", "program-ab-data", "0.0.4.1", "zip");
meta.addDependency("program-ab", "program-ab-kw", "0.0.4.1");
meta.addDependency("org.json", "json", "20090211");
return meta;
}
public static void main(String s[]) throws IOException {
try {
LoggingFactory.init("INFO");
Runtime.start("gui", "SwingGui");
// Runtime.start("webgui", "WebGui");
ProgramAB brain = (ProgramAB) Runtime.start("brain", "ProgramAB");
// brain.startSession("default", "alice2");
WebkitSpeechRecognition ear = (WebkitSpeechRecognition) Runtime.start("ear", "WebkitSpeechRecognition");
MarySpeech mouth = (MarySpeech) Runtime.start("mouth", "MarySpeech");
// mouth.attach(ear);
ear.attach(mouth);
// ear.addMouth(mouth);
brain.attach(ear);
mouth.attach(brain);
brain.startSession("default", "Alice2");
// ear.startListening();
// FIXME - make this work
// brain.attach(mouth);
// ear.attach(mouth);
// FIXME !!! - make this work
// ear.attach(mouth);
// brain.addTextPublisher(service);
// ear.attach(brain);
/*
* log.info(brain.getResponse("hi there").toString());
* log.info(brain.getResponse("").toString());
* log.info(brain.getResponse("test").toString());
* log.info(brain.getResponse("").toString()); brain.setUsername("test");
*/
brain.savePredicates();
} catch (Exception e) {
log.error("main threw", e);
}
}
public String getPath() {
return path;
}
public String getCurrentUserName() {
return currentUserName;
}
public void setCurrentUserName(String currentUserName) {
this.currentUserName = currentUserName;
}
public String getCurrentBotName() {
return currentBotName;
}
} |
package org.owasp.dependencycheck;
import java.util.EnumMap;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.analyzer.AnalysisException;
import org.owasp.dependencycheck.analyzer.AnalysisPhase;
import org.owasp.dependencycheck.analyzer.Analyzer;
import org.owasp.dependencycheck.analyzer.AnalyzerService;
import org.owasp.dependencycheck.data.CachedWebDataSource;
import org.owasp.dependencycheck.data.UpdateException;
import org.owasp.dependencycheck.data.UpdateService;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.FileUtils;
/**
* Scans files, directories, etc. for Dependencies. Analyzers are loaded and
* used to process the files found by the scan, if a file is encountered and an
* Analyzer is associated with the file type then the file is turned into a
* dependency.
*
* @author Jeremy Long (jeremy.long@gmail.com)
*/
public class Engine {
/**
* The list of dependencies.
*/
private List<Dependency> dependencies = new ArrayList<Dependency>();
/**
* A Map of analyzers grouped by Analysis phase.
*/
private EnumMap<AnalysisPhase, List<Analyzer>> analyzers =
new EnumMap<AnalysisPhase, List<Analyzer>>(AnalysisPhase.class);
/**
* A set of extensions supported by the analyzers.
*/
private Set<String> extensions = new HashSet<String>();
/**
* Creates a new Engine.
*/
public Engine() {
doUpdates();
loadAnalyzers();
}
/**
* Creates a new Engine.
*
* @param autoUpdate indicates whether or not data should be updated from
* the Internet.
*/
public Engine(boolean autoUpdate) {
if (autoUpdate) {
doUpdates();
}
loadAnalyzers();
}
/**
* Loads the analyzers specified in the configuration file (or system
* properties).
*/
private void loadAnalyzers() {
for (AnalysisPhase phase : AnalysisPhase.values()) {
analyzers.put(phase, new ArrayList<Analyzer>());
}
final AnalyzerService service = AnalyzerService.getInstance();
final Iterator<Analyzer> iterator = service.getAnalyzers();
while (iterator.hasNext()) {
final Analyzer a = iterator.next();
analyzers.get(a.getAnalysisPhase()).add(a);
if (a.getSupportedExtensions() != null) {
extensions.addAll(a.getSupportedExtensions());
}
}
}
/**
* Get the List of the analyzers for a specific phase of analysis.
*
* @param phase the phase to get the configured analyzers.
* @return the analyzers loaded
*/
public List<Analyzer> getAnalyzers(AnalysisPhase phase) {
return analyzers.get(phase);
}
/**
* Get the dependencies identified.
*
* @return the dependencies identified
*/
public List<Dependency> getDependencies() {
return dependencies;
}
/**
* Scans a given file or directory. If a directory is specified, it will be
* scanned recursively. Any dependencies identified are added to the
* dependency collection.
*
* @param path the path to a file or directory to be analyzed.
*/
public void scan(String path) {
final File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
scanDirectory(file);
} else {
scanFile(file);
}
}
}
/**
* Recursively scans files and directories. Any dependencies identified are
* added to the dependency collection.
*
* @param dir the directory to scan.
*/
protected void scanDirectory(File dir) {
final File[] files = dir.listFiles();
for (File f : files) {
if (f.isDirectory()) {
scanDirectory(f);
} else {
scanFile(f);
}
}
}
/**
* Scans a specified file. If a dependency is identified it is added to the
* dependency collection.
*
* @param file The file to scan.
*/
protected void scanFile(File file) {
if (!file.isFile()) {
final String msg = String.format("Path passed to scanFile(File) is not a file: %s.", file.toString());
Logger.getLogger(Engine.class.getName()).log(Level.WARNING, msg);
}
final String fileName = file.getName();
final String extension = FileUtils.getFileExtension(fileName);
if (extension != null) {
if (extensions.contains(extension)) {
final Dependency dependency = new Dependency(file);
dependencies.add(dependency);
}
} else {
final String msg = String.format("No file extension found on file '%s'. The file was not analyzed.",
file.toString());
Logger.getLogger(Engine.class.getName()).log(Level.FINEST, msg);
}
}
/**
* Runs the analyzers against all of the dependencies.
*/
public void analyzeDependencies() {
//phase one initialize
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
for (Analyzer a : analyzerList) {
try {
a.initialize();
} catch (Exception ex) {
Logger.getLogger(Engine.class.getName()).log(Level.SEVERE,
"Exception occurred initializing " + a.getName() + ".", ex);
try {
a.close();
} catch (Exception ex1) {
Logger.getLogger(Engine.class.getName()).log(Level.FINER, null, ex1);
}
}
}
}
// analysis phases
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
for (Analyzer a : analyzerList) {
//need to create a copy of the collection because some of the
// analyzers may modify it. This prevents ConcurrentModificationExceptions.
final Set<Dependency> dependencySet = new HashSet<Dependency>();
dependencySet.addAll(dependencies);
for (Dependency d : dependencySet) {
if (a.supportsExtension(d.getFileExtension())) {
try {
a.analyze(d, this);
} catch (AnalysisException ex) {
d.addAnalysisException(ex);
}
}
}
}
}
//close/cleanup
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
for (Analyzer a : analyzerList) {
try {
a.close();
} catch (Exception ex) {
Logger.getLogger(Engine.class.getName()).log(Level.WARNING, null, ex);
}
}
}
}
/**
* Cycles through the cached web data sources and calls update on all of them.
*/
private void doUpdates() {
final UpdateService service = UpdateService.getInstance();
final Iterator<CachedWebDataSource> iterator = service.getDataSources();
while (iterator.hasNext()) {
final CachedWebDataSource source = iterator.next();
try {
source.update();
} catch (UpdateException ex) {
Logger.getLogger(Engine.class.getName()).log(Level.WARNING,
"Unable to update {0}", source.getClass().getName());
Logger.getLogger(Engine.class.getName()).log(Level.INFO,
String.format("Unable to update details for {0}",
source.getClass().getName()), ex);
}
}
}
/**
* Returns a full list of all of the analyzers. This is useful
* for reporting which analyzers where used.
* @return a list of Analyzers
*/
public List<Analyzer> getAnalyzers() {
final List<Analyzer> ret = new ArrayList<Analyzer>();
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
ret.addAll(analyzerList);
}
return ret;
}
} |
package org.rspspin.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.query.Syntax;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.NodeIterator;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDF;
import org.rspspin.lang.rspql.ParserRSPQL;
import org.topbraid.spin.arq.ARQ2SPIN;
import org.topbraid.spin.arq.ARQFactory;
import org.topbraid.spin.model.Command;
import org.topbraid.spin.model.Module;
import org.topbraid.spin.model.Template;
import org.topbraid.spin.system.SPINArgumentChecker;
import org.topbraid.spin.system.SPINModuleRegistry;
import org.topbraid.spin.vocabulary.ARG;
import org.topbraid.spin.vocabulary.SP;
import org.topbraid.spin.vocabulary.SPIN;
import org.topbraid.spin.vocabulary.SPL;
public class TemplateManager {
private static TemplateManager instance = null;
private Model model;
private Syntax syntax = ParserRSPQL.syntax;
private ARQ2SPIN arq2spin;
/**
* Initialize
*/
private TemplateManager() {
ParserRSPQL.register();
SPINModuleRegistry.get().init();
ARQFactory.setSyntax(syntax);
model = Utils.createDefaultModel();
arq2spin = new ARQ2SPIN(model, true);
// Install the argument checker
SPINArgumentChecker.set(new SPINArgumentChecker() {
@Override
public void handleErrors(Module module, QuerySolutionMap bindings, List<String> errors)
throws ArgumentConstraintException {
throw new ArgumentConstraintException(errors);
}
});
}
/**
* Get singleton.
*/
public static TemplateManager get() {
if (instance == null) {
instance = new TemplateManager();
}
return instance;
}
/**
* Set template manager model.
*
* @param model
*/
public void setModel(Model model) {
this.model = model;
}
/**
* Get template manager model.
*
* @return
*/
public Model getModel() {
return model;
}
/**
* Create template
*
* @param templateUri
* @param queryString
* @return
*/
public Template createTemplate(String templateUri, String queryString) {
if (templateUri == null) {
System.err.println("Template identifier must be a valid URI");
return null;
}
Query arqQuery = QueryFactory.create(queryString, ParserRSPQL.syntax);
// Get template type
Resource templateType;
if (arqQuery.isSelectType()) {
templateType = SPIN.SelectTemplate;
} else if (arqQuery.isAskType()) {
templateType = SPIN.AskTemplate;
} else if (arqQuery.isConstructType()) {
templateType = SPIN.ConstructTemplate;
} else {
System.err.println("Invalid query type for template: " + arqQuery.getQueryType());
return null;
}
// Use a blank node identifier for the query
org.topbraid.spin.model.Query spinQuery = arq2spin.createQuery(arqQuery, null);
Template template = createResource(templateUri, templateType).as(Template.class);
template.addProperty(SPIN.body, spinQuery);
return template;
}
/**
* Create a resource.
*
* @param uri
* @return
*/
public Resource createResource(String uri) {
return model.createResource(uri);
}
/**
* Create a typed resource.
*
* @param type
* @return
*/
public Resource createResource(Resource type) {
return model.createResource(type);
}
/**
* Create a typed resource.
*
* @param uri
* @return
*/
public Resource createResource(String uri, Resource type) {
return model.createResource(uri, type);
}
/**
* Create a property.
*
* @param uri
* @return
*/
public Property createProperty(String uri) {
return model.createProperty(uri);
}
/**
* Create an argument constraint.
*
* @param varName
* Name of variable
* @param valueType
* Value type of variable binding
* @param defaultValue
* Default value for variable (or null)
* @param optional
* States whether the argument is required
* @return argument
* @throws ArgumentConstraintException
*/
public Resource addArgumentConstraint(String varName, RDFNode valueType, RDFNode defaultValue, boolean optional,
Template template) throws ArgumentConstraintException {
// Check if argument is variable in template
QueryExecution qe = QueryExecutionFactory.create(String.format(
"" + "PREFIX sp: <http://spinrdf.org/sp#> " + "ASK WHERE { <%s> (!<:>)*/sp:varName \"%s\" }",
template.getURI(), varName), template.getModel());
if (!qe.execAsk()) {
template.getModel().write(System.out, "TTL");
List<String> errors = new ArrayList<String>();
errors.add("Argument " + varName + " is not a variable in the query");
throw new ArgumentConstraintException(errors);
}
// Create argument
Resource arg = createResource(SPL.Argument);
arg.addProperty(SPL.predicate, createResource(ARG.NS + varName));
if (valueType != null)
arg.addProperty(SPL.valueType, valueType);
if (defaultValue != null)
arg.addProperty(SPL.defaultValue, defaultValue);
arg.addProperty(SPL.optional, model.createTypedLiteral(optional));
// Add constraint to template
template.addProperty(SPIN.constraint, arg);
return arg;
}
/**
* Get a query from a template.
*
* @param template
* @return query
*/
public Query getQuery(Template template) {
Query arq;
if (template.getBody() != null) {
Command spinQuery = template.getBody();
arq = ARQFactory.get().createQuery((org.topbraid.spin.model.Query) spinQuery);
} else {
arq = ARQFactory.get().createQuery(template.getProperty(SP.text).getObject().toString());
}
return arq;
}
/**
* Get template from the current model based on a URI identifier.
* @return
*/
public Template getTemplate(String uri) {
// Find template type
NodeIterator iter = model.listObjectsOfProperty(model.createResource(uri), RDF.type);
if (iter.hasNext()) {
Resource r = iter.next().asResource();
if (r.equals(SPIN.SelectTemplate)) {
return model.createResource(uri, SPIN.SelectTemplate).as(Template.class);
} else if (r.equals(SPIN.ConstructTemplate)) {
return model.createResource(uri, SPIN.ConstructTemplate).as(Template.class);
} else if (r.equals(SPIN.AskTemplate)) {
return model.createResource(uri, SPIN.AskTemplate).as(Template.class);
} else {
return model.createResource(uri, SPIN.Template).as(Template.class);
}
}
return null;
}
/**
* Get a query from a template and a set of bindings.
*
* @param template
* @param bindings
* @return query
*/
public Query getQuery(Template template, QuerySolutionMap bindings) {
Query arq;
if (template.getBody() != null) {
Command spinQuery = template.getBody();
arq = ARQFactory.get().createQuery((org.topbraid.spin.model.Query) spinQuery);
} else {
arq = ARQFactory.get().createQuery(template.getProperty(SP.text).getObject().toString());
}
// Parameterized
ParameterizedSparqlString pss = new ParameterizedSparqlString(arq.toString(), bindings);
return pss.asQuery(syntax);
}
public void check(Template template, QuerySolutionMap bindings) throws ArgumentConstraintException {
SPINArgumentChecker.get().check(template, bindings);
}
/**
* Set the syntax used by the template manager.
*
* @param syntax
*/
public void setSyntax(Syntax syntax) {
this.syntax = syntax;
ARQFactory.setSyntax(syntax);
}
/**
* Get the syntax used by the template manager.
*
* @param syntax
* @return
*/
public Syntax getSyntax() {
return syntax;
}
} |
package org.scy.common.ds.query;
import org.apache.commons.lang3.StringUtils;
import org.scy.common.ds.PageInfo;
import org.scy.common.utils.ArrayUtilsEx;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unused")
public class Selector {
private PageInfo pageInfo;
private List<Filter> filters = new ArrayList<Filter>();
public static Selector build(PageInfo pageInfo) {
Selector selector = new Selector();
selector.setPageInfo(pageInfo);
return selector;
}
public void setPageInfo(PageInfo pageInfo) {
this.pageInfo = pageInfo;
}
public Selector addFilter(Filter filter) {
if (filter != null)
this.filters.add(filter);
return this;
}
public Selector addFilter(String field, Object value) {
if (StringUtils.isNotBlank(field))
this.filters.add(new Filter(field, value));
return this;
}
public Selector addFilter(String field, Object value, Oper oper) {
if (StringUtils.isNotBlank(field))
this.filters.add(new Filter(field, value, oper));
return this;
}
public Selector addFilterNotNull(String field, Object value) {
if (value != null) {
this.addFilter(field, value);
}
return this;
}
public Selector addFilterNotNull(String field, Object value, Oper oper) {
if (value != null) {
this.addFilter(field, value, oper);
}
return this;
}
public Selector addFilterNotEmpty(String field, Object value) {
if (value != null && StringUtils.isNotEmpty(value.toString())) {
this.addFilter(field, value);
}
return this;
}
public Selector addFilterNotEmpty(String field, Object value, Oper oper) {
if (value != null && StringUtils.isNotEmpty(value.toString())) {
this.addFilter(field, value, oper);
}
return this;
}
public Selector addFilterNotBlank(String field, Object value) {
if (value != null && StringUtils.isNotBlank(value.toString())) {
this.addFilter(field, value);
}
return this;
}
public Selector addFilterNotBlank(String field, Object value, Oper oper) {
if (value != null && StringUtils.isNotBlank(value.toString())) {
this.addFilter(field, value, oper);
}
return this;
}
public String getWhere() {
List<String> wheres = new ArrayList<String>();
for (Filter filter: filters) {
wheres.add(filter.toString());
}
if (wheres.size() > 0)
return ArrayUtilsEx.join(wheres, " and ");
return "";
}
public String getWhereMore() {
List<String> wheres = new ArrayList<String>();
for (Filter filter: filters) {
wheres.add(filter.toString());
}
if (wheres.size() > 0)
return ArrayUtilsEx.join(wheres, " and ");
return "";
}
public String getOrderBy() {
return "";
}
public String getGroupBy() {
return "";
}
public String getOrder() {
return "";
}
public String getOrderMore() {
return "";
}
public String getGroup() {
return "";
}
public String getGroupMore() {
return "";
}
public String getLimit() {
if (pageInfo != null) {
return "limit " + pageInfo.getPage() + "," + pageInfo.getSize();
}
return "";
}
} |
package org.spout.downpour;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class DownpourCache {
private boolean offlineMode = false;
private long maxAge = 1000 * 60 * 60 * 24 * 7; // Keep for one week
private File cacheDb = null;
public static final String CACHE_FILE_SUFFIX = ".downpurcache";
public static final DefaultURLConnector DEFAULT_CONNECTOR = new DefaultURLConnector();
/**
* Creates a new cache db
*
* @param db the directory to put the caches in. The files will have a .downpourcache suffix
*
* You should call {@link cleanup()} after instancing the DB.
*/
public DownpourCache(File db) {
this.cacheDb = db;
if (db.isFile()) {
throw new IllegalStateException("DB needs to be a directory");
} else if (!db.exists()) {
db.mkdirs();
}
}
/**
* Deletes all caches older than {@link getMaxAge()}
* <br/>Does not do anything in offline mode
*/
public void cleanup() {
if (!isOfflineMode()) {
long currentTime = System.currentTimeMillis();
File[] contents = cacheDb.listFiles();
for (File file:contents) {
if (file.isFile() && file.getAbsolutePath().endsWith(CACHE_FILE_SUFFIX)) {
long lastModified = file.lastModified();
if (currentTime - getMaxAge() > lastModified) {
file.delete();
}
}
}
}
}
/**
* Sets the maximum age a cached URL will survive in this cache
*
* @param maxAge the maximum age of a cache file
*
* Note that if in offline mode, no cache file will be deleted so longer offline trips are possible
*/
public void setMaxAge(long maxAge) {
this.maxAge = maxAge;
}
/**
* Gets the maximum age a cached URL will survive in this cache
* @return the maximum age of a cache file
*/
public long getMaxAge() {
return maxAge;
}
/**
* Sets whether this cache is offline, i.e. read from cache files instead of looking for data online
* @param offlineMode if this cache is in offline mode
*/
public void setOfflineMode(boolean offlineMode) {
this.offlineMode = offlineMode;
}
/**
* Gets if this cache is in offline mode
* @return if this cache is in offline mode
*/
public boolean isOfflineMode() {
return offlineMode;
}
/**
* If online, connects to the host and opens an InputStream that reads the url.
* If offline, reads from the cache file.
* @param url the URL to connect to
* @param connector the URLConnector to open an InputStream from an URL {@link URLConnector}
* @return an InputStream that reads from the URL or the cached File
* @throws NoCacheException if offline and the cache file is missing
* @throws IOException if an IOException occurs during connecting or reading the cache file
*/
public InputStream get(URL url, URLConnector connector) throws NoCacheException, IOException {
File cacheFile = getCachedFile(url);
if (isOfflineMode()) {
if (cacheFile.exists()) {
return new FileInputStream(cacheFile);
} else {
throw new NoCacheException();
}
} else {
InputStream readFrom = connector.openURL(url);
OutputStream writeTo = new FileOutputStream(cacheFile);
return new CachingInputStream(readFrom, writeTo);
}
}
/**
* If online, connects to the host and opens an InputStream that reads the url.
* If offline, reads from the cache file.
* @param url the URL to connect to
* @return an InputStream that reads from the URL or the cached File
* @throws NoCacheException if offline and the cache file is missing
* @throws IOException if an IOException occurs during connecting or reading the cache file
*/
public InputStream get(URL url) throws NoCacheException, IOException {
return get(url, DEFAULT_CONNECTOR);
}
private File getCachedFile(URL url) {
return new File(cacheDb, getCacheKey(url) + CACHE_FILE_SUFFIX);
}
private String getCacheKey(URL url) {
// Sanitize string
String path = url.toString();
path = path.replaceAll("[^a-zA-Z]", "-");
return (new StringBuilder()).append(path).append('-').append(url.toString()).toString();
}
} |
package practice;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ConnectedGraphTraversal {
static Set<Vertex> createGraph(Stream<String> lines) {
// the lines are of the form: 1 2,3,4 i.e. vertex comma separated neighbors
Set<Vertex> vertices = new HashSet<>();
lines.forEach(line -> {
String[] parts = line.split("\\s");
int vid = Integer.parseInt(parts[0]);
String[] ns = parts[1].split(","); // could be more accommodating
List<Integer> neighbors = Arrays.stream(ns).mapToInt(Integer::parseInt).collect(ArrayList<Integer>::new,
ArrayList::add,
ArrayList::addAll);
Vertex v = new Vertex(vid, neighbors);
vertices.add(v);
// System.out.println(v);
});
return vertices;
}
static void traverse(Set<Vertex> graph) {
int sum = graph.stream().mapToInt(v -> v.neighbors.size()).sum();
Vertex from = getRandomStartingVertex(graph);
System.out.println("start: " + from);
Vertex to = null;
int i = 0;
while (i < sum) {
// to = graph.stream().filter(v -> v.id == from.leave()).findFirst().get();
Integer tmp = from.leave();
for (Vertex v : graph) {
if (v.id == tmp) {
to = v;
break;
}
}
System.out.println(from.id + " -> " + to.id);
to.arrive(from);
from = to;
i += 1;
}
}
private static Vertex getRandomStartingVertex(Set<Vertex> graph) {
Random r = new Random();
int n = r.nextInt(graph.size());
Iterator<Vertex> iter = graph.iterator();
int i = 0;
while (iter.hasNext()) {
Vertex d = iter.next();
if (i == n) {
// iter.remove();
return d;
}
i += 1;
}
throw new AssertionError("An item should have been found");
}
public static void main(String[] args) {
StringReader sr = new StringReader("1 3,4,6\n2 3,5,6\n3 1,2\n4 1,5,6\n5 2,4,6\n6 1,2,4,5");
// StringReader sr = new StringReader("1 2,3,5\n2 1,4,5\n3 1,4\n4 2,3\n5 1,2\n");
// StringReader sr = new StringReader("1 2,3,4\n2 1,3,4\n3 1,2,4\n4 1,2,3\n");
Set<Vertex> g = createGraph(new BufferedReader(sr).lines());
traverse(g);
}
private static final class Vertex {
final int id;
private final LinkedHashSet<Integer> arrivedFrom = new LinkedHashSet<>();
private final LinkedHashSet<Integer> leftTo = new LinkedHashSet<>();
private final HashSet<Integer> neighbors = new HashSet<>();
private Vertex firstArrivingFrom = null;
Vertex(int id, List<Integer> neighbors) {
this.id = id;
this.neighbors.addAll(neighbors.stream().collect(Collectors.toList()));
}
public void arrive(Vertex from) {
if (arrivedFrom.isEmpty()) {
firstArrivingFrom = from;
}
arrivedFrom.add(from.id);
}
public Integer leave() {
// returns the ID of the vertex to which we go
if (leftTo.size() == neighbors.size() - 1) { // last choice
assert firstArrivingFrom != null;
int id = firstArrivingFrom.id;
leftTo.add(id);
return id;
}
for (Integer neighbor : neighbors) {
if (!leftTo.contains(neighbor)) {
if (firstArrivingFrom != null && firstArrivingFrom.id == neighbor)
continue; // we skip the special vertex from which the first arrival occurred here
leftTo.add(neighbor);
return neighbor;
}
}
throw new AssertionError("all done!");
}
@Override
public String toString() {
return "vertex: " + this.id + ", neighbors: " + this.neighbors;
}
}
} |
package redis.clients.jedis;
import java.net.URI;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.exceptions.InvalidURIException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.util.JedisURIHelper;
/**
* PoolableObjectFactory custom impl.
*/
public class JedisFactory implements PooledObjectFactory<Jedis> {
private static final Logger logger = LoggerFactory.getLogger(JedisFactory.class);
private final JedisSocketFactory jedisSocketFactory;
private final JedisClientConfig clientConfig;
protected JedisFactory(final String host, final int port, final int connectionTimeout,
final int soTimeout, final String password, final int database, final String clientName) {
this(host, port, connectionTimeout, soTimeout, password, database, clientName, false, null, null, null);
}
protected JedisFactory(final String host, final int port, final int connectionTimeout,
final int soTimeout, final String user, final String password, final int database, final String clientName) {
this(host, port, connectionTimeout, soTimeout, 0, user, password, database, clientName);
}
protected JedisFactory(final String host, final int port, final int connectionTimeout, final int soTimeout,
final int infiniteSoTimeout, final String user, final String password, final int database, final String clientName) {
this(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName, false, null, null, null);
}
/**
* {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later.
*/
protected JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout,
final String user, final String password, final int database, final String clientName) {
this(connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName, false, null, null, null);
}
protected JedisFactory(final String host, final int port, final int connectionTimeout,
final int soTimeout, final String password, final int database, final String clientName,
final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(host, port, connectionTimeout, soTimeout, null, password, database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier);
}
protected JedisFactory(final String host, final int port, final int connectionTimeout,
final int soTimeout, final String user, final String password, final int database, final String clientName,
final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(host, port, connectionTimeout, soTimeout, 0, user, password, database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier);
}
protected JedisFactory(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) {
this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig);
this.jedisSocketFactory = new DefaultJedisSocketFactory(hostAndPort, this.clientConfig);
}
protected JedisFactory(final String host, final int port, final int connectionTimeout, final int soTimeout,
final int infiniteSoTimeout, final String user, final String password, final int database,
final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this.clientConfig = DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout)
.socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout).user(user)
.password(password).database(database).clientName(clientName)
.ssl(ssl).sslSocketFactory(sslSocketFactory)
.sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build();
this.jedisSocketFactory = new DefaultJedisSocketFactory(new HostAndPort(host, port), this.clientConfig);
}
protected JedisFactory(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) {
this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig);
this.jedisSocketFactory = jedisSocketFactory;
}
/**
* {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later.
*/
protected JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout,
final String user, final String password, final int database, final String clientName, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout)
.socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout).user(user)
.password(password).database(database).clientName(clientName)
.ssl(ssl).sslSocketFactory(sslSocketFactory)
.sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build());
}
/**
* {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later.
*/
protected JedisFactory(final JedisClientConfig clientConfig) {
this.clientConfig = clientConfig;
this.jedisSocketFactory = new DefaultJedisSocketFactory(clientConfig);
}
protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout,
final String clientName) {
this(uri, connectionTimeout, soTimeout, clientName, null, null, null);
}
protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout,
final String clientName, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(uri, connectionTimeout, soTimeout, 0, clientName, sslSocketFactory, sslParameters, hostnameVerifier);
}
protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout,
final int infiniteSoTimeout, final String clientName, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
if (!JedisURIHelper.isValid(uri)) {
throw new InvalidURIException(String.format(
"Cannot open Redis connection due invalid URI. %s", uri.toString()));
}
this.clientConfig = DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout)
.socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout)
.user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri))
.database(JedisURIHelper.getDBIndex(uri)).clientName(clientName)
.ssl(JedisURIHelper.isRedisSSLScheme(uri)).sslSocketFactory(sslSocketFactory)
.sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build();
this.jedisSocketFactory = new DefaultJedisSocketFactory(new HostAndPort(uri.getHost(), uri.getPort()), this.clientConfig);
}
public void setHostAndPort(final HostAndPort hostAndPort) {
jedisSocketFactory.updateHostAndPort(hostAndPort);
}
public void setPassword(final String password) {
this.clientConfig.updatePassword(password);
}
@Override
public void activateObject(PooledObject<Jedis> pooledJedis) throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.getDB() != clientConfig.getDatabase()) {
jedis.select(clientConfig.getDatabase());
}
}
@Override
public void destroyObject(PooledObject<Jedis> pooledJedis) throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.isConnected()) {
try {
// need a proper test, probably with mock
if (!jedis.isBroken()) {
jedis.quit();
}
} catch (Exception e) {
logger.warn("Error while QUIT", e);
}
try {
jedis.close();
} catch (Exception e) {
logger.warn("Error while close", e);
}
}
}
@Override
public PooledObject<Jedis> makeObject() throws Exception {
Jedis jedis = null;
try {
jedis = new Jedis(jedisSocketFactory, clientConfig);
jedis.connect();
return new DefaultPooledObject<>(jedis);
} catch (JedisException je) {
if (jedis != null) {
try {
jedis.quit();
} catch (Exception e) {
logger.warn("Error while QUIT", e);
}
try {
jedis.close();
} catch (Exception e) {
logger.warn("Error while close", e);
}
}
throw je;
}
}
@Override
public void passivateObject(PooledObject<Jedis> pooledJedis) throws Exception {
// TODO maybe should select db 0? Not sure right now.
}
@Override
public boolean validateObject(PooledObject<Jedis> pooledJedis) {
final BinaryJedis jedis = pooledJedis.getObject();
try {
String host = jedisSocketFactory.getHost();
int port = jedisSocketFactory.getPort();
String connectionHost = jedis.getClient().getHost();
int connectionPort = jedis.getClient().getPort();
return host.equals(connectionHost)
&& port == connectionPort && jedis.isConnected()
&& jedis.ping().equals("PONG");
} catch (final Exception e) {
logger.error("Error while validating pooled Jedis object.", e);
return false;
}
}
} |
package seedu.address.model;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import java.util.logging.Logger;
import javafx.collections.transformation.FilteredList;
import seedu.address.commons.core.ComponentManager;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.events.model.TaskBookChangedEvent;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.commons.events.ui.UpdateListCountEvent;
import seedu.address.commons.util.StringUtil;
import seedu.address.model.task.Datetime;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Status;
import seedu.address.model.task.Task;
import seedu.address.model.task.UniqueTaskList;
import seedu.address.model.task.UniqueTaskList.TaskNotFoundException;
import seedu.address.model.undo.UndoList;
import seedu.address.model.undo.UndoTask;
/**
* Represents the in-memory model of the task book data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final TaskBook taskBook;
private final FilteredList<Task> filteredDatedTasks;
private final FilteredList<Task> filteredUndatedTasks;
private UndoList undoableTasks;
/**
* Initializes a ModelManager with the given TaskBook
* TaskBook and its variables should not be null
*/
public ModelManager(TaskBook src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with task book: " + src + " and user prefs " + userPrefs);
taskBook = new TaskBook(src);
filteredDatedTasks = new FilteredList<>(taskBook.getDatedTasks());
filteredUndatedTasks = new FilteredList<>(taskBook.getUndatedTasks());
undoableTasks = new UndoList();
}
public ModelManager() {
this(new TaskBook(), new UserPrefs());
}
public ModelManager(ReadOnlyTaskBook initialData, UserPrefs userPrefs) {
taskBook = new TaskBook(initialData);
filteredDatedTasks = new FilteredList<>(taskBook.getDatedTasks());
filteredUndatedTasks = new FilteredList<>(taskBook.getUndatedTasks());
undoableTasks = new UndoList();
}
//@@author A0139024M
/**
* Check the start time and date time of all tasks in application
*/
public void checkStatus(){
checkDatedTaskStatus(taskBook.getUniqueDatedTaskList(), getCurrentTime(), DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm"));
checkUndatedTaskStatus(taskBook.getUniqueUndatedTaskList());
}
/**
* Get the current time of the local machine
* @return
*/
private LocalDateTime getCurrentTime() {
return LocalDateTime.now();
}
/**
* Update the status of all Undated/Floating Tasks in application
* @param floating
*/
private void checkUndatedTaskStatus(UniqueTaskList floating) {
for (Task undatedTarget : floating) {
if (undatedTarget.getStatus().status == Status.State.OVERDUE || undatedTarget.getStatus().status == Status.State.OVERDUE ) {
try {
taskBook.resetFloatingTaskStatus(undatedTarget);
}catch (TaskNotFoundException e){}
}
}
}
/**
* Update the status of all Dated Tasks in application
* @param tasks
* @param currentTime
* @param formatter
*/
private void checkDatedTaskStatus(UniqueTaskList tasks, LocalDateTime currentTime, DateTimeFormatter formatter) {
for (Task target : tasks) {
assert target.getDatetime().getStart() != null;
//Deadline
if (target.getDatetime().getEnd() == null) {
updateDeadlineStatus(currentTime, formatter, target);
}
//Event
else if (target.getDatetime().getEnd() != null) {
updateEventStatus(currentTime, formatter, target);
}
}
}
/**
* Updated the status of all Event Tasks in application
* @param currentTime
* @param formatter
* @param target
*/
private void updateEventStatus(LocalDateTime currentTime, DateTimeFormatter formatter, Task target) {
String endDateTime = getEventEndTimeInStringFormat(target);
LocalDateTime dateTime = LocalDateTime.parse(endDateTime,formatter);
if (dateTime.isBefore(currentTime) && target.getStatus().status != Status.State.DONE) {
try {
taskBook.setExpire(target);
}catch (TaskNotFoundException e) {
throw new AssertionError("Impossible!");
}
}
else if (dateTime.isAfter(currentTime) && (target.getStatus().status == Status.State.EXPIRE || target.getStatus().status == Status.State.OVERDUE)) {
try {
taskBook.postponeTask(target);
}catch (TaskNotFoundException e) {
throw new AssertionError("Impossible!");
}
}
}
/**
* Get the End Time of Event in String Format
* @param target
* @return
*/
private String getEventEndTimeInStringFormat(Task target) {
return target.getDatetime().toString().substring(21);
}
/**
* Updated the status of all Deadline tasks in application
* @param currentTime
* @param formatter
* @param target
*/
private void updateDeadlineStatus(LocalDateTime currentTime, DateTimeFormatter formatter, Task target) {
LocalDateTime dateTime = LocalDateTime.parse(target.getDatetime().toString(), formatter);
if (dateTime.isBefore(currentTime) && target.getStatus().status != Status.State.DONE) {
try {
taskBook.setTaskOverdue(target);
}catch (TaskNotFoundException e) {
throw new AssertionError("Impossible!");
}
}
else if (dateTime.isAfter(currentTime) && (target.getStatus().status == Status.State.OVERDUE || target.getStatus().status == Status.State.EXPIRE)) {
try {
taskBook.postponeTask(target);
}catch (TaskNotFoundException e) {
throw new AssertionError("Impossible!");
}
}
}
//@@author
@Override
public void resetData(ReadOnlyTaskBook newData) {
taskBook.resetData(newData);
undoableTasks = new UndoList();
indicateTaskBookChanged();
raise(new UpdateListCountEvent(this));
}
@Override
public ReadOnlyTaskBook getTaskBook() {
return taskBook;
}
/** Raises an event to indicate the model has changed */
private void indicateTaskBookChanged() {
checkStatus();
raise(new TaskBookChangedEvent(taskBook));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException {
taskBook.removeTask(target);
indicateTaskBookChanged();
}
//@@author A0143884W
@Override
public synchronized boolean addTask(Task target) {
boolean duplicate = taskBook.addTask(target);
updateFilteredListToShowAll();
indicateTaskBookChanged();
scrollToAddedTask(target);
return duplicate;
}
// after task is added, scroll to it in the UndatedListPanel || DatedListPanel
private void scrollToAddedTask(Task target) {
int [] result = indexOfAddedTask(target);
raise (new JumpToListRequestEvent(result[0], result[1]));
}
private int[] indexOfAddedTask(Task target) {
int datedTaskIndex = filteredDatedTasks.indexOf(target);
int undatedTaskIndex = filteredUndatedTasks.indexOf(target);
int [] result = new int[2];
// indexOf returns -1 if task not found in the list
if (datedTaskIndex == -1){
result[0] = undatedTaskIndex;
result[1] = JumpToListRequestEvent.UNDATED_LIST;
}
else if (undatedTaskIndex == -1){
result[0] = datedTaskIndex;
result[1] = JumpToListRequestEvent.DATED_LIST;
}
return result;
}
//@@author
//@@author A0139145E
@Override
public synchronized void completeTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException {
taskBook.completeTask(target);
updateFilteredListToShowAll();
indicateTaskBookChanged();
}
@Override
public synchronized void uncompleteTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException {
taskBook.uncompleteTask(target);
updateFilteredListToShowAll();
indicateTaskBookChanged();
}
@Override
public synchronized UndoTask undoTask() {
return undoableTasks.removeFromFront();
}
@Override
public synchronized void overdueTask(ReadOnlyTask target) throws TaskNotFoundException {
taskBook.setTaskOverdue(target);
updateFilteredListToShowAll();
indicateTaskBookChanged();
}
@Override
public void addUndo(String command, ReadOnlyTask postData) {
undoableTasks.addToFront(command, postData, null);
}
@Override
public void addUndo(String command, ReadOnlyTask postData, ReadOnlyTask preData) {
undoableTasks.addToFront(command, postData, preData);
}
//@@author
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredDatedTaskList() {
return new UnmodifiableObservableList<>(filteredDatedTasks);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredUndatedTaskList() {
return new UnmodifiableObservableList<>(filteredUndatedTasks);
}
//@@author A0139145E
@Override
public void updateFilteredListToShowAll() {
updateFilteredTaskListByStatus("NONE", "OVERDUE", "EXPIRE");
}
//@@author
// called by ViewCommand
@Override
public void updateFilteredTaskListByDate(Date date){
filteredDatedTasks.setPredicate((new PredicateExpression(new DateQualifier(date)))::satisfies);
raise(new UpdateListCountEvent(this));
}
// called by FindCommand
@Override
public void updateFilteredTaskListByKeywords(Set<String> keywords){
updateFilteredTaskList(new PredicateExpression(new TaskQualifier(keywords)));
}
// called by ListCommand
@Override
public void updateFilteredTaskListByStatus(String... keyword){
ArrayList<String> listOfKeywords = new ArrayList<>();
for (String word : keyword){
listOfKeywords.add(word);
}
updateFilteredTaskList(new PredicateExpression(new StatusQualifier(listOfKeywords)));
}
private void updateFilteredTaskList(Expression expression) {
filteredDatedTasks.setPredicate(expression::satisfies);
filteredUndatedTasks.setPredicate(expression::satisfies);
raise(new UpdateListCountEvent(this));
}
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
//@@author A0139528W
private class TaskQualifier implements Qualifier {
private Set<String> taskKeyWords;
TaskQualifier(Set<String> taskKeyWords) {
this.taskKeyWords = taskKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return (taskKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getName().fullName, keyword))
.findAny()
.isPresent()
|| taskKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getDatetime().toString(), keyword))
.findAny()
.isPresent()
|| taskKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getDescription().value, keyword))
.findAny()
.isPresent()
|| taskKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getTags().toString(), keyword))
.findAny()
.isPresent());
}
@Override
public String toString() {
return "task=" + String.join(", ", taskKeyWords);
}
}
//@@author
//@@author A0139145E
private class StatusQualifier implements Qualifier {
private ArrayList<Status> statusList;
StatusQualifier(ArrayList<String> stateKeyWords) {
this.statusList = new ArrayList<Status>();
for (String word : stateKeyWords){
statusList.add(new Status(word));
}
}
@Override
public boolean run(ReadOnlyTask task) {
for (Status key : statusList) {
if (task.getStatus().equals(key)) {
return true;
}
}
return false;
}
@Override
public String toString() {
return "status=" + statusList.toString();
}
}
//@@author
//@@author A0143884W
private class DateQualifier implements Qualifier {
private Date inputDate;
DateQualifier(Date date) {
this.inputDate = date;
}
@Override
public boolean run(ReadOnlyTask task) {
Datetime taskDate = task.getDatetime();
Date startDate = taskDate.getStart();
Date endDate = taskDate.getEnd();
// check deadline and event start date
if (sameDate(startDate)){
return true;
}
// check event end date but make sure deadlines are excluded
else if (endDate != null && sameDate(endDate)){
return true;
}
// check event dates between start date and end date but make sure deadlines are excluded
else if (endDate != null && inputDate.after(startDate) && inputDate.before(endDate)){
return true;
}
else {
return false;
}
}
@Override
public String toString() {
return "date=" + inputDate.toString();
}
private boolean sameDate(Date other){
return inputDate.getDate() == other.getDate() && inputDate.getMonth() == other.getMonth()
&& inputDate.getYear() == other.getYear();
}
}
//@@author
} |
package seedu.address.model;
import javafx.collections.transformation.FilteredList;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.util.StringUtil;
import seedu.address.commons.events.model.AddressBookChangedEvent;
import seedu.address.commons.core.ComponentManager;
import seedu.address.model.person.Task;
import seedu.address.model.person.ReadOnlyTask;
import seedu.address.model.person.UniquePersonList;
import seedu.address.model.person.UniquePersonList.PersonNotFoundException;
import java.util.Set;
import java.util.logging.Logger;
/**
* Represents the in-memory model of the address book data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final AddressBook addressBook;
private final FilteredList<Task> filteredPersons;
private final FilteredList<Task> filteredUndatedTasks;
/**
* Initializes a ModelManager with the given AddressBook
* AddressBook and its variables should not be null
*/
public ModelManager(AddressBook src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with address book: " + src + " and user prefs " + userPrefs);
addressBook = new AddressBook(src);
filteredPersons = new FilteredList<>(addressBook.getPersons());
filteredUndatedTasks = new FilteredList<>(addressBook.getUndatedTasks());
}
public ModelManager() {
this(new AddressBook(), new UserPrefs());
}
public ModelManager(ReadOnlyAddressBook initialData, UserPrefs userPrefs) {
addressBook = new AddressBook(initialData);
filteredPersons = new FilteredList<>(addressBook.getPersons());
filteredUndatedTasks = new FilteredList<>(addressBook.getUndatedTasks());
}
@Override
public void resetData(ReadOnlyAddressBook newData) {
addressBook.resetData(newData);
indicateAddressBookChanged();
}
@Override
public ReadOnlyAddressBook getAddressBook() {
return addressBook;
}
/** Raises an event to indicate the model has changed */
private void indicateAddressBookChanged() {
raise(new AddressBookChangedEvent(addressBook));
}
@Override
public synchronized void deletePerson(ReadOnlyTask target) throws UniquePersonList.PersonNotFoundException {
addressBook.removePerson(target);
indicateAddressBookChanged();
}
@Override
public synchronized void addPerson(Task person) throws UniquePersonList.DuplicatePersonException {
addressBook.addPerson(person);
updateFilteredListToShowAll();
indicateAddressBookChanged();
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredPersonList() {
return new UnmodifiableObservableList<>(filteredPersons);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredUndatedTaskList() {
return new UnmodifiableObservableList<>(filteredUndatedTasks);
}
@Override
public void updateFilteredListToShowAll() {
filteredPersons.setPredicate(null);
filteredUndatedTasks.setPredicate(null);
}
@Override
public void updateFilteredPersonList(Set<String> keywords){
updateFilteredPersonList(new PredicateExpression(new NameQualifier(keywords)));
}
private void updateFilteredPersonList(Expression expression) {
filteredPersons.setPredicate(expression::satisfies);
filteredUndatedTasks.setPredicate(expression::satisfies);
}
interface Expression {
boolean satisfies(ReadOnlyTask person);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask person) {
return qualifier.run(person);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return (nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getName().fullName, keyword))
.findAny()
.isPresent()
|| nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getTime().value, keyword))
.findAny()
.isPresent()
|| nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getDate().value, keyword))
.findAny()
.isPresent()
|| nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getDescription().value, keyword))
.findAny()
.isPresent()
|| nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getTags().toString(), keyword))
.findAny()
.isPresent());
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
} |
package seedu.address.model;
import java.util.Set;
import java.util.logging.Logger;
import javafx.collections.transformation.FilteredList;
import seedu.address.commons.core.ComponentManager;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.events.model.ToDoAppChangedEvent;
import seedu.address.commons.util.CollectionUtil;
import seedu.address.commons.util.StringUtil;
import seedu.address.model.person.ReadOnlyTask;
import seedu.address.model.person.Task;
import seedu.address.model.person.UniqueTaskList;
import seedu.address.model.person.UniqueTaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the address book data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final ToDoApp toDoApp;
private final FilteredList<ReadOnlyTask> filteredTasks;
/**
* Initializes a ModelManager with the given toDoApp and userPrefs.
*/
public ModelManager(ReadOnlyToDoApp toDoApp, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(toDoApp, userPrefs);
logger.fine("Initializing with ToDoApp: " + toDoApp + " and user prefs " + userPrefs);
this.toDoApp = new ToDoApp(toDoApp);
filteredTasks = new FilteredList<>(this.toDoApp.getTaskList());
}
public ModelManager() {
this(new ToDoApp(), new UserPrefs());
}
@Override
public void resetData(ReadOnlyToDoApp newData) {
toDoApp.resetData(newData);
indicateToDoAppChanged();
}
@Override
public ReadOnlyToDoApp getToDoApp() {
return toDoApp;
}
/** Raises an event to indicate the model has changed */
private void indicateToDoAppChanged() {
raise(new ToDoAppChangedEvent(toDoApp));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
toDoApp.removeTask(target);
indicateToDoAppChanged();
}
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
toDoApp.addTask(task);
updateFilteredListToShowAll();
indicateToDoAppChanged();
}
//@@author A0114395E
@Override
public synchronized void addTask(Task task, int idx) throws UniqueTaskList.DuplicateTaskException {
toDoApp.addTask(task, idx);
updateFilteredListToShowAll();
indicateToDoAppChanged();
}
//@@author
@Override
public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask)
throws UniqueTaskList.DuplicateTaskException {
assert editedTask != null;
int toDoAppIndex = filteredTasks.getSourceIndex(filteredTaskListIndex);
toDoApp.updateTask(toDoAppIndex, editedTask);
indicateToDoAppChanged();
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(null);
}
@Override
public void updateFilteredTaskList(Set<String> keywords) {
updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getName().fullName, keyword))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
} |
package tigase.xmpp.impl;
import tigase.db.NonAuthUserRepository;
import tigase.db.TigaseDBException;
import tigase.server.Packet;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import tigase.xmpp.NoConnectionIdException;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPException;
import tigase.xmpp.XMPPPacketFilterIfc;
import tigase.xmpp.XMPPPreprocessorIfc;
import tigase.xmpp.XMPPProcessor;
import tigase.xmpp.XMPPProcessorIfc;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.impl.roster.RosterAbstract;
import tigase.xmpp.impl.roster.RosterFactory;
import static tigase.xmpp.impl.Privacy.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Describe class JabberIqPrivacy here.
*
*
* Created: Mon Oct 9 18:18:11 2006
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class JabberIqPrivacy extends XMPPProcessor
implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc {
/**
* Private logger for class instances.
*/
private static Logger log = Logger.getLogger(JabberIqPrivacy.class.getName());
private static final String XMLNS = "jabber:iq:privacy";
private static final String ID = XMLNS;
private static final String[] ELEMENTS = { "query" };
private static final String[] XMLNSS = { XMLNS };
private static final Element[] DISCO_FEATURES = {
new Element("feature", new String[] { "var" }, new String[] { XMLNS }) };
private static final String PRIVACY_INIT_KEY = "privacy-init";
private static final String LIST_EL_NAME = "list";
private static final String DEFAULT_EL_NAME = "default";
private static final String ACTIVE_EL_NAME = "active";
private static final String PRESENCE_IN_EL_NAME = "presence-in";
private static final String PRESENCE_OUT_EL_NAME = "presence-out";
private static final String PRESENCE_EL_NAME = "presence";
private static RosterAbstract roster_util = RosterFactory.getRosterImplementation(true);
private static final Comparator<Element> compar = new Comparator<Element>() {
@Override
public int compare(Element el1, Element el2) {
String or1 = el1.getAttribute(ORDER);
String or2 = el2.getAttribute(ORDER);
return or1.compareTo(or2);
}
};
private enum ITEM_ACTION { allow, deny }
private enum ITEM_SUBSCRIPTIONS {
both, to, from, none
}
private enum ITEM_TYPE {
jid, group, subscription, all
}
/**
* Method description
*
*
* @param packet
* @param session
* @param repo
* @param results
*/
@Override
public void filter(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results) {
if ((session == null) ||!session.isAuthorized() || (results == null) || (results.size() == 0)) {
return;
}
for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) {
Packet res = it.next();
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Checking outbound packet: {0}", res);
}
// Always allow presence unavailable to go, privacy lists packets and
// all other which are allowed by privacy rules
if ((res.getType() == StanzaType.unavailable) || res.isXMLNS("/iq/query", XMLNS)
|| allowed(res, session)) {
continue;
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Packet not allowed to go, removing: {0}", res);
}
it.remove();
}
}
/**
* Method description
*
*
* @return
*/
@Override
public String id() {
return ID;
}
/**
* <code>preProcess</code> method checks only incoming stanzas
* so it doesn't check for presence-out at all.
*
* @param packet a <code>Packet</code> value
* @param session a <code>XMPPResourceConnection</code> value
* @param repo a <code>NonAuthUserRepository</code> value
* @param results
* @param settings
* @return a <code>boolean</code> value
*/
@Override
public boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) {
if ((session == null) ||!session.isAuthorized() || packet.isXMLNS("/iq/query", XMLNS)) {
return false;
} // end of if (session == null)
return !allowed(packet, session);
}
/**
* Method description
*
*
* @param packet
* @param session
* @param repo
* @param results
* @param settings
*
* @throws XMPPException
*/
@Override
public void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings)
throws XMPPException {
if (session == null) {
return;
} // end of if (session == null)
try {
StanzaType type = packet.getType();
switch (type) {
case get :
processGetRequest(packet, session, results);
break;
case set :
processSetRequest(packet, session, results);
break;
case result :
case error :
// Ignore
break;
default :
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"Request type is incorrect", false));
break;
} // end of switch (type)
} catch (NotAuthorizedException e) {
log.log(Level.WARNING,
"Received privacy request but user session is not authorized yet: {0}", packet);
results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You must authorize session first.", true));
} catch (TigaseDBException e) {
log.log(Level.WARNING, "Database proble, please contact admin: {0}", e);
results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet,
"Database access problem, please contact administrator.", true));
}
}
/**
* Method description
*
*
* @param session
*
* @return
*/
@Override
public Element[] supDiscoFeatures(final XMPPResourceConnection session) {
return DISCO_FEATURES;
}
/**
* Method description
*
*
* @return
*/
@Override
public String[] supElements() {
return ELEMENTS;
}
/**
* Method description
*
*
* @return
*/
@Override
public String[] supNamespaces() {
return XMLNSS;
}
private boolean allowed(Packet packet, XMPPResourceConnection session) {
try {
// If this is a preprocessing phase, always allow all packets to
// make it possible for the client to communicate with the server.
if (session.getConnectionId().equals(packet.getPacketFrom())) {
return true;
}
Element list = Privacy.getActiveList(session);
if ((list == null) && (session.getSessionData(PRIVACY_INIT_KEY) == null)) {
// First mark the session as privacy lists loaded for it, this way if there
// is an exception thrown during database call for this user we won't
// call it again for the same user.
session.putSessionData(PRIVACY_INIT_KEY, "");
String lName = Privacy.getDefaultList(session);
if (lName != null) {
Privacy.setActiveList(session, lName);
list = Privacy.getActiveList(session);
} // end of if (lName != null)
} // end of if (lName == null)
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Active privcy list: {0}", list);
}
if (list != null) {
List<Element> items = list.getChildren();
if (items != null) {
Collections.sort(items, compar);
for (Element item : items) {
boolean type_matched = false;
boolean elem_matched = false;
ITEM_TYPE type = ITEM_TYPE.all;
if (item.getAttribute(TYPE) != null) {
type = ITEM_TYPE.valueOf(item.getAttribute(TYPE));
} // end of if (item.getAttribute(TYPE) != null)
String value = item.getAttribute(VALUE);
BareJID sessionUserId = session.getBareJID();
JID jid = packet.getStanzaFrom();
boolean packetIn = true;
if ((jid == null) || sessionUserId.equals(jid.getBareJID())) {
jid = packet.getStanzaTo();
packetIn = false;
}
if (jid != null) {
switch (type) {
case jid :
type_matched = jid.toString().contains(value);
break;
case group :
String[] groups = roster_util.getBuddyGroups(session, jid);
if (groups != null) {
for (String group : groups) {
if (type_matched = group.equals(value)) {
break;
} // end of if (group.equals(value))
} // end of for (String group: groups)
}
break;
case subscription :
ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value);
switch (subscr) {
case to :
type_matched = roster_util.isSubscribedTo(session, jid);
break;
case from :
type_matched = roster_util.isSubscribedFrom(session, jid);
break;
case none :
type_matched = ( !roster_util.isSubscribedFrom(session, jid)
&&!roster_util.isSubscribedTo(session, jid));
break;
case both :
type_matched = (roster_util.isSubscribedFrom(session, jid)
&& roster_util.isSubscribedTo(session, jid));
break;
default :
break;
} // end of switch (subscr)
break;
case all :
default :
type_matched = true;
break;
} // end of switch (type)
} else {
if (type == ITEM_TYPE.all) {
type_matched = true;
}
} // end of if (from != null) else
if ( !type_matched) {
continue;
} // end of if (!type_matched)
List<Element> elems = item.getChildren();
if ((elems == null) || (elems.size() == 0)) {
elem_matched = true;
} else {
for (Element elem : elems) {
if (
(packet.getElemName() == PRESENCE_EL_NAME)
&& ((packetIn && (elem.getName() == PRESENCE_IN_EL_NAME))
|| ( !packetIn && (elem.getName() == PRESENCE_OUT_EL_NAME)))
&& ((packet.getType() == null) || (packet.getType() == StanzaType.unavailable))
)
{
elem_matched = true;
break;
}
if (packetIn && (elem.getName() == packet.getElemName())) {
elem_matched = true;
break;
} // end of if (elem.getName().equals(packet.getElemName()))
} // end of for (Element elem: elems)
} // end of else
if ( !elem_matched) {
break;
} // end of if (!elem_matched)
ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttribute(ACTION));
switch (action) {
case allow :
return true;
case deny :
return false;
default :
break;
} // end of switch (action)
} // end of for (Element item: items)
} // end of if (items != null)
} // end of if (lName != null)
} catch (NoConnectionIdException e) {
// Always allow, this is server dummy session
} catch (NotAuthorizedException e) {
// results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
// "You must authorize session first.", true));
} catch (TigaseDBException e) {
log.log(Level.WARNING, "Database problem, please notify the admin. {0}", e);
}
return true;
}
private void processGetRequest(final Packet packet, final XMPPResourceConnection session,
final Queue<Packet> results)
throws NotAuthorizedException, XMPPException, TigaseDBException {
List<Element> children = packet.getElemChildren("/iq/query");
if ((children == null) || (children.size() == 0)) {
String[] lists = Privacy.getLists(session);
if (lists != null) {
StringBuilder sblists = new StringBuilder(100);
for (String list : lists) {
sblists.append("<list name=\"").append(list).append("\"/>");
}
String list = Privacy.getDefaultList(session);
if (list != null) {
sblists.append("<default name=\"").append(list).append("\"/>");
} // end of if (defList != null)
list = Privacy.getActiveListName(session);
if (list != null) {
sblists.append("<active name=\"").append(list).append("\"/>");
} // end of if (defList != null)
results.offer(packet.okResult(sblists.toString(), 1));
} else {
results.offer(packet.okResult((String) null, 1));
} // end of if (buddies != null) else
} else {
if (children.size() > 1) {
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"You can retrieve only one list at a time.", true));
} else {
Element eList = Privacy.getList(session, children.get(0).getAttribute("name"));
if (eList != null) {
results.offer(packet.okResult(eList, 1));
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"Requested list not found.", true));
} // end of if (eList != null) else
} // end of else
} // end of else
}
private void processSetRequest(final Packet packet, final XMPPResourceConnection session,
final Queue<Packet> results)
throws NotAuthorizedException, XMPPException, TigaseDBException {
List<Element> children = packet.getElemChildren("/iq/query");
if ((children != null) && (children.size() == 1)) {
Element child = children.get(0);
if (child.getName() == LIST_EL_NAME) {
// Broken privacy implementation sends list without name set
// instead of sending BAD_REQUEST error I can just assign
// 'default' name here.
String name = child.getAttribute(NAME);
if ((name == null) || (name.length() == 0)) {
child.setAttribute(NAME, "default");
} // end of if (name == null || name.length() == 0)
Privacy.addList(session, child);
results.offer(packet.okResult((String) null, 0));
} // end of if (child.getName().equals("list))
if (child.getName() == DEFAULT_EL_NAME) {
Privacy.setDefaultList(session, child);
results.offer(packet.okResult((String) null, 0));
} // end of if (child.getName().equals("list))
if (child.getName() == ACTIVE_EL_NAME) {
// User selects a different active list
String listName = child.getAttribute(NAME);
Element list = Privacy.getList(session, listName);
if ((listName != null) && (list == null)) {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"Selected list not found on the server", true));
} else {
// This is either declining of active list use or setting a new active list
Privacy.setActiveList(session, child.getAttribute(NAME));
results.offer(packet.okResult((String) null, 0));
}
} // end of if (child.getName().equals("list))
} else {
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"Only 1 element is allowed in privacy set request.", true));
} // end of else
}
} // JabberIqPrivacy
//~ Formatted in Sun Code Convention |
package org.prevayler.demos.demo2;
import org.prevayler.Prevayler;
import org.prevayler.PrevaylerFactory;
import org.prevayler.demos.demo2.business.Bank;
public class MainReplica {
public static void main(String[] args) throws Exception {
out( "This demo shows how your application can be replicated"
+ "\nwithout changing ONE SINGLE LINE OF CODE in the"
+ "\nbusiness classes or GUI. This enables query load-"
+ "\nbalancing and system fault-tolerance.\n\n"
);
String serverURI;
if (args.length == 1) {
serverURI = args[0];
} else {
out( "Usage: java MainReplica <Server IP Address>"
+ "\nExample: java MainReplica 10.42.10.5"
+ "\n\nBefore that, though, you must run: java MainReplicaServer"
+ "\non this machine or any other in your network, if you haven't"
+ "\nalready done so.\n"
+ "\nTrying to find server on localhost..."
);
serverURI = "localhost";
}
PrevaylerFactory factory = new PrevaylerFactory();
factory.configurePrevalentSystem(new Bank());
factory.configurePrevalenceDirectory("demo2Replica");
factory.configureReplicationClient(serverURI, PrevaylerFactory.DEFAULT_REPLICATION_PORT);
Prevayler prevayler = factory.create();
Main.startSnapshots(prevayler);
}
private static void out(String message) {
System.out.println(message);
}
} |
package sgdk.rescomp.resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import sgdk.rescomp.Resource;
import sgdk.rescomp.tool.Util;
import sgdk.rescomp.type.Basics.Compression;
import sgdk.rescomp.type.Basics.PackedData;
import sgdk.tool.ArrayUtil;
public class Bin extends Resource
{
public final byte[] data;
public final int align;
public final Compression wantedCompression;
public PackedData packedData;
public Compression doneCompression;
public boolean far;
final int hc;
public Bin(String id, byte[] data, int align, int sizeAlign, int fill, Compression compression, boolean far)
{
super(id);
if (sizeAlign > 0)
this.data = Util.sizeAlign(data, sizeAlign, (byte) fill);
else
this.data = data;
this.align = align;
wantedCompression = compression;
packedData = null;
doneCompression = Compression.NONE;
this.far = far;
// compute hash code
hc = Arrays.hashCode(data) ^ (align << 16) ^ wantedCompression.hashCode();
}
public Bin(String id, byte[] data, int align, int sizeAlign, int fill, Compression compression)
{
this(id, data, align, sizeAlign, fill, compression, true);
}
public Bin(String id, byte[] data, int align, int sizeAlign, int fill)
{
this(id, data, align, sizeAlign, fill, Compression.NONE);
}
public Bin(String id, byte[] data, int align, Compression compression)
{
this(id, data, align, 0, 0, compression);
}
public Bin(String id, byte[] data, Compression compression)
{
this(id, data, 2, 0, 0, compression);
}
public Bin(String id, short[] data, Compression compression, boolean far)
{
this(id, ArrayUtil.shortToByte(data), 2, 0, 0, compression, far);
}
public Bin(String id, short[] data, Compression compression)
{
this(id, ArrayUtil.shortToByte(data), 2, 0, 0, compression, true);
}
public Bin(String id, int[] data, Compression compression)
{
this(id, ArrayUtil.intToByte(data), 2, 0, 0, compression);
}
@Override
public int internalHashCode()
{
return hc;
}
@Override
public boolean internalEquals(Object obj)
{
if (obj instanceof Bin)
{
final Bin bin = (Bin) obj;
return (align == bin.align) && (wantedCompression == bin.wantedCompression)
&& Arrays.equals(data, bin.data);
}
return false;
}
@Override
public int shallowSize()
{
return (packedData != null) ? packedData.data.length : data.length;
}
@Override
public int totalSize()
{
return shallowSize();
}
@Override
public void out(ByteArrayOutputStream outB, StringBuilder outS, StringBuilder outH) throws IOException
{
// do 'outB' align *before* doing compression (as LZ4W compression can use previous data block)
Util.align(outB, align);
// pack data first if needed
packedData = Util.pack(data, wantedCompression, outB);
doneCompression = packedData.compression;
final int baseSize = data.length;
final int packedSize = packedData.data.length;
// data was compressed ?
if (packedSize < baseSize)
{
System.out.print("'" + id + "' ");
switch (packedData.compression)
{
case APLIB:
System.out.print("packed with APLIB, ");
break;
case LZ4W:
System.out.print("packed with LZ4W, ");
break;
default:
break;
}
System.out.println("size = " + packedSize + " (" + Math.round((packedSize * 100f) / baseSize)
+ "% - origin size = " + baseSize + ")");
}
// couldn't compress
else if (wantedCompression != Compression.NONE)
System.out.println("'" + id + "' couldn't be compressed");
// output binary data (data alignment was done before)
Util.outB(outB, packedData.data);
// declare
Util.declArray(outS, outH, "u8", id, packedData.data.length, align, global);
// output data (compression information is stored in 'parent' resource)
Util.outS(outS, packedData.data, 1);
outS.append("\n");
}
} |
package net.sf.cglib;
import java.io.*;
import java.lang.reflect.*;
import java.security.PrivilegedAction;
import java.util.*;
import org.apache.bcel.generic.*;
/**
* Abstract base class for code generators
* @author baliuka
*/
public abstract class CodeGenerator implements Constants {
protected static final String CONSTRUCTOR_NAME = "<init>";
protected static final String SOURCE_FILE = "<generated>";
protected static final String FIND_CLASS = "CGLIB$findClass";
protected static final String STATIC_NAME = "<clinit>";
protected static final Method EQUALS_METHOD;
private static final String PRIVATE_PREFIX = "PRIVATE_";
private static final Map primitiveMethods = new HashMap();
private static final Map primitiveToWrapper = new HashMap();
private static final Method forName;
private static final Method getMessage;
private static String debugLocation;
private static final Class[] TYPES_DEFINE_CLASS = {
String.class, byte[].class, int.class, int.class
};
private final ClassGen cg;
private final InstructionList il = new InstructionList();
private final ConstantPoolGen cp;
private final ClassLoader loader;
private MethodGen mg;
private Class returnType;
private Class superclass;
private Map branches;
private Map labels;
private int nextPrivateLabel;
private int nextPrivateLocal;
private Map locals = new HashMap();
private Map localTypes = new HashMap();
private int nextLocal;
private boolean inMethod;
private LinkedList handlerStack = new LinkedList();
private LinkedList handlerList = new LinkedList();
private Map fields = new HashMap();
private Set staticFields = new HashSet();
static {
try {
forName = Class.class.getDeclaredMethod("forName", TYPES_STRING);
getMessage = Throwable.class.getDeclaredMethod("getMessage", null);
} catch (Exception e) {
throw new CodeGenerationException(e);
}
}
protected CodeGenerator(String className, Class superclass, ClassLoader loader) {
if (loader == null) {
throw new IllegalArgumentException("ClassLoader is required");
}
this.loader = loader;
cg = new ClassGen(className, superclass.getName(), SOURCE_FILE, ACC_PUBLIC, null);
cp = cg.getConstantPool();
this.superclass = superclass;
}
protected String getClassName() {
return cg.getClassName();
}
protected Class getSuperclass() {
return superclass;
}
public static void setDebugLocation(String debugLocation) {
CodeGenerator.debugLocation = debugLocation;
}
/**
* method used to generate code
*/
abstract protected void generate() throws Exception;
public Class define() {
try {
try {
generate();
String name = cg.getClassName();
byte[] bytes = cg.getJavaClass().getBytes();
if (debugLocation != null) {
OutputStream out = new FileOutputStream(debugLocation + name + ".cglib");
out.write(bytes);
out.close();
}
PrivilegedAction action = getDefineClassAction(name, bytes, loader);
return (Class)java.security.AccessController.doPrivileged(action);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new CodeGenerationException(e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
// almost impossible
throw new CodeGenerationException(t);
}
}
private static PrivilegedAction getDefineClassAction(final String name,
final byte[] b,
final ClassLoader loader) {
return new PrivilegedAction() {
public Object run() {
try {
Method m = ClassLoader.class.getDeclaredMethod("defineClass", TYPES_DEFINE_CLASS);
// protected method invocaton
boolean flag = m.isAccessible();
m.setAccessible(true);
Object[] args = new Object[]{ name, b, new Integer(0), new Integer(b.length) };
Class result = (Class)m.invoke(loader, args);
m.setAccessible(flag);
return result;
} catch (Exception e) {
throw new CodeGenerationException(e);
}
}
};
}
static {
try {
primitiveMethods.put(Boolean.TYPE, Boolean.class.getDeclaredMethod("booleanValue", null));
primitiveMethods.put(Character.TYPE, Character.class.getDeclaredMethod("charValue", null));
primitiveMethods.put(Long.TYPE, Number.class.getDeclaredMethod("longValue", null));
primitiveMethods.put(Double.TYPE, Number.class.getDeclaredMethod("doubleValue", null));
primitiveMethods.put(Float.TYPE, Number.class.getDeclaredMethod("floatValue", null));
primitiveMethods.put(Short.TYPE, Number.class.getDeclaredMethod("intValue", null));
primitiveMethods.put(Integer.TYPE, Number.class.getDeclaredMethod("intValue", null));
primitiveMethods.put(Byte.TYPE, Number.class.getDeclaredMethod("intValue", null));
EQUALS_METHOD = Object.class.getDeclaredMethod("equals", new Class[]{ Object.class });
} catch (NoSuchMethodException e) {
throw new CodeGenerationException(e);
}
primitiveToWrapper.put(Boolean.TYPE, Boolean.class);
primitiveToWrapper.put(Character.TYPE, Character.class);
primitiveToWrapper.put(Long.TYPE, Long.class);
primitiveToWrapper.put(Double.TYPE, Double.class);
primitiveToWrapper.put(Float.TYPE, Float.class);
primitiveToWrapper.put(Short.TYPE, Short.class);
primitiveToWrapper.put(Integer.TYPE, Integer.class);
primitiveToWrapper.put(Byte.TYPE, Byte.class);
}
protected void declare_interfaces(Class[] interfaces) {
for (int i = 0; i < interfaces.length; i++) {
declare_interface(interfaces[i]);
}
}
protected void declare_interface(Class iface) {
cg.addInterface(iface.getName());
}
protected void declare_field(int modifiers, Class typeClass, String name) {
if (fields.containsKey(name)) {
throw new IllegalArgumentException("Field \"" + name + "\" already exists");
}
Type type = getType(typeClass);
FieldGen fg = new FieldGen(javaModifiersToBcel(modifiers), type, name, cp);
cg.addField(fg.getField());
int ref = cp.addFieldref(cg.getClassName(), name, type.getSignature());
if (Modifier.isStatic(modifiers)) {
staticFields.add(name);
}
fields.put(name, new Integer(ref));
}
protected void begin_method(int modifiers, Class returnType, String methodName,
Class[] parameterTypes, Class[] exceptionTypes) {
checkInMethod();
this.returnType = returnType;
mg = new MethodGen(javaModifiersToBcel(modifiers),
getType(returnType),
getTypes(parameterTypes),
null,
methodName,
cg.getClassName(), il, cp);
if (exceptionTypes != null) {
for (int i = 0; i < exceptionTypes.length; i++) {
mg.addException(exceptionTypes[i].getName());
}
}
setNextLocal();
}
protected void begin_method(java.lang.reflect.Method method) {
int modifiers = method.getModifiers();
modifiers = Modifier.FINAL
| (modifiers
& ~Modifier.ABSTRACT
& ~Modifier.NATIVE
& ~Modifier.SYNCHRONIZED);
begin_method(method, modifiers);
}
protected void begin_method(java.lang.reflect.Method method, int modifiers) {
begin_method(modifiers, method.getReturnType(), method.getName(),
method.getParameterTypes(), method.getExceptionTypes());
}
protected void begin_constructor(java.lang.reflect.Constructor constructor) {
begin_constructor(constructor.getParameterTypes());
}
protected void begin_constructor() {
begin_constructor(TYPES_EMPTY);
}
protected void begin_constructor(Class[] parameterTypes) {
checkInMethod();
returnType = Void.TYPE;
mg = new MethodGen(ACC_PUBLIC, Type.VOID, getTypes(parameterTypes), null,
CONSTRUCTOR_NAME, cg.getClassName(), il, cp);
setNextLocal();
}
protected void begin_static() {
checkInMethod();
returnType = Void.TYPE;
mg = new MethodGen(ACC_STATIC, Type.VOID, new Type[0], null,
STATIC_NAME, cg.getClassName(), il, cp);
setNextLocal();
}
private void checkInMethod() {
if (inMethod) {
throw new IllegalStateException("cannot nest methods");
}
}
private void setNextLocal() {
nextLocal = 1 + getStackSize(mg.getArgumentTypes());
}
// TODO: ensure there are matched pairs and there is no nesting
protected void end_constructor() {
end_method();
}
protected void end_static() {
end_method();
}
protected void end_method() {
setTargets();
// TODO: PRINT DEBUG
// System.out.print(mg.getMethod());
// System.out.print(mg.getMethod().getCode());
mg.removeNOPs();
mg.stripAttributes(true);
mg.setMaxLocals();
mg.setMaxStack();
cg.addMethod(mg.getMethod());
il.dispose();
locals.clear();
localTypes.clear();
if (handlerStack.size() > 0) {
throw new IllegalStateException("unclosed exception handler");
}
handlerList.clear();
inMethod = false;
}
/**
* Allocates and fills an Object[] array with the arguments to the
* current method. Primitive values are inserted as their boxed
* (Object) equivalents.
*/
protected void create_arg_array() {
/* generates:
Object args[] = new Object[]{ arg1, new Integer(arg2) };
*/
Type[] types = mg.getArgumentTypes();
push(types.length);
newarray();
for (int i = 0; i < types.length; i++) {
dup();
push(i);
load_arg(i);
box(types[i]);
aastore();
}
}
private InstructionHandle mark() {
return il.append(new NOP());
}
// TODO: use labels instead?
protected int begin_handler() {
int ref = handlerList.size();
InstructionHandle[] ih = new InstructionHandle[]{ mark(), null };
handlerList.add(ih);
handlerStack.add(ih);
return ref;
}
protected void end_handler() {
if (handlerStack.size() == 0) {
throw new IllegalStateException("mismatched handler boundaries");
}
InstructionHandle[] ih = (InstructionHandle[])handlerStack.removeLast();
ih[1] = il.getEnd().getPrev();
}
protected void handle_exception(int ref, Class exceptionType) {
if (handlerList.size() <= ref) {
throw new IllegalArgumentException("unknown handler reference: " + ref);
}
InstructionHandle[] ih = (InstructionHandle[])handlerList.get(ref);
if (ih[1] == null) {
throw new IllegalStateException("end of handler is unset");
}
mg.addExceptionHandler(ih[0], ih[1], mark(), (ObjectType)getType(exceptionType));
}
private void append(Instruction intruction) {
il.append(intruction);
}
private void append(String label, Instruction instruction) {
if (label != null) {
initLabels();
if (null != labels.put(label, il.append(instruction))) {
throw new IllegalStateException("duplicated label " + label);
}
} else {
il.append(instruction);
}
}
private void initLabels() {
if (labels == null) {
labels = new HashMap();
}
}
private void append(BranchInstruction instruction, String label) {
if (branches == null) {
branches = new HashMap();
}
List list = (List)branches.get(label);
if (list == null) {
branches.put(label, list = new LinkedList());
}
list.add(instruction);
il.append(instruction);
}
private void setTargets() {
if (labels != null && branches != null) {
for( Iterator labelIterator = labels.entrySet().iterator(); labelIterator.hasNext(); ){
Map.Entry label = (Map.Entry)labelIterator.next();
List branchInstructions = (List)branches.get(label.getKey());
if( branchInstructions != null ){
for( Iterator instructions = branchInstructions.iterator(); instructions.hasNext(); ){
BranchInstruction instruction = (BranchInstruction)instructions.next();
instruction.setTarget( (InstructionHandle)label.getValue() );
}
}
}
}
if( labels != null){
labels.clear();
}
if( branches != null ){
branches.clear();
}
}
protected void ifeq(String label ){ append( new IFEQ(null), label ); }
protected void ifne(String label){ append( new IFNE(null), label ); }
protected void iflt(String label){ append( new IFLT(null), label ); }
protected void ifge(String label){ append( new IFGE(null), label ); }
protected void ifgt(String label){ append( new IFGT(null), label ); }
protected void ifle(String label){ append( new IFLE(null), label ); }
protected void goTo(String label){ append( new GOTO(null), label ); }
protected void jsr(String label ){ append( new JSR(null), label ); }
protected void ifnull(String label){ append( new IFNULL(null), label ); }
protected void ifnonnull(String label){ append( new IFNONNULL(null), label ); }
protected void if_icmplt(String label) {
append(new IF_ICMPLT(null), label);
}
protected void if_icmpne(String label) {
append(new IF_ICMPNE(null), label);
}
protected void if_icmpeq(String label) {
append(new IF_ICMPEQ(null), label);
}
// math
protected void imul() { append(new IMUL()); }
protected void iadd() { append(new IADD()); }
protected void lushr() { append(new LUSHR()); }
protected void lxor() { append(new LXOR()); }
protected void ixor() { append(new IXOR()); }
protected void l2i() { append(new L2I()); }
protected void dcmpg() { append(new DCMPG()); }
protected void fcmpg() { append(new FCMPG()); }
protected void lcmp() { append(new LCMP()); }
protected void nop(){ append( new NOP()); }
protected void nop(String label){ append( label, new NOP() ); }
protected void aconst_null(){ append( new ACONST_NULL() ); }
protected void push(int i) {
if (i < 0) {
append(new LDC(cp.addInteger(i)));
} else if (i <= 5) {
append(new ICONST(i));
} else if (i <= Byte.MAX_VALUE) {
append(new BIPUSH((byte)i));
} else if (i <= Short.MAX_VALUE) {
append(new SIPUSH((short)i));
} else {
append(new LDC(cp.addInteger(i)));
}
}
protected void push( long value){
if (value == 0L || value == 1L) {
append(new LCONST(value));
} else {
append( new LDC( cp.addLong(value) ) );
}
}
protected void push( float value ){
if (value == 0f || value == 1f || value == 2f) {
append(new FCONST(value));
} else {
append( new LDC( cp.addFloat(value) ) );
}
}
protected void push( double value){
if (value == 0d || value == 1d) {
append(new DCONST(value));
} else {
append( new LDC( cp.addDouble(value) ) ) ;
}
}
protected void push(String value) {
append(new LDC(cp.addString(value)));
}
protected void newarray() {
newarray(Object.class);
}
protected void newarray(Class clazz) {
if (clazz.isPrimitive()) {
append(new NEWARRAY((BasicType)getType(clazz)));
} else {
append(new ANEWARRAY(cp.addClass(clazz.getName())));
}
}
protected void arraylength() {
append(new ARRAYLENGTH());
}
protected void array_load(Class clazz) {
if (clazz.isPrimitive()) {
if (clazz.equals(Long.TYPE)) {
append(new LALOAD());
} else if (clazz.equals(Double.TYPE)) {
append(new DALOAD());
} else if (clazz.equals(Float.TYPE)) {
append(new FALOAD());
} else {
append(new IALOAD());
}
} else {
append(new AALOAD());
}
}
protected void array_store(Class clazz) {
if (clazz.isPrimitive()) {
if (clazz.equals(Long.TYPE)) {
append(new LASTORE());
} else if (clazz.equals(Double.TYPE)) {
append(new DASTORE());
} else if (clazz.equals(Float.TYPE)) {
append(new FASTORE());
} else {
append(new IASTORE());
}
} else {
append(new AASTORE());
}
}
protected void load_this() {
append(new ALOAD(0));
}
protected void load_class(Class clazz) {
if (clazz.isPrimitive()) {
if (clazz.equals(Void.TYPE)) {
// TODO: error
}
try {
getfield(((Class)primitiveToWrapper.get(clazz)).getDeclaredField("TYPE"));
} catch (NoSuchFieldException e) {
throw new CodeGenerationException(e);
}
} else {
push(clazz.getName());
int ref = cp.addMethodref(cg.getClassName(),
FIND_CLASS,
getMethodSignature(Class.class, TYPES_STRING));
append(new INVOKESTATIC(ref));
}
}
/**
* Pushes all of the arguments of the current method onto the stack.
*/
protected void load_args() {
load_args(0, mg.getArgumentTypes().length);
}
/**
* Pushes the specified argument of the current method onto the stack.
* @param index the zero-based index into the argument list
*/
protected void load_arg(int index) {
int pos = 1 + skipArgs(index);
load_local(mg.getArgumentType(index), pos);
}
// zero-based (see load_this)
protected void load_args(int fromArg, int count) {
int pos = 1 + skipArgs(fromArg);
for (int i = 0; i < count; i++) {
Type t = mg.getArgumentType(fromArg + i);
load_local(t, pos);
pos += t.getSize();
}
}
private int skipArgs(int numArgs) {
int amount = 0;
for (int i = 0; i < numArgs; i++) {
amount += mg.getArgumentType(i).getSize();
}
return amount;
}
private void load_local(Type t, int pos) {
if (t instanceof BasicType) {
if (t.equals(Type.LONG)) {
append(new LLOAD(pos));
} else if (t.equals(Type.DOUBLE)) {
append(new DLOAD(pos));
} else if (t.equals(Type.FLOAT)) {
append(new FLOAD(pos));
} else {
append(new ILOAD(pos));
}
} else {
append(new ALOAD(pos));
}
}
private void store_local(Type t, int pos) {
if (t instanceof BasicType) {
if (t.equals(Type.LONG)) {
append(new LSTORE(pos));
} else if (t.equals(Type.DOUBLE)) {
append(new DSTORE(pos));
} else if (t.equals(Type.FLOAT)) {
append(new FSTORE(pos));
} else {
append(new ISTORE(pos));
}
} else {
append(new ASTORE(pos));
}
}
protected void iinc(String local, int amount) {
append(new IINC(getLocal(local), amount));
}
protected void local_type(String name, Class type) {
localTypes.put(name, getType(type));
}
protected void store_local(String name) {
Integer position = (Integer)locals.get(name);
if (position == null) {
position = new Integer(nextLocal);
locals.put(name, position);
Type type = (Type)localTypes.get(name);
nextLocal += (type == null) ? 1 : type.getSize();
}
store_local((Type)localTypes.get(name), position.intValue());
}
protected void load_local(String name) {
load_local((Type)localTypes.get(name), getLocal(name));
}
private int getLocal(String name) {
Integer position = (Integer)locals.get(name);
if (position == null) {
throw new IllegalArgumentException("unknown local " + name);
}
return position.intValue();
}
protected void pop() { append( new POP() ); }
protected void pop2() { append( new POP2() ); }
protected void dup() { append( new DUP() ); }
protected void dup2() { append( new DUP2() ); }
protected void dup_x1() { append( new DUP_X1() ); }
protected void dup_x2() { append( new DUP_X2() ); }
protected void swap(){ append( new SWAP() ); }
protected void pop(String label) { append( label, new POP() ); }
protected void dup(String label) { append( label, new DUP() ); }
protected void swap(String label) { append( label, new SWAP() ); }
protected void return_value() {
if (returnType.isPrimitive()) {
if (returnType.equals(Void.TYPE)) {
append(new RETURN());
} else if (returnType.equals(Long.TYPE)) {
append(new LRETURN());
} else if (returnType.equals(Double.TYPE)) {
append(new DRETURN());
} else if (returnType.equals(Float.TYPE)) {
append(new FRETURN());
} else {
append(new IRETURN());
}
} else {
append(new ARETURN());
}
}
private int getFieldref(Field field) {
return cp.addFieldref(field.getDeclaringClass().getName(),
field.getName(),
getType(field.getType()).getSignature());
}
private int getFieldref(String name) {
Integer ref = (Integer)fields.get(name);
if (ref == null) {
throw new IllegalArgumentException("No field named \"" + name + "\"");
}
return ref.intValue();
}
private int getInstanceField(String name) {
int ref = getFieldref(name);
if (staticFields.contains(name)) {
throw new IllegalArgumentException("Field \"" + name + "\" is static");
}
return ref;
}
private int getStaticField(String name) {
int ref = getFieldref(name);
if (!staticFields.contains(name)) {
throw new IllegalArgumentException("Field \"" + name + "\" is not static");
}
return ref;
}
protected void getfield(String name) {
append(new GETFIELD(getInstanceField(name)));
}
protected void putfield(String name) {
append(new PUTFIELD(getInstanceField(name)));
}
protected void getstatic(String name) {
append(new GETSTATIC(getStaticField(name)));
}
protected void putstatic(String name) {
append(new PUTSTATIC(getStaticField(name)));
}
protected void super_getfield(String name) throws NoSuchFieldException {
getfield(superclass.getField(name));
}
protected void super_putfield(String name) throws NoSuchFieldException {
putfield(superclass.getDeclaredField(name));
}
protected void getfield(Field field) {
if (Modifier.isStatic(field.getModifiers())) {
append(new GETSTATIC(getFieldref(field)));
} else {
append(new GETFIELD(getFieldref(field)));
}
}
protected void putfield(Field field) {
if (Modifier.isStatic(field.getModifiers())) {
append(new PUTSTATIC(getFieldref(field)));
} else {
append(new PUTFIELD(getFieldref(field)));
}
}
protected void invoke(Method method) {
if (method.getDeclaringClass().isInterface()) {
invoke_interface(method);
} else if (Modifier.isStatic(method.getModifiers())) {
invoke_static(method);
} else {
invoke_virtual(method);
}
}
protected void super_invoke(Method method) {
append(new INVOKESPECIAL(addMethodref(method)));
}
protected void invoke_virtual_this(String methodName, Class returnType, Class[] parameterTypes) {
append(new INVOKEVIRTUAL(cp.addMethodref(cg.getClassName(),
methodName,
getMethodSignature(returnType, parameterTypes))));
}
protected void invoke_static_this(String methodName, Class returnType, Class[] parameterTypes) {
append(new INVOKESTATIC(cp.addMethodref(cg.getClassName(),
methodName,
getMethodSignature(returnType, parameterTypes))));
}
protected void super_invoke() {
append(new INVOKESPECIAL(cp.addMethodref(cg.getSuperclassName(), mg.getName(), mg.getSignature())));
}
protected void invoke_constructor(Class type) {
invoke_constructor(type, TYPES_EMPTY);
}
protected void invoke_constructor(Class type, Class[] parameterTypes) {
invoke_constructor_helper(type.getName(), parameterTypes);
}
private void invoke_interface(Method method) {
int ref = cp.addInterfaceMethodref(method.getDeclaringClass().getName(),
method.getName(),
getMethodSignature(method));
append(new INVOKEINTERFACE(ref, 1 + getStackSize(method.getParameterTypes())));
}
private static int getStackSize(Class clazz) {
return getType(clazz).getSize();
}
private static int getStackSize(Class[] classes) {
int size = 0;
for (int i = 0; i < classes.length; i++) {
size += getStackSize(classes[i]);
}
return size;
}
private static int getStackSize(Type[] types) {
int size = 0;
for (int i = 0; i < types.length; i++) {
size += types[i].getSize();
}
return size;
}
// this is taken from BCEL CVS: Type.getType(Class)
public static Type getType(java.lang.Class cl) {
if (cl == null) {
throw new IllegalArgumentException("Class must not be null");
}
if (cl.isArray()) {
return Type.getType(cl.getName());
} else if (cl.isPrimitive()) {
if (cl == Integer.TYPE) {
return Type.INT;
} else if (cl == Void.TYPE) {
return Type.VOID;
} else if (cl == Double.TYPE) {
return Type.DOUBLE;
} else if (cl == Float.TYPE) {
return Type.FLOAT;
} else if (cl == Boolean.TYPE) {
return Type.BOOLEAN;
} else if (cl == Byte.TYPE) {
return Type.BYTE;
} else if (cl == Short.TYPE) {
return Type.SHORT;
} else if (cl == Byte.TYPE) {
return Type.BYTE;
} else if (cl == Long.TYPE) {
return Type.LONG;
} else if (cl == Character.TYPE) {
return Type.CHAR;
} else {
throw new IllegalStateException("Ooops, what primitive type is " + cl);
}
} else { // "Real" class
return new ObjectType(cl.getName());
}
}
private static Type[] getTypes(Class[] classes) {
Type[] types = new Type[classes.length];
for (int i = 0; i < types.length; i++) {
types[i] = getType(classes[i]);
}
return types;
}
private static String getMethodSignature(Method method) {
return getMethodSignature(method.getReturnType(), method.getParameterTypes());
}
private static String getMethodSignature(Class returnType, Class[] parameterTypes) {
return Type.getMethodSignature(getType(returnType), getTypes(parameterTypes));
}
private void invoke_virtual(Method method) {
append(new INVOKEVIRTUAL(addMethodref(method)));
}
private void invoke_static(Method method) {
append(new INVOKESTATIC(addMethodref(method)));
}
private int addMethodref(Method method) {
return cp.addMethodref(method.getDeclaringClass().getName(),
method.getName(),
getMethodSignature(method));
}
protected void super_invoke_constructor(Constructor constructor) {
super_invoke_constructor(constructor.getParameterTypes());
}
protected void super_invoke_constructor() {
invoke_constructor_helper(cg.getSuperclassName(), TYPES_EMPTY);
}
protected void super_invoke_constructor(Class[] parameterTypes) {
invoke_constructor_helper(cg.getSuperclassName(), parameterTypes);
}
protected void invoke_constructor_this() {
invoke_constructor_this(TYPES_EMPTY);
}
protected void invoke_constructor_this(Class[] parameterTypes) {
invoke_constructor_helper(cg.getClassName(), parameterTypes);
}
private void invoke_constructor_helper(String className, Class[] parameterTypes) {
int ref = cp.addMethodref(className,
CONSTRUCTOR_NAME,
getMethodSignature(Void.TYPE, parameterTypes));
append(new INVOKESPECIAL(ref));
}
protected void new_instance_this() {
append(new NEW(cp.addClass(cg.getClassName())));
}
protected void new_instance(Class clazz) {
append(new NEW(cp.addClass(clazz.getName())));
}
protected void aaload( int index ){
push(index);
aaload();
}
protected void aaload() {
append( new AALOAD() );
}
protected void aastore() {
append(new AASTORE());
}
protected void athrow(){ append( new ATHROW() ); }
protected void athrow(String label){ append(label,new ATHROW() ); }
protected String newLabel() {
initLabels();
String label;
do {
label = PRIVATE_PREFIX + nextPrivateLabel++;
} while (labels.containsKey(label));
return label;
}
protected String newLocal() {
String local;
do {
local = PRIVATE_PREFIX + nextPrivateLocal++;
} while (locals.containsKey(local));
return local;
}
/**
* Pushes a zero onto the stack if the argument is a primitive class, or a null otherwise.
*/
protected void zero_or_null(Class type) {
if (type.isPrimitive()) {
if (type.equals(Double.TYPE)) {
push(0d);
} else if (type.equals(Long.TYPE)) {
push(0L);
} else if (type.equals(Float.TYPE)) {
push(0f);
} else if (type.equals(Void.TYPE)) {
// ignore
} else {
push(0);
}
} else {
aconst_null();
}
}
/**
* Unboxes the object on the top of the stack. If the object is null, the
* unboxed primitive value becomes zero.
*/
protected void unbox_or_zero(Class type) {
if (type.isPrimitive()) {
if (!type.equals(Void.TYPE)) {
String nonNull = newLabel();
String end = newLabel();
dup();
ifnonnull(nonNull);
pop();
zero_or_null(type);
goTo(end);
nop(nonNull);
unbox(type);
nop(end);
}
} else {
checkcast(type);
}
}
private Class getPrimitiveClass(BasicType type) {
switch (type.getType()) {
case T_BYTE:
return Byte.TYPE;
case T_BOOLEAN:
return Boolean.TYPE;
case T_CHAR:
return Character.TYPE;
case T_LONG:
return Long.TYPE;
case T_DOUBLE:
return Double.TYPE;
case T_FLOAT:
return Float.TYPE;
case T_SHORT:
return Short.TYPE;
case T_INT:
return Integer.TYPE;
case T_VOID:
return Void.TYPE;
default:
return null; // impossible
}
}
private void box(Type type) {
if (type instanceof BasicType) {
box(getPrimitiveClass((BasicType)type));
}
}
/**
* If the argument is a primitive class, replaces the primitive value
* on the top of the stack with the wrapped (Object) equivalent. For
* example, char -> Character.
* If the class is Void, a null is pushed onto the stack instead.
* @param clazz the class indicating the current type of the top stack value
*/
protected void box(Class clazz) {
if (clazz.isPrimitive()) {
if (clazz.equals(Void.TYPE)) {
aconst_null();
} else {
Class wrapper = (Class)primitiveToWrapper.get(clazz);
new_instance(wrapper);
if (getStackSize(clazz) == 2) {
// Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o
dup_x2();
dup_x2();
pop();
} else {
// p -> po -> opo -> oop -> o
dup_x1();
swap();
}
invoke_constructor(wrapper, new Class[]{ clazz });
}
}
}
/**
* If the argument is a primitive class, replaces the object
* on the top of the stack with the unwrapped (primitive)
* equivalent. For example, Character -> char.
* @param clazz the class indicating the desired type of the top stack value
* @return true if the value was unboxed
*/
protected void unbox(Class clazz) {
if (clazz.isPrimitive()) {
if (clazz.equals(Void.TYPE)) {
// ignore
}
Class wrapper = (Class)primitiveToWrapper.get(clazz);
Method convert = (Method)primitiveMethods.get(clazz);
checkcast(wrapper);
invoke(convert);
} else {
checkcast(clazz);
}
}
protected void checkcast_this() {
append(new CHECKCAST(cp.addClass(cg.getClassName())));
}
protected void checkcast(Class clazz) {
Type type = getType(clazz);
if (clazz.isArray()) {
append(new CHECKCAST(cp.addArrayClass((ArrayType)type)));
} else if (clazz.equals(Object.class)) {
// ignore
} else {
append(new CHECKCAST(cp.addClass((ObjectType)type)));
}
}
protected void instance_of(Class clazz) {
append(new INSTANCEOF(cp.addClass(clazz.getName())));
}
private static int javaModifiersToBcel(int modifiers) {
int result = 0;
if (Modifier.isAbstract(modifiers))
result |= ACC_ABSTRACT;
if (Modifier.isFinal(modifiers))
result |= ACC_FINAL;
if (Modifier.isInterface(modifiers))
result |= ACC_INTERFACE;
if (Modifier.isNative(modifiers))
result |= ACC_NATIVE;
if (Modifier.isPrivate(modifiers))
result |= ACC_PRIVATE;
if (Modifier.isProtected(modifiers))
result |= ACC_PROTECTED;
if (Modifier.isPublic(modifiers))
result |= ACC_PUBLIC;
if (Modifier.isStatic(modifiers))
result |= ACC_STATIC;
if (Modifier.isStrict(modifiers))
result |= ACC_STRICT;
if (Modifier.isSynchronized(modifiers))
result |= ACC_SYNCHRONIZED;
if (Modifier.isTransient(modifiers))
result |= ACC_TRANSIENT;
if (Modifier.isVolatile(modifiers))
result |= ACC_VOLATILE;
return result;
}
protected void generateNullConstructor() {
begin_constructor();
load_this();
super_invoke_constructor();
return_value();
end_constructor();
}
protected void generateFindClass() {
/* generates:
static private Class findClass(String name) throws Exception {
try {
return Class.forName(name);
} catch (java.lang.ClassNotFoundException cne) {
throw new java.lang.NoClassDefFoundError(cne.getMessage());
}
}
*/
begin_method(Modifier.PRIVATE | Modifier.STATIC,
Class.class,
FIND_CLASS,
TYPES_STRING,
null);
int eh = begin_handler();
load_this();
invoke(forName);
return_value();
end_handler();
handle_exception(eh, ClassNotFoundException.class);
invoke(getMessage);
new_instance(NoClassDefFoundError.class);
dup_x1();
swap();
invoke_constructor(NoClassDefFoundError.class, TYPES_STRING);
athrow();
end_method();
}
protected boolean isVisible(Member member, Package packageName) {
int mod = member.getModifiers();
if (Modifier.isPrivate(mod)) {
return false;
}
if (Modifier.isProtected(mod) || Modifier.isPublic(mod)) {
return true;
}
Package p = member.getDeclaringClass().getPackage();
return ( null == packageName ? p == null :
packageName.equals(p) );
}
protected interface ProcessArrayCallback {
public void processElement(Class type);
}
/**
* Process an array on the stack. Assumes the top item on the stack
* is an array of the specified type. For each element in the array,
* puts the element on the stack and triggers the callback.
* @param type the type of the array (type.isArray() must be true)
* @param callback the callback triggered for each element
*/
protected void process_array(Class type, ProcessArrayCallback callback) {
Class compType = type.getComponentType();
String array = newLocal();
String loopvar = newLocal();
String loopbody = newLabel();
String checkloop = newLabel();
local_type(loopvar, Integer.TYPE);
store_local(array);
push(0);
store_local(loopvar);
goTo(checkloop);
nop(loopbody);
load_local(array);
load_local(loopvar);
array_load(compType);
callback.processElement(compType);
iinc(loopvar, 1);
nop(checkloop);
load_local(loopvar);
load_local(array);
arraylength();
if_icmplt(loopbody);
}
/**
* Process two arrays on the stack in parallel. Assumes the top two items on the stack
* are arrays of the specified class. The arrays must be the same length. For each pair
* of elements in the arrays, puts the pair on the stack and triggers the callback.
* @param clazz the type of the arrays (clazz.isArray() must be true)
* @param callback the callback triggered for each pair of elements
*/
protected void process_arrays(Class clazz, ProcessArrayCallback callback) {
Class compType = clazz.getComponentType();
String array1 = newLocal();
String array2 = newLocal();
String loopvar = newLocal();
String loopbody = newLabel();
String checkloop = newLabel();
local_type(loopvar, Integer.TYPE);
store_local(array1);
store_local(array2);
push(0);
store_local(loopvar);
goTo(checkloop);
nop(loopbody);
load_local(array1);
load_local(loopvar);
array_load(compType);
load_local(array2);
load_local(loopvar);
array_load(compType);
callback.processElement(compType);
iinc(loopvar, 1);
nop(checkloop);
load_local(loopvar);
load_local(array1);
arraylength();
if_icmplt(loopbody);
}
/**
* Branches to the specified label if the top two items on the stack
* are not equal. The items must both be of the specified
* class. Equality is determined by comparing primitive values
* directly and by invoking the <code>equals</code> method for
* Objects. Arrays are recursively processed in the same manner.
*/
protected void not_equals(Class clazz, final String notEquals) {
(new ProcessArrayCallback() {
public void processElement(Class type) {
not_equals_helper(type, notEquals, this);
}
}).processElement(clazz);
}
private void not_equals_helper(Class clazz, String notEquals, ProcessArrayCallback callback) {
if (clazz.isPrimitive()) {
if (returnType.equals(Double.TYPE)) {
dcmpg();
ifne(notEquals);
} else if (returnType.equals(Long.TYPE)) {
lcmp();
ifne(notEquals);
} else if (returnType.equals(Float.TYPE)) {
fcmpg();
ifne(notEquals);
} else {
if_icmpne(notEquals);
}
} else {
String end = newLabel();
nullcmp(notEquals, end);
if (clazz.isArray()) {
String checkContents = newLabel();
dup2();
arraylength();
swap();
arraylength();
if_icmpeq(checkContents);
pop2();
goTo(notEquals);
nop(checkContents);
process_arrays(clazz, callback);
} else {
invoke(EQUALS_METHOD);
ifeq(notEquals);
}
nop(end);
}
}
protected void throwException(Class type, String msg){
new_instance(type);
dup();
push(msg);
invoke_constructor(type, new Class[]{ String.class });
athrow();
}
/**
* If both objects on the top of the stack are non-null, does nothing.
* If one is null, or both are null, both are popped off and execution
* branches to the respective label.
* @param oneNull label to branch to if only one of the objects is null
* @param bothNull label to branch to if both of the objects are null
*/
protected void nullcmp(String oneNull, String bothNull) {
dup2();
String nonNull = newLabel();
String oneNullHelper = newLabel();
String end = newLabel();
ifnonnull(nonNull);
ifnonnull(oneNullHelper);
pop2();
goTo(bothNull);
nop(nonNull);
ifnull(oneNullHelper);
goTo(end);
nop(oneNullHelper);
pop2();
goTo(oneNull);
nop(end);
}
} |
package ru.job4j.max;
public class Max {
/**
* max.
* @param first number
* @param second number
* @return max number
*/
public int max(int first, int second) {
return first > second ? first : second;
}
/**
* max.
* @param first number
* @param second number
* @param third number
* @return max number
*/
public int max(int first, int second, int third) {
return max(first, max(second, third));
}
} |
package rtdc.web.test;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import rtdc.core.Config;
import rtdc.core.event.*;
import rtdc.core.json.JSONArray;
import rtdc.core.json.JSONObject;
import rtdc.core.model.Action;
import rtdc.core.model.Message;
import rtdc.core.model.Unit;
import rtdc.core.model.User;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
public class ServiceTest {
private static final String _url = "http://" + Config.SERVER_IP + ":8888/api/";
private static final String USER_AGENT = "Mozilla/5.0";
private static final String TEST_USERNAME = "nathaniel";
private static final String TEST_PASSWORD = "password";
@BeforeClass
public static void oneTimeSetUp() {
}
private static JSONObject executeSyncRequest(String service, String urlParameters, String requestMethod, @Nullable String authToken) {
try {
URL urlObj = new URL(_url + service);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod(requestMethod);
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
if (authToken != null)
con.setRequestProperty("auth_token", authToken);
con.setDoOutput(true);
if (urlParameters != null) {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
}
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject object = new JSONObject(response.toString());
return object;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
// Does not happen when debugging the server and stepping through the getUnit method in UnitServlet ??
private static Unit getSingleUnit(String authToken, int id) {
JSONObject unitJson = executeSyncRequest("units/" + id, null, "GET", authToken);
if (unitJson.get("_type").equals(ErrorEvent.TYPE.getName())) {
return null;
}
JSONArray unitJsonArray = unitJson.getJSONArray("units");
Unit unit = new Unit(unitJsonArray.getJSONObject(0));
return unit;
}
private String getAuthToken(String username, String password) {
JSONObject object = executeSyncRequest("auth/login", "username=" + username + "&password=" + password, "POST", null);
return object.get("authenticationToken").toString();
}
} |
package chart;
import sesim.OHLCDataItem;
import sesim.OHLCData;
import java.awt.*;
import sesim.Exchange.*;
import sesim.Quote;
import gui.Globals;
import java.awt.geom.Rectangle2D;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import sesim.MinMax;
import sesim.Scheduler;
/**
*
* @author 7u83 <7u83@mail.ru>
*/
public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollable {
private int em_height;
private int em_width;
protected double x_legend_height = 6;
protected double x_unit_width = 1.0;
/**
* width of y legend in em
*/
protected float y_legend_width = 10;
protected int num_bars = 4000;
protected Rectangle clip_bounds = new Rectangle();
private int first_bar, last_bar;
public final void initChart() {
// data = new OHLCData(60000*30);
//data = new OHLCData(60000*30);
//data = Globals.se.getOHLCdata(60000 * 30);
this.setCompression(10000);
}
/**
* Creates new form Chart
*/
public Chart() {
if (Globals.se == null) {
return;
}
initComponents();
initChart();
// initCtxMenu();
//setCompression(60000);
if (Globals.se == null) {
return;
}
Globals.se.addQuoteReceiver(this);
// scrollPane=new JScrollPane();
// scrollPane.setViewportView(this);
}
OHLCData data;
@Override
public Dimension getPreferredScrollableViewportSize() {
return this.getPreferredSize();
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 1;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 100;
}
@Override
public boolean getScrollableTracksViewportWidth() {
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
class XLegendDef {
//int big_tick = 10;
// long start;
XLegendDef() {
}
String getAt(int unit) {
int fs = data.getFrameSize();
return Scheduler.formatTimeMillis(0 + unit * fs);
}
}
protected void setXLegendHeight(int h) {
this.x_legend_height = h;
}
/**
* Color of X-legend
*/
protected Color xl_color = null;
/**
* Background color of X-legend
*/
protected Color xl_bgcolor = null;
/**
* Height of X-legend
*/
protected int xl_height;
/**
* Draw the one and only one X legend
*
* @param g Graphics conext to draw
* @param xld Definition
*/
void drawXLegend(Graphics2D g, XLegendDef xld) {
int yw = (int) (this.y_legend_width * this.em_width);
//g.setColor(Color.BLUE);
// g.drawRect(clip_bounds.x, clip_bounds.y, clip_bounds.width - yw-1, clip_bounds.height-1);
g.setClip(clip_bounds.x, clip_bounds.y, clip_bounds.width - yw, clip_bounds.height);
Dimension dim = getSize();
int y = clip_bounds.height - em_height * xl_height;
// g.drawLine(0, y, dim.width, y);
// Set background color
if (this.xl_bgcolor != null) {
Color cur = g.getColor();
g.setColor(xl_bgcolor);
g.fillRect(0, y, dim.width, em_height * xl_height);
g.drawRect(0, y, dim.width, em_height * xl_height);
g.setColor(cur);
}
int n;
double x;
long big_tick = 1;
double btl, xxx;
do {
big_tick++;
btl = em_width * big_tick * x_unit_width;
xxx = 7 * em_width;
} while (btl < xxx);
for (n = 0, x = 0; x < dim.width; x += em_width * x_unit_width) {
if (n % big_tick == 1) {
g.drawLine((int) x, y, (int) x, y + em_width);
String text;
text = xld.getAt(n);
int swidth = g.getFontMetrics().stringWidth(text);
g.drawString(text, (int) x - swidth / 2, y + em_height * 2);
} else {
g.drawLine((int) x, y, (int) x, y + em_width / 2);
}
if (n % big_tick == 0) {
}
n += 1;
}
}
class RenderCtx {
Rectangle rect;
float scaling;
float min;
Graphics2D g;
float iwidth;
float getY(float y) {
float ys = rect.height / c_mm.getDiff();
if (c_mm.isLog()) {
return rect.height + rect.y - ((float) Math.log(y) - c_mm.getMin()) * ys;
}
return (rect.height - ((y - c_mm.getMin()) * c_yscaling)) + rect.y;
}
}
boolean logs = false;
float getY0(float y) {
float ys = c_rect.height / c_mm.getDiff();
// ys = c_rect.height / c_mm.getDiff();
if (c_mm.isLog()) {
// c_mm.setLog(true);
// ys = c_rect.height / c_mm.getDiff();
// return (c_rect.height - (((float)Math.log(y) - c_mm.getMin()) * ys)) + c_rect.y;
return c_rect.height + c_rect.y - ((float) Math.log(y) - c_mm.getMin()) * ys;
/* float m = c_mm.getMax() / c_mm.getMin();
float fac = (float) c_rect.height / (float) Math.log(m);
float fmin = c_rect.height - ((float) Math.log((y / c_mm.getMin())) * fac);
return fmin;
*/
//return c_rect.height - ((float) Math.log((y - c_mm.getMin()) * c_yscaling) * fac);
}
return (c_rect.height - ((y - c_mm.getMin()) * c_yscaling)) + c_rect.y;
// return c_rect.height - ((y - c_mm.getMin()) * c_yscaling);
}
double getValAtY(float y) {
float val = 0;
// y = (c_rect.height - ((val - c_mm.getMin()) * c_yscaling)) + c_rect.y;
// y-c_rect.y = c_rect.height - ((val - c_mm.getMin()) * c_yscaling)
// y-c_rect.y-c_rect.height = - ((val - c_mm.getMin()) * c_yscaling)
// -(y-c_rect.y-c_rect.heigh) = (val - c_mm.getMin()) * c_yscaling
// (-(y-c_rect.y-c_rect.heigh))/c_yscaling = (val - c_mm.getMin())
if (c_mm.isLog()) {
float ys = c_rect.height / c_mm.getDiff();
//val = return c_rect.height + c_rect.y - ((float)Math.log(y) - c_mm.getMin()) * ys;
// val + ((float)Math.log(y) - c_mm.getMin()) * ys = c_rect.height + c_rect.y
// val/ys + ((float)Math.log(y) - c_mm.getMin()) = (c_rect.height + c_rect.y)/ys
// val/ys + ((float)Math.log(y) = (c_rect.height + c_rect.y)/ys + c_mm.getMin())
//return (-(Math.exp(y)-c_rect.y-c_rect.height))/ys+c_mm.getMin();
return Math.exp((c_rect.height + c_rect.y) / ys + c_mm.getMin() - y / ys);
}
return (-(y - c_rect.y - c_rect.height)) / c_yscaling + c_mm.getMin();
// return (y+c_rect.y-c_rect.height)/c_yscaling+c_mm.getMin();
}
private void drawCandleItem(RenderCtx ctx, int prevx, int x, OHLCDataItem prev, OHLCDataItem i) {
Graphics2D g = ctx.g;
Rectangle r = ctx.rect;
if (i.open < i.close) {
int xl = (int) (x + ctx.iwidth / 2);
g.setColor(Color.BLACK);
g.drawLine(xl, (int) ctx.getY(i.close), xl, (int) ctx.getY(i.high));
g.drawLine(xl, (int) ctx.getY(i.low), xl, (int) ctx.getY(i.open));
float w = ctx.iwidth;
float h = (int) (ctx.getY(i.open) - ctx.getY(i.close));
g.setColor(Color.GREEN);
g.fillRect((int) (x), (int) ctx.getY(i.close), (int) w, (int) h);
g.setColor(Color.BLACK);
g.drawRect((int) (x), (int) ctx.getY(i.close), (int) w, (int) h);
} else {
int xl = (int) (x + ctx.iwidth / 2);
g.setColor(Color.RED);
g.drawLine(xl, (int) ctx.getY(i.high), xl, (int) ctx.getY(i.close));
g.drawLine(xl, (int) ctx.getY(i.open), xl, (int) ctx.getY(i.low));
float w = ctx.iwidth;
float h = (int) (ctx.getY(i.close) - ctx.getY(i.open));
g.fillRect((int) (x), (int) ctx.getY(i.open), (int) w, (int) h);
g.setColor(Color.BLACK);
g.drawRect((int) (x), (int) ctx.getY(i.open), (int) w, (int) h);
}
}
private void drawBarItem(RenderCtx ctx, int prevx, int x, OHLCDataItem prev, OHLCDataItem i) {
Graphics2D g = ctx.g;
g.setColor(Color.BLACK);
g.drawLine(x, (int) ctx.getY(0), x, (int) ctx.getY(i.volume));
Rectangle r = ctx.rect;
}
/**
* Char types
*/
protected enum ChartType {
CANDLESTICK,
BAR,
VOL,
}
ChartType ct = ChartType.CANDLESTICK;
private void drawItem(RenderCtx ctx, int prevx, int x, OHLCDataItem prev, OHLCDataItem i) {
switch (ct) {
case CANDLESTICK:
this.drawCandleItem(ctx, prevx, x, prev, i);
break;
case VOL:
this.drawBarItem(ctx, prevx, x, prev, i);
break;
}
}
float c_yscaling;
private void drawYLegend(RenderCtx ctx) {
Graphics2D g = ctx.g;
Rectangle dim;
dim = this.clip_bounds;
// Dimension rv = this.getSize();
int yw = (int) (this.y_legend_width * this.em_width);
g.drawLine(dim.width + dim.x - yw, 0, dim.width + dim.x - yw, dim.height);
float y1 = ctx.getY(c_mm.getMin(false));
float y2 = ctx.getY(c_mm.getMax(false));
float ydiff = y1 - y2;
System.out.printf("%s y1: %f, y2: %f, diff %f\n", Boolean.toString(c_mm.isLog()), y1, y2, ydiff);
for (int yp = (int) y2; yp < y1; yp += em_width * 5) {
g.drawLine(dim.width + dim.x - yw, yp, dim.width + dim.x - yw + em_width, yp);
double v1 = getValAtY(yp);
g.drawString(String.format("%.2f", v1), dim.width + dim.x - yw + em_width * 1.5f, yp + c_font_height / 3);
}
// c_yscaling = c_rect.height / c_mm.getDiff();
//System.out.printf("Step: %f\n",step);
double v1, v2;
v1 = getValAtY(y1);
v2 = getValAtY(y2);
System.out.printf("v1 %f, v2 %f\n", v1, v2);
/* for (float y = c_mm.getMin(); y < c_mm.getMax(); y += step) {
int my = (int) getY(y); //c_rect.height - (int) ((y - c_mm.getMin()) * c_yscaling);
g.drawLine(dim.width + dim.x - yw, my, dim.width + dim.x - yw + em_width, my);
g.drawString(String.format("%.2f", y), dim.width + dim.x - yw + em_width * 1.5f, my + c_font_height / 3);
}
*/
}
private MinMax c_mm = null;
private Rectangle c_rect;
void drawChart(RenderCtx ctx) {
c_yscaling = c_rect.height / c_mm.getDiff();
ctx.g.setClip(null);
// ctx.g.setColor(Color.ORANGE);
// ctx.g.setClip(ctx.rect.x, ctx.rect.y, ctx.rect.width, ctx.rect.height);
// ctx.g.drawRect(ctx.rect.x, ctx.rect.y, ctx.rect.width, ctx.rect.height);
this.drawYLegend(ctx);
/// ctx.g.setColor(Color.ORANGE);
int yw = (int) (this.y_legend_width * this.em_width);
ctx.g.setClip(clip_bounds.x, clip_bounds.y, clip_bounds.width - yw, clip_bounds.height);
// ctx.g.setClip(ctx.rect.x, ctx.rect.y, ctx.rect.width-yw, ctx.rect.height);
OHLCDataItem prev = null;
for (int i = first_bar; i < last_bar && i < data.size(); i++) {
OHLCDataItem di = data.get(i);
int x = (int) (i * em_width * x_unit_width); //em_width;
this.drawItem(ctx, x - em_width, x, prev, di); //, ctx.scaling, data.getMin());
// myi++;
prev = di;
}
}
boolean autoScroll = true;
int lastvpos = 0;
class ChartDef {
float height;
ChartType type;
OHLCData data;
Color bgcolor = null;
}
ArrayList<ChartDef> charts = new ArrayList<>();
void addChart(ChartDef d) {
charts.add(d);
}
void setupCharts() {
charts = new ArrayList<>();
ChartDef main = new ChartDef();
main.height = 0.8f;
main.type = ChartType.CANDLESTICK;
main.data = this.data;
//main.bgcolor =Color.WHITE;
addChart(main);
ChartDef vol = new ChartDef();
vol.height = 0.2f;
vol.type = ChartType.VOL;
vol.data = this.data;
// vol.bgcolor = Color.GRAY;
addChart(vol);
}
void drawAll(Graphics2D g) {
int pwidth = (int) (em_width * x_unit_width * (num_bars + 1)) + clip_bounds.width;
this.setPreferredSize(new Dimension(pwidth, gdim.height));
this.revalidate();
int h1 = 0;
int loops = 0;
for (ChartDef d : charts) {
switch (d.type) {
case VOL:
c_mm = d.data.getVolMinMax(first_bar, last_bar);
c_mm.setMin(0);
break;
default:
c_mm = d.data.getMinMax(first_bar, last_bar);
}
int cheight = gdim.height - (xl_height * 2) * em_width;
cheight = clip_bounds.height - xl_height * em_width;
int my = clip_bounds.height - em_height * xl_height;
g.setColor(Color.RED);
g.drawRect(clip_bounds.x,clip_bounds.y,clip_bounds.width,my);
int h = (int) (my * d.height);
c_rect = new Rectangle(0, h1, pwidth, h);
g.draw(c_rect);
System.out.printf("Nananan %d\n", loops++);
RenderCtx ctx = new RenderCtx();
ctx.rect = c_rect;
ctx.scaling = (float) c_rect.height / (c_mm.getMax() - c_mm.getMin());
ctx.min = c_mm.getMin();
ctx.g = g;
ctx.iwidth = (float) ((x_unit_width * em_width) * 0.9f);
this.ct = d.type;
logs = false;
c_mm.setLog(false);
if (d.bgcolor != null) {
Color cur = g.getColor();
ctx.g.setColor(d.bgcolor);
ctx.g.fillRect(ctx.rect.x, ctx.rect.y, ctx.rect.width, ctx.rect.height);
ctx.g.drawRect(ctx.rect.x, ctx.rect.y, ctx.rect.width, ctx.rect.height);
ctx.g.setColor(cur);
}
drawChart(ctx);
h1 = h1+h;
}
}
private void draw(Graphics2D g) {
if (data == null) {
return;
}
if (data.size() == 0) {
return;
}
// g.setColor(Color.RED);
// g.drawRect(0,0,gdim.width,gdim.height);
this.setupCharts();
num_bars = data.size();
// c_mm = data.getMinMax(first_bar, last_bar);
// if (c_mm == null) {
// return;
em_height = g.getFontMetrics().getHeight();
em_width = g.getFontMetrics().stringWidth("M");
XLegendDef xld = new XLegendDef();
this.drawXLegend(g, xld);
drawAll(g);
}
Dimension gdim;
private void draw2(Graphics2D g) {
if (data == null) {
return;
}
if (data.size() == 0) {
return;
}
num_bars = data.size();
c_mm = data.getMinMax(first_bar, last_bar);
if (c_mm == null) {
return;
}
em_height = g.getFontMetrics().getHeight();
em_width = g.getFontMetrics().stringWidth("M");
XLegendDef xld = new XLegendDef();
this.drawXLegend(g, xld);
int pwidth = (int) (em_width * x_unit_width * (num_bars + 1)) + clip_bounds.width;
// int phight = 400;
// phight=this.getVisibleRect().height;
this.setPreferredSize(new Dimension(pwidth, gdim.height));
this.revalidate();
int bww = (int) (data.size() * (this.x_unit_width * this.em_width));
int p0 = pwidth - clip_bounds.width - (clip_bounds.width - (int) (13 * em_width));
if (p0 < 0) {
p0 = 0;
}
JViewport vp = (JViewport) this.getParent();
Point pp = vp.getViewPosition();
Point cp = vp.getViewPosition();
if (autoScroll && this.lastvpos != cp.x) {
autoScroll = false;
}
if (!autoScroll && cp.x >= p0) {
autoScroll = true;
}
if (autoScroll) {
vp.setViewPosition(new Point(p0, 0));
lastvpos = p0;
}
int cheight = gdim.height - 6 * em_width;
int h = (int) (cheight * 0.8);
Rectangle r = new Rectangle(0, 0, pwidth, h);
c_rect = r;
RenderCtx ctx = new RenderCtx();
// c_rect.x = 0;
// c_rect.y = 50;
// c_rect.height = ;
ctx.rect = c_rect;
ctx.scaling = (float) r.height / (c_mm.getMax() - c_mm.getMin());
ctx.min = c_mm.getMin();
ctx.g = g;
ctx.iwidth = (float) ((x_unit_width * em_width) * 0.9f);
this.ct = ChartType.CANDLESTICK;
logs = true;
c_mm.setLog(true);
drawChart(ctx);
c_mm = data.getVolMinMax(first_bar, last_bar);
// c_mm.min = 0f;
c_mm.setMin(0);
int h1 = h + em_width;
h = (int) (cheight * 0.2);
r = new Rectangle(0, h1, pwidth, h);
c_rect = r;
// c_rect.x = 0;
// c_rect.y = 250;
// c_rect.height = 50;
ctx.rect = c_rect;
ctx.scaling = (float) r.height / (c_mm.getMax() - c_mm.getMin());
ctx.min = c_mm.getMin();
ctx.g = g;
ctx.iwidth = (float) ((x_unit_width * em_width) * 0.9f);
logs = false;
c_mm.setLog(false);
this.ct = ChartType.VOL;
drawChart(ctx);
}
private float c_font_height;
@Override
public final void paintComponent(Graphics g) {
if (Globals.se == null) {
return;
}
super.paintComponent(g);
// Calculate the number of pixels for 1 em
em_width = g.getFontMetrics().stringWidth("M");
this.gdim = this.getParent().getSize(gdim);
this.getParent().setPreferredSize(gdim);
//Object o = this.getParent();
JViewport vp = (JViewport) this.getParent();
//this.clip_bounds=g.getClipBounds();
this.clip_bounds = vp.getViewRect();
first_bar = (int) (clip_bounds.x / (this.x_unit_width * this.em_width));
last_bar = 1 + (int) ((clip_bounds.x + clip_bounds.width - (this.y_legend_width * em_width)) / (this.x_unit_width * this.em_width));
// num_bars = data.size(); // + (int) (clip_bounds.width / (this.x_unit_width * this.em_width))+5;
// num_bars=1;
c_font_height = g.getFontMetrics().getHeight();
draw((Graphics2D) g);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
ctxMenu = new javax.swing.JPopupMenu();
compMenu = new javax.swing.JMenu();
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
compMenu.setText("Compression");
ctxMenu.add(compMenu);
jCheckBoxMenuItem1.setMnemonic('l');
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("Log Scale");
jCheckBoxMenuItem1.setToolTipText("");
jCheckBoxMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuItem1ActionPerformed(evt);
}
});
ctxMenu.add(jCheckBoxMenuItem1);
setBackground(java.awt.Color.white);
setBorder(null);
setOpaque(false);
setPreferredSize(new java.awt.Dimension(300, 300));
setRequestFocusEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 589, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void jCheckBoxMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jCheckBoxMenuItem1ActionPerformed
protected void setCompression(int timeFrame) {
javax.swing.SwingUtilities.invokeLater(() -> {
data = Globals.se.getOHLCdata(timeFrame);
invalidate();
repaint();
});
}
@Override
public void UpdateQuote(Quote q) {
// System.out.print("Quote Received\n");
// this.realTimeAdd(q.time, (float) q.price, (float)q.volume);
// data.realTimeAdd(q.time, (float) q.price, (float) q.volume);
// this.invalidate();
this.repaint();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu compMenu;
private javax.swing.JPopupMenu ctxMenu;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
// End of variables declaration//GEN-END:variables
} |
package eco;
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class NameGen {
public static String[] uno = new String[] {
"new",
"wam",
"will",
"notting",
"burn"
};
public static String[] dos = new String[] {
"ton",
"stead",
"ham",
"land",
"ness",
"port"
};
public static String[] tres = new String[] {
"ton",
"stead",
"ham",
"new",
"land",
"ness",
"port",
"arden",
"wam",
"burn",
"don",
"phil",
"will"
};
public static String[] consonants = new String[] {
"b",
"c",
"d",
"f",
"g",
"k",
"l",
"m",
"n",
"n",
"n",
"n",
"p",
"q",
"r",
"s",
"t",
"r",
"s",
"t",
"r",
"s",
"t",
"r",
"s",
"t",
"v",
"th",
"sh",
"ch",
"ph",
"phil",
"ing"
};
public static String[] vowels = new String[] {
"a",
"e",
"e",
"e",
"i",
"o",
"u",
"y",
"a",
"e",
"e",
"i",
"o",
"u",
"y",
"oo",
"ue",
"ee",
};
public static String[] suffixes = new String[] {
"stan",
"grad",
"bad",
"ville",
"stead",
" On the Sea",
"land",
"wood",
"field",
"shire",
"burg",
"furt",
"ham",
"dale",
"port",
"ford",
"ia",
"mare",
"polis",
"ago",
"uim"
};
public static String[] spanishAdjectives = new String[]{
"blancos",
"amarillos",
"dorados",
"gordos",
"pequenos",
"grandes",
"altos",
"llenos"
};
public static String[] spanishWordsO = new String[]{
"gato",
"globo",
"asalto",
"pato",
"inodoro",
"malo",
"aguacate",
"chicle",
"bajo",
"juego",
"jugo",
"rayo",
"ojo",
"rojo",
"lago",
"camino",
"infierno",
"fuego",
"rio",
"lobo",
"oro",
"torrente",
"veneno",
"pulpo",
"caballero",
"pajaro",
"plato",
"trono",
"abalorio",
"abandono",
"ajo",
"banco",
"bando",
"borujo",
"cacho",
"cigarillo",
"churro",
"dinero",
"durazno",
"enimigo",
"epico",
"exclusivo",
"mercado",
"mercado",
"burro",
"fracaso",
"conflicto",
"turbulento",
"cero",
"mundo"
};
public static String[] spanishWordsA = new String[] {
"nube",
"pintura",
"nada",
"tierra",
"ropa",
"mantequilla",
"iglesia",
"mano",
"montana",
"tortilla",
"ola",
"ardilla", //squirrel
"vibora", //viper
"ven",
"bruja",
"espada",
"piedra",
"joya",
"babosa",
"calavera",
"defensa",
"elitista",
"mesa",
"medusa",
"abeja",
"paloma",
"calabaza",
"soldadura",
"corona"
};
public static String generateRandom(){
String name = "";
int num = randInt(1,4);
switch (num){
case 1: name = generateSpanish();
break;
case 2: name = generateSyllables();
break;
case 3: name = generateJapanese();
break;
case 4: name = generateCastle(); // + ".castle";
break;
}
return name;
}
public static String generateSpanish(){
boolean gender = random.nextBoolean();
boolean plurality = random.nextBoolean();
boolean adjective = random.nextBoolean();
int num = randInt(1, spanishAdjectives.length - 1);
String name = "";
if(gender){
if(plurality){
name = "Los " + spanishWordsO[randInt(1, spanishWordsO.length - 1)] + "s";
name = name.substring(0,4) + name.substring(4,5).toUpperCase() + name.substring(5);
if(adjective){
name = name + " " + spanishAdjectives[num].substring(0,1).toUpperCase() + spanishAdjectives[num].substring(1);
}
}
else{
name = "El " + spanishWordsO[randInt(1, spanishWordsO.length - 1)];
name = name.substring(0,3) + name.substring(3,4).toUpperCase() + name.substring(4);
if(adjective){
name = name + " " + spanishAdjectives[num].substring(0,1).toUpperCase() + spanishAdjectives[num].substring(1, spanishAdjectives[num].length() - 1);
}
}
}
else{
if(plurality){
name = "Las " + spanishWordsA[randInt(1, spanishWordsA.length - 1)] + "s";
name = name.substring(0,4) + name.substring(4,5).toUpperCase() + name.substring(5);
if(adjective){
name = name + " " + spanishAdjectives[num].substring(0,1).toUpperCase() + spanishAdjectives[num].substring(1, spanishAdjectives[num].length() - 2) + "as";
}
}
else{
name = "La " + spanishWordsA[randInt(1, spanishWordsA.length - 1)];
name = name.substring(0,3) + name.substring(3,4).toUpperCase() + name.substring(4);
if(adjective){
name = name + " " + spanishAdjectives[num].substring(0,1).toUpperCase() + spanishAdjectives[num].substring(1, spanishAdjectives[num].length() - 2) + "a";
}
}
}
name = name.substring(0,1).toUpperCase() + name.substring(1);
return name;
}
public static String[] noveltyPrefixes = new String[] {
"Connor's",
"Phil's",
"Nate's",
"Will's",
"Mr. Drew's",
"Krugman's"
};
public static String[] noveltySuffixes = new String[] {
"of Bailey",
"of Heikoop",
"of Delgado",
"of Sidley-Parker",
"de Leon"
};
public static String[] castleSuffixes = new String[] {
"fard",
"ton",
"wood",
"ham", "hampton",
"bury",
"ester", "aster",
"chester",
"seed",
"hurst",
"ville",
"stow",
"don",
"worth",
"aple",
"minster",
"more",
"roth",
"wick",
"port",
"field",
"dill",
"sham",
"hollow",
"borough",
"dale",
"pass",
"cove",
"tail",
"cliff",
"born", "borne", "bourne",
"marsh",
"firth",
"isle",
"broth",
"well",
"mouth",
"fall",
"lock",
"shop", "shoppe", "shoppe"
};
public static String[] castlePrefixes = new String[] {
"wolf",
"deer",
"weasal",
"sea",
"grist",
"axe",
"cone",
"hammer",
"strath",
"mill",
"horn",
"stone",
"west", "north", "south",
"beck",
"wake",
"holly",
"white", "black", "blue", "grey", "silver", "iron", "yellow", "brown", "gold", "bronze",
"bull",
"finch",
"dragon", "draco",
"trout",
"dry",
"sharp",
"cray",
"long", "short",
"aber",
"ruther",
"cardinal",
"arrow", "dagger", "spears", "cannon", "pike",
"siege",
"boat",
"salt",
"bell",
"dire",
"hill",
"leaf", "vine", "tree", "ivy",
"garth",
"apple",
"ample",
"skag",
"smoke",
"berx",
"wind",
"star",
"sun",
"moon",
"frost",
"bleak",
"air",
"brae",
"dawn",
"weld",
"hull", "hell",
"saxon",
"aqua",
"death",
"mir",
"warring",
"ram",
"deer",
"lizard",
"card",
"fire", "flame", "blaze", "char", "ember", "flare",
"ox",
"mag",
"veil", "vail",
"mount",
"valley",
"heaven",
"stein",
"fortran",
"cobol",
"tiger"
};
public static String[] castleSynonyms = new String[] {
"stronghold",
"acropolis",
"citadel",
"fortress",
"establishment",
"fortification",
"keep",
"hold",
"manor",
"mansion",
"palace",
"safehold",
"villa",
"tower",
"bastion",
"castle",
"garrison",
"rampart",
"abode",
"residency",
"legal residence",
"pad",
"estate"
};
public static String[] castlePreSynonyms = new String[]{
"fort",
"camp",
"castle"
};
public static String[] castleAdjectives = new String[] {
"big",
"great",
"soaring",
"towering",
"elevated",
"giant",
"skyscraping",
"shining",
"glimmering",
"lustrous",
"radiant",
"immortal",
"enduring",
"everlasting",
"imperishable",
"indestructible",
"invincible",
"invulnerable",
"impenetrable",
"decrepit",
"deteriorated",
"crippled",
"battered",
"weather-beaten"
};
public static String[] japaneseKatakana = new String[] {
"a",
"e",
"i",
"o",
"u",
"ya",
"yu",
"yo",
"ka",
"ki",
"ku",
"ke",
"ko",
"sa",
"si",
"su",
"se",
"so",
"ta",
"ti",
"tu",
"te",
"to",
"na",
"ni",
"nu",
"ne",
"no",
"ha",
"hi",
"hu",
"he",
"ho",
"ma",
"mi",
"mu",
"me",
"mo",
"ra",
"ri",
"ru",
"re",
"ro",
"wa",
"wi",
"wu",
"we",
"wo",
"ga",
"gi",
"gu",
"ge",
"go",
"za",
"zi",
"zu",
"ze",
"zo",
"da",
"di",
"du",
"de",
"do"
};
public static String[] historicalLeaders = new String[] {
"Napoleon",
"Genghis",
"Pizarro",
"Pachacuti",
"Claudius",
"Ghandi",
"Mandela",
"Alexander the Great",
"Solomon",
"Washington",
"Henry VIII"
};
public static Random random = new Random();
public static void list(int loops){
for(int i = 0; i < loops; i++){
System.out.println(generateRandom());
}
System.out.println("\n\n\n\n");
for(int i = 0; i < loops; i++){
System.out.println(generateCastle());
}
System.out.println("===== DONE!!! ======");
}
public static String generateCastle(){
int length = randInt(1,3);
int choice = randInt(1,20);
int otherChoice = randInt(1,20);
int otherOtherChoice = randInt(1,6);
int preOrSuff = randInt(1,10);
String name = "";
if(choice == 1){
int num = randInt(1, noveltyPrefixes.length - 1);
name = name + noveltyPrefixes[num].substring(0,1).toUpperCase() + noveltyPrefixes[num].substring(1) + " ";
}
else if(choice == 2){
int num = randInt(1, historicalLeaders.length - 1);
name = name + "The " + historicalLeaders[num].substring(0,1).toUpperCase() + historicalLeaders[num].substring(1) + " ";
}
if (otherOtherChoice == 1){
int num = randInt(1, castleAdjectives.length - 1);
name = name + castleAdjectives[num].substring(0,1).toUpperCase() + castleAdjectives[num].substring(1) + " ";
}
if(preOrSuff == 1){
int num = randInt(1, castlePreSynonyms.length - 1);
name = name + castlePreSynonyms[num].substring(0,1).toUpperCase() + castlePreSynonyms[num].substring(1) + " ";
}
int num = randInt(1, castlePrefixes.length - 1);
name = name + castlePrefixes[num].substring(0,1).toUpperCase() + castlePrefixes[num].substring(1);
num = randInt(1, castleSuffixes.length - 1);
name = name + castleSuffixes[num] + " ";
if(preOrSuff > 1){
num = randInt(1, castleSynonyms.length - 1);
name = name + castleSynonyms[num].substring(0,1).toUpperCase() + castleSynonyms[num].substring(1) + " ";
}
if(otherChoice == 1){
num = randInt(1, noveltySuffixes.length - 1);
name = name + noveltySuffixes[num].substring(0,1).toUpperCase() + noveltySuffixes[num].substring(1);
}
name = name.substring(0,1).toUpperCase() + name.substring(1);
return name;
}
/*public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ten random names below!");
for(int i = 0; i < 10; i++){
//System.out.println(generate(uno, dos, tres));
System.out.println(generateSyllables(consonants, vowels, suffixes));
}
}
*/
public static int randInt(int min, int max) { //Returns a random number between min and max.
return min + random.nextInt((max + 1)- min);
}
public static String generate(){
int length = randInt(0,1);
String name = "";
for(int i = 0; i <= length; i++){
if(i == 0)
name = name + uno[randInt(1, uno.length - 1)];
else
name = name + dos[randInt(1, dos.length - 1)];
}
name = name.substring(0,1).toUpperCase() + name.substring(1);
return name ;
}
public static String generateSyllables(){
int length = randInt(1,2);
String name = "";
for(int i = 0; i <= length; i++){
if(i == 0)
name = name + consonants[randInt(1, consonants.length - 1)] + vowels[randInt(0, vowels.length - 1)];
else
name = name + consonants[randInt(1, consonants.length - 1)] + vowels[randInt(0, vowels.length - 1)];
}
name = name.substring(0,1).toUpperCase() + name.substring(1);
int chance = (randInt(1,100));
if(chance < 25){
name = name + suffixes[randInt(0, suffixes.length - 1)];
}
else if (chance >= 25 && chance < 75){
name = name + consonants[randInt(0, consonants.length -1)];
}
return name ;
}
public static String generateJapanese(){
int length = randInt(1,3);
String name = "";
for(int i = 0; i <= length; i++){
name = name + japaneseKatakana[randInt(1, japaneseKatakana.length - 1)];
}
name = name.substring(0,1).toUpperCase() + name.substring(1);
return name;
}
} |
package edu.stuy;
import edu.stuy.commands.*;
import edu.stuy.commands.tuning.ShooterManualSpeed;
import edu.stuy.subsystems.Shooter;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.DriverStationEnhancedIO;
import edu.wpi.first.wpilibj.DriverStationEnhancedIO.EnhancedIOException;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
public class OI {
private Joystick leftStick;
private Joystick rightStick;
private Joystick shooterStick;
private Joystick debugBox;
public static final int DISTANCE_BUTTON_AUTO = 1;
public static final int DISTANCE_BUTTON_FAR = 2;
public static final int DISTANCE_BUTTON_FENDER_WIDE = 3;
public static final int DISTANCE_BUTTON_FENDER_NARROW = 4;
public static final int DISTANCE_BUTTON_FENDER_SIDE = 5;
public static final int DISTANCE_BUTTON_FENDER = 6;
public static final int DISTANCE_BUTTON_STOP = 7;
private DriverStationEnhancedIO enhancedIO;
// EnhancedIO digital input
private static final int ACQUIRER_IN_SWITCH_CHANNEL = 1;
private static final int ACQUIRER_OUT_SWITCH_CHANNEL = 2;
private static final int BIT_1_CHANNEL = 3;
private static final int BIT_2_CHANNEL = 4;
private static final int BIT_3_CHANNEL = 5;
private static final int SHOOT_BUTTON_CHANNEL = 6;
private static final int OVERRIDE_BUTTON_CHANNEL = 7;
private static final int CONVEYOR_IN_SWITCH_CHANNEL = 8;
private static final int CONVEYOR_OUT_SWITCH_CHANNEL = 9;
public int distanceButton;
public double distanceInches;
public boolean topHoop = true;
// EnhancedIO digital output
private static final int DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL = 10;
private static final int DISTANCE_BUTTON_FAR_LIGHT_CHANNEL = 11;
private static final int DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL = 12;
private static final int DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL = 13;
private static final int DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL = 14;
private static final int DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL = 15;
private static final int DISTANCE_BUTTON_STOP_LIGHT_CHANNEL = 16;
// EnhancedIO analog input
private static final int DISTANCE_BUTTONS_CHANNEL = 1;
private static final int SPEED_TRIM_POT_CHANNEL = 2;
private static final int SPIN_TRIM_POT_CHANNEL = 3;
private static final int MAX_ANALOG_CHANNEL = 4;
public OI() {
if (!Devmode.DEV_MODE) {
enhancedIO = DriverStation.getInstance().getEnhancedIO();
}
leftStick = new Joystick(RobotMap.LEFT_JOYSTICK_PORT);
rightStick = new Joystick(RobotMap.RIGHT_JOYSTICK_PORT);
shooterStick = new Joystick(RobotMap.SHOOTER_JOYSTICK_PORT);
debugBox = new Joystick(RobotMap.DEBUG_BOX_PORT);
distanceButton = DISTANCE_BUTTON_STOP;
distanceInches = 0;
try {
if (!Devmode.DEV_MODE) {
enhancedIO.setDigitalConfig(BIT_1_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(BIT_2_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(BIT_3_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(ACQUIRER_IN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(ACQUIRER_OUT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(CONVEYOR_IN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(CONVEYOR_OUT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(SHOOT_BUTTON_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(OVERRIDE_BUTTON_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp);
enhancedIO.setDigitalConfig(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput);
enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput);
enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput);
enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput);
enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput);
enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput);
enhancedIO.setDigitalConfig(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput);
}
} catch (EnhancedIOException e) {
}
if (!Devmode.DEV_MODE) {
new JoystickButton(leftStick, 1).whileHeld(new ShooterMoveFlyWheel(distanceInches, Shooter.speedsTopHoop));
new JoystickButton(rightStick, 1).whenPressed(new DrivetrainSetGear(false));
new JoystickButton(rightStick, 2).whenPressed(new DrivetrainSetGear(true));
new JoystickButton(leftStick, 1).whenPressed(new TusksExtend());
new JoystickButton(leftStick, 2).whenPressed(new TusksRetract());
// OI box switches
new DigitalIOButton(ACQUIRER_IN_SWITCH_CHANNEL).whileHeld(new AcquirerAcquire());
new DigitalIOButton(ACQUIRER_OUT_SWITCH_CHANNEL).whileHeld(new AcquirerReverse());
new DigitalIOButton(CONVEYOR_IN_SWITCH_CHANNEL).whileHeld(new ConveyManual());
new DigitalIOButton(CONVEYOR_OUT_SWITCH_CHANNEL).whileHeld(new ConveyReverseManual());
new DigitalIOButton(SHOOT_BUTTON_CHANNEL).whileHeld(new ConveyAutomatic());
new JoystickButton(shooterStick, 1).whileHeld(new ConveyAutomatic());
new JoystickButton(shooterStick, 2).whileHeld(new AcquirerAcquire());
new JoystickButton(shooterStick, 3).whileHeld(new ConveyManual());
new JoystickButton(shooterStick, 4).whileHeld(new ConveyReverseManual());
new JoystickButton(shooterStick, 5).whileHeld(new AcquirerReverse());
// 6 and 7 are used for top and mid hoop respectively (see getHeightFromButton())
new JoystickButton(shooterStick, 8).whenPressed(new ShooterStop());
// 9-11 are used for fender, fender side, and max speed, in that order
// see getDistanceButton()
}
}
// Copied from last year's DesDroid code.
public double getRawAnalogVoltage() {
try {
return enhancedIO.getAnalogIn(DISTANCE_BUTTONS_CHANNEL);
}
catch (EnhancedIOException e) {
return 0;
}
}
public double getMaxVoltage() {
try {
return enhancedIO.getAnalogIn(MAX_ANALOG_CHANNEL);
}
catch (EnhancedIOException e) {
return 2.2;
}
}
/**
* Determines which height button is pressed. All (7 logically because
* side buttons are wired together) buttons are wired by means of
* resistors to one analog input. Depending on the button that is pressed, a
* different voltage is read by the analog input. Each resistor reduces the
* voltage by about 1/7 the maximum voltage.
*
* @return An integer value representing the distance button that was pressed.
* If a Joystick button is being used, that will returned. Otherwise, the
* button will be returned from the voltage (if it returns 0, no button is pressed).
*/
public int getDistanceButton() {
if (shooterStick.getRawButton(8)) {
distanceButton = DISTANCE_BUTTON_STOP;
}
if (shooterStick.getRawButton(9)) {
distanceButton = DISTANCE_BUTTON_FENDER;
}
if (shooterStick.getRawButton(10)) {
distanceButton = DISTANCE_BUTTON_FENDER_SIDE;
}
if (shooterStick.getRawButton(11)) {
distanceButton = DISTANCE_BUTTON_FAR;
}
distanceButton = (int) ((getRawAnalogVoltage() / (getMaxVoltage() / 7)) + 0.5);
return distanceButton;
}
/**
* Takes the distance button that has been pressed, and finds the distance for
* the shooter to use.
* @return distance for the shooter.
*/
public double getDistanceFromHeightButton(){
switch(distanceButton){
case DISTANCE_BUTTON_AUTO:
distanceInches = CommandBase.drivetrain.getSonarDistance_in();
break;
case DISTANCE_BUTTON_FAR:
distanceInches = 725; // TODO: Max distance to max speed?
break;
case DISTANCE_BUTTON_FENDER_WIDE:
distanceInches = Shooter.distances[Shooter.FENDER_LONG_INDEX];
break;
case DISTANCE_BUTTON_FENDER_NARROW:
distanceInches = Shooter.distances[Shooter.FENDER_WIDE_INDEX];
break;
case DISTANCE_BUTTON_FENDER_SIDE:
distanceInches = Shooter.distances[Shooter.FENDER_SIDE_INDEX];
break;
case DISTANCE_BUTTON_FENDER:
distanceInches = Shooter.distances[Shooter.FENDER_INDEX];
break;
case DISTANCE_BUTTON_STOP:
distanceInches = 0;
break;
default:
break;
}
return distanceInches;
}
public double[] getHeightFromButton() {
if (shooterStick.getRawButton(7)) {
topHoop = false;
}
if (shooterStick.getRawButton(6)) {
topHoop = true;
}
return topHoop ? Shooter.speedsMiddleHoop : Shooter.speedsTopHoop;
}
// Copied from last year's DesDroid code.
public Joystick getLeftStick() {
return leftStick;
}
public Joystick getRightStick() {
return rightStick;
}
public Joystick getDebugBox() {
return debugBox;
}
public boolean getShootOverrideButton() {
try {
return !enhancedIO.getDigital(OVERRIDE_BUTTON_CHANNEL) || shooterStick.getRawButton(8);
} catch (EnhancedIOException ex) {
return shooterStick.getRawButton(8);
}
}
/**
* Use a thumb wheel switch to set the autonomous mode setting.
* @return Autonomous setting to run.
*/
public int getAutonSetting() {
try {
int switchNum = 0;
int[] binaryValue = new int[3];
boolean[] dIO = {!enhancedIO.getDigital(BIT_1_CHANNEL), !enhancedIO.getDigital(BIT_2_CHANNEL), !enhancedIO.getDigital(BIT_3_CHANNEL)};
for (int i = 0; i < 3; i++) {
if (dIO[i]) {
binaryValue[i] = 1;
}
else {
binaryValue[i] = 0;
}
}
binaryValue[0] *= 4; // convert all binaryValues to decimal values
binaryValue[1] *= 2;
for (int i = 0; i < 3; i++) { // finish binary -> decimal conversion
switchNum += binaryValue[i];
}
return switchNum;
}
catch (EnhancedIOException e) {
return -1; // Do nothing in case of failure
}
}
public int getDebugBoxBinaryAutonSetting() {
int switchNum = 0;
int[] binaryValue = new int[4];
boolean[] dIO = {debugBox.getRawButton(1), debugBox.getRawButton(2), debugBox.getRawButton(3), debugBox.getRawButton(4)};
for (int i = 0; i < 4; i++) {
if (dIO[i]) {
binaryValue[i] = 1;
}
else {
binaryValue[i] = 0;
}
}
binaryValue[0] *= 8; // convert all binaryValues to decimal values
binaryValue[1] *= 4;
binaryValue[2] *= 2;
for (int i = 0; i < 4; i++) { // finish binary -> decimal conversion
switchNum += binaryValue[i];
}
return switchNum;
}
public double getSpeedPot() {
try {
return enhancedIO.getAnalogIn(SPEED_TRIM_POT_CHANNEL);
} catch (EnhancedIOException ex) {
return 0.0;
}
}
public double getSpinPot() {
try {
return enhancedIO.getAnalogIn(SPIN_TRIM_POT_CHANNEL);
} catch (EnhancedIOException ex) {
return 0.0;
}
}
/**
* Turns on specified light on OI.
* @param lightNum
*/
public void setLight(int lightNum) {
turnOffLights();
try {
enhancedIO.setDigitalOutput(lightNum, true);
}
catch (EnhancedIOException e) {
}
}
/**
* Turns all lights off.
*/
public void turnOffLights(){
try {
enhancedIO.setDigitalOutput(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL, false);
enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, false);
enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, false);
enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, false);
enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, false);
enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, false);
enhancedIO.setDigitalOutput(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, false);
}
catch (EnhancedIOException e) {
}
}
/**
* Meant to be called continuously to update the lights on the OI board.
* Depending on which button has been pressed last (which distance is
* currently set), that button will be lit.
*/
public void updateLights(){
switch(distanceButton){
case DISTANCE_BUTTON_AUTO:
setLight(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL);
break;
case DISTANCE_BUTTON_FAR:
setLight(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL);
break;
case DISTANCE_BUTTON_FENDER_WIDE:
setLight(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL);
break;
case DISTANCE_BUTTON_FENDER_NARROW:
setLight(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL);
break;
case DISTANCE_BUTTON_FENDER_SIDE:
setLight(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL);
break;
case DISTANCE_BUTTON_FENDER:
setLight(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL);
break;
case DISTANCE_BUTTON_STOP:
setLight(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL);
break;
default:
turnOffLights();
break;
}
}
} |
package devopsdistilled.operp;
public class Main {
public static void main(String[] args) {
System.out.println("OpERP");
System.out.println("Enterprise Resource Planning for Distribution Companies");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.