answer
stringlengths 17
10.2M
|
|---|
package jamex.link;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.jms.Message;
import javax.jms.MessageListener;
import static org.junit.Assert.*;
final class MessageCollector
implements MessageListener
{
private static final int MAX_MESSAGE_COUNT = 10;
private static final long DEFAULT_WAIT = 100L;
private final LinkedBlockingQueue<Message> m_messages = new LinkedBlockingQueue<Message>( MAX_MESSAGE_COUNT );
@Override
public void onMessage( final Message message )
{
m_messages.add( message );
}
Collection<Message> expectMessageCount( final int expectedMessageCount )
throws InterruptedException
{
return expectMessageCount( expectedMessageCount, DEFAULT_WAIT );
}
Collection<Message> expectMessageCount( final int expectedMessageCount, final long maxWait )
throws InterruptedException
{
final LinkedList<Message> results = new LinkedList<Message>();
final long start = System.currentTimeMillis();
long now;
while( results.size() < expectedMessageCount &&
( ( now = System.currentTimeMillis() ) < start + maxWait ) )
{
final long waitTime = Math.max( 1, start + maxWait - now );
final Message message = m_messages.poll( waitTime, TimeUnit.MILLISECONDS );
results.add( message );
}
assertEquals( "Expected message count", expectedMessageCount, results.size() );
return results;
}
}
|
package com.tripadvisor.seekbar;
import android.content.Context;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import com.tripadvisor.seekbar.util.Utils;
import org.jetbrains.annotations.Nullable;
import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;
import org.joda.time.Interval;
import java.util.Locale;
import static com.tripadvisor.seekbar.util.Utils.FontType.BOLD;
import static com.tripadvisor.seekbar.util.Utils.FontType.REGULAR;
import static com.tripadvisor.seekbar.util.Utils.SIMPLE_DATE_FORMAT_AM_PM;
import static com.tripadvisor.seekbar.util.Utils.SIMPLE_DATE_FORMAT_HOURS;
import static com.tripadvisor.seekbar.util.Utils.SIMPLE_DATE_FORMAT_MERIDIAN;
import static com.tripadvisor.seekbar.CircularClockSeekBar.ClockRangeStatus.DIFFERENT_DAY_OF_WEEK;
import static com.tripadvisor.seekbar.CircularClockSeekBar.ClockRangeStatus.INVALID_RANGE;
import static com.tripadvisor.seekbar.CircularClockSeekBar.ClockRangeStatus.VALID_RANGE;
public class ClockView extends LinearLayout {
public static final float LETTER_SPACING = -3.0f;
private final LetterSpacingTextView mTimeText;
private final LetterSpacingTextView mTimeMeridianText;
private final RobotoTextView mTimeWeekDayText;
private final CircularClockSeekBar mCircularClockSeekBar;
private Interval mTimeInterval;
private DateTime mOriginalTime;
private final boolean mIs24HourFormat;
private DateTime mNewCurrentTime;
private int mCurrentValidProgressDelta;
private DateTime mCurrentValidTime;
private ClockTimeUpdateListener mClockTimeUpdateListener;
public ClockView(Context context, AttributeSet attrs) {
super(context, attrs);
mClockTimeUpdateListener = new ClockTimeUpdateListener() {
@Override
public void onClockTimeUpdate(ClockView clockView, DateTime currentTime) {
}
};
mIs24HourFormat = DateFormat.is24HourFormat(context);
final View view = LayoutInflater.from(context).inflate(R.layout.clock_view, this);
mTimeText = (LetterSpacingTextView) view.findViewById(R.id.time_text_view);
mTimeMeridianText = (LetterSpacingTextView) view.findViewById(R.id.time_meredian_text_view);
mTimeWeekDayText = (RobotoTextView) view.findViewById(R.id.time_week_day_text);
if (!isInEditMode()) {
mTimeText.setTypeface(Utils.getRobotoTypeface(context, BOLD));
mTimeText.setLetterSpacing(LETTER_SPACING);
mTimeMeridianText.setTypeface(Utils.getRobotoTypeface(context, REGULAR));
mTimeMeridianText.setLetterSpacing(LETTER_SPACING);
}
mCircularClockSeekBar = (CircularClockSeekBar) view.findViewById(R.id.clock_seek_bar);
mCircularClockSeekBar.setSeekBarChangeListener(new CircularClockSeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(CircularClockSeekBar seekBar, int progress, boolean fromUser) {
updateProgressWithDelta(seekBar.getProgressDelta());
}
@Override
public void onStartTrackingTouch(CircularClockSeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(CircularClockSeekBar seekBar) {
// snap to correct position
if (mTimeInterval.contains(mNewCurrentTime)) {
// snap to nearest hour.
int progressDelta = (int) (mCircularClockSeekBar.getAngle() % 30);
if (progressDelta != 0) {
// snap either to previous/next hour
mCircularClockSeekBar.roundToNearestDegree(30);
} else {
// we are trigering onClockTimeUpdate because the user was perfect and moved the
// clock by exact multiple of 30 degrees so there is no animation and the time is still
// within valid time interval
mClockTimeUpdateListener.onClockTimeUpdate(ClockView.this, mNewCurrentTime);
}
} else {
// slide-animate back or forward
mCircularClockSeekBar.animateToDelta(mCircularClockSeekBar.getProgressDelta(), mCurrentValidProgressDelta);
setClockText(mCurrentValidTime);
}
}
@Override
public void onAnimationComplete(CircularClockSeekBar seekBar) {
if (mTimeInterval != null && mNewCurrentTime != null
&& mTimeInterval.contains(mNewCurrentTime)) {
mClockTimeUpdateListener.onClockTimeUpdate(ClockView.this, mNewCurrentTime);
}
}
});
}
public interface ClockTimeUpdateListener{
public void onClockTimeUpdate(ClockView clockView, DateTime currentTime);
}
private void updateProgressWithDelta(int progressDelta) {
// 1 deg = 2 min
mNewCurrentTime = mOriginalTime.plusMinutes(progressDelta * 2);
setClockText(mNewCurrentTime);
if (mTimeInterval != null && mNewCurrentTime != null
&& mTimeInterval.contains(mNewCurrentTime)) {
mCurrentValidProgressDelta = progressDelta;
mCurrentValidTime = mNewCurrentTime.minusMinutes(progressDelta * 2);
}
}
private void setClockText(DateTime newCurrentTime) {
if (mIs24HourFormat) {
mTimeText.setText(SIMPLE_DATE_FORMAT_HOURS.format(newCurrentTime.toDate()));
mTimeMeridianText.setText(R.string.hrs);
} else {
mTimeText.setText(SIMPLE_DATE_FORMAT_AM_PM.format(newCurrentTime.toDate()));
mTimeMeridianText.setText(SIMPLE_DATE_FORMAT_MERIDIAN.format(newCurrentTime.toDate()).toLowerCase(Locale.US));
}
setSeekBarStatus(newCurrentTime);
}
private void setSeekBarStatus(DateTime newCurrentTime) {
if (mTimeInterval.contains(newCurrentTime)) {
if (newCurrentTime.getDayOfWeek() == mTimeInterval.getStart().getDayOfWeek()) {
mCircularClockSeekBar.setSeekBarStatus(VALID_RANGE);
mTimeWeekDayText.setVisibility(GONE);
} else {
mCircularClockSeekBar.setSeekBarStatus(DIFFERENT_DAY_OF_WEEK);
mTimeWeekDayText.setVisibility(VISIBLE);
mTimeWeekDayText.setText(newCurrentTime.toString("EEE"));
}
} else {
mCircularClockSeekBar.setSeekBarStatus(INVALID_RANGE);
mTimeWeekDayText.setVisibility(GONE);
}
}
public void setBounds(DateTime minTime, DateTime maxTime, boolean isMaxClock) {
// NOTE: To show correct end time on clock, since the Interval.contains() checks for
// millisInstant >= thisStart && millisInstant < thisEnd
// however we want
// millisInstant >= thisStart && millisInstant <= thisEnd
maxTime = maxTime.plusMillis(1);
mTimeInterval = new Interval(minTime, maxTime);
maxTime = maxTime.minusMillis(1);
if (isMaxClock) {
mOriginalTime = maxTime;
mCurrentValidTime = maxTime;
int hourOfDay = maxTime.get(DateTimeFieldType.clockhourOfDay()) % 12;
mCircularClockSeekBar.setProgress(hourOfDay * 10);
setClockText(mOriginalTime);
} else {
mOriginalTime = minTime;
mCurrentValidTime = minTime;
int hourOfDay = minTime.get(DateTimeFieldType.clockhourOfDay()) % 12;
mCircularClockSeekBar.setProgress(hourOfDay * 10);
setClockText(mOriginalTime);
}
}
@Nullable
@Override
public CharSequence getContentDescription() {
return String.format("%s%s", mTimeText.getText(), mTimeMeridianText.getText());
}
public void setClockTimeUpdateListener(ClockTimeUpdateListener clockTimeUpdateListener) {
mClockTimeUpdateListener = clockTimeUpdateListener;
}
}
|
package scal.io.liger.view;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.joanzapata.android.iconify.IconDrawable;
import com.joanzapata.android.iconify.Iconify;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import scal.io.liger.Constants;
import scal.io.liger.MainActivity;
import scal.io.liger.R;
import scal.io.liger.model.Card;
import scal.io.liger.model.ClipCard;
import scal.io.liger.model.ClipMetadata;
import scal.io.liger.model.FullMetadata;
import scal.io.liger.model.MediaFile;
import scal.io.liger.model.ReviewCard;
import scal.io.liger.model.StoryPath;
/**
* ReviewCardView allows the user to review the order of clips
* attached to a ReviewCard's Story Path. This card will also support
* adding narration, changing the order of clips, and jumbling the order.
*/
public class ReviewCardView implements DisplayableCard {
public static final String TAG = "ReviewCardView";
private ReviewCard mCardModel;
private Context mContext;
private String mMedium;
/** Current Narration State. To change use
* {@link #changeRecordNarrationStateChanged(scal.io.liger.view.ReviewCardView.RecordNarrationState)}
*/
private RecordNarrationState mRecordNarrationState = RecordNarrationState.READY;
/** The ReviewCard Narration Dialog State */
static enum RecordNarrationState {
/** Done / Record Buttons present */
READY,
/** Recording countdown then Pause / Stop Buttons present */
RECORDING,
/** Recording paused. Resume / Stop Buttons present */
PAUSED,
/** Recording stopped. Done / Redo Buttons present */
STOPPED
}
public ReviewCardView(Context context, Card cardModel) {
Log.d("RevieCardView", "constructor");
mContext = context;
mCardModel = (ReviewCard) cardModel;
}
@Override
public View getCardView(final Context context) {
Log.d("RevieCardView", "getCardView");
if (mCardModel == null) {
return null;
}
View view = LayoutInflater.from(context).inflate(R.layout.card_review, null);
final ImageView ivCardPhoto = ((ImageView) view.findViewById(R.id.iv_thumbnail));
final TextureView tvCardVideo = ((TextureView) view.findViewById(R.id.tv_card_video));
Button btnJumble = ((Button) view.findViewById(R.id.btn_jumble));
Button btnOrder = ((Button) view.findViewById(R.id.btn_order));
Button btnNarrate = ((Button) view.findViewById(R.id.btn_narrate));
Button btnPublish = ((Button) view.findViewById(R.id.btn_publish));
btnJumble.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO
}
});
btnOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaCards.size() > 0)
Util.showOrderMediaPopup((Activity) mContext, mMedium, mMediaCards);
else
Toast.makeText(mContext, mContext.getString(R.string.add_clips_before_reordering), Toast.LENGTH_SHORT).show();
}
});
btnNarrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaCards.size() > 0)
showClipNarrationDialog();
else
Toast.makeText(mContext, mContext.getString(R.string.add_clips_before_narrating), Toast.LENGTH_SHORT).show();
}
});
btnPublish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity mainActivity = (MainActivity) mCardModel.getStoryPath().getContext(); // FIXME this isn't a safe cast as context can sometimes not be an activity (getApplicationContext())
Util.startPublishActivity(mainActivity, mCardModel.getStoryPath());
}
});
// Initialize mMediaCards from current StoryPath
getClipCardsWithAttachedMedia();
if (mMediaCards.size() > 0) {
switch (((ClipCard) mMediaCards.get(0)).getMedium()) {
case Constants.VIDEO:
setThumbnailForClip(ivCardPhoto, (ClipCard) mMediaCards.get(0));
ivCardPhoto.setVisibility(View.VISIBLE);
tvCardVideo.setVisibility(View.VISIBLE);
tvCardVideo.setSurfaceTextureListener(new VideoWithNarrationSurfaceTextureListener(tvCardVideo, mMediaCards, ivCardPhoto));
break;
case Constants.AUDIO:
// TODO
break;
case Constants.PHOTO:
setThumbnailForClip(ivCardPhoto, (ClipCard) mMediaCards.get(0));
break;
}
} else {
Log.e(TAG, "No Clips available");
}
// supports automated testing
view.setTag(mCardModel.getId());
return view;
}
/**
* Initializes the value of {@link #mMediaCards} to a List of ClipCards with attached media
* within the current StoryPath
*/
private void getClipCardsWithAttachedMedia() {
ArrayList<Card> mediaCards = mCardModel.getStoryPath().gatherCards("<<ClipCard>>");
Iterator iterator = mediaCards.iterator();
while (iterator.hasNext()) {
ClipCard clipCard = (ClipCard) iterator.next();
mMedium = clipCard.getMedium();
if ( clipCard.getClips() == null || clipCard.getClips().size() < 1 ) {
iterator.remove();
}
}
mMediaCards = mediaCards;
}
/** Record Narration Dialog */
/** Collection of ClipCards with attached media within the current StoryPath. */
ArrayList<Card> mMediaCards;
/** Records audio */
MediaRecorder mMediaRecorder;
File mNarrationOutput;
/** Record Narration Dialog Views */
Button mDonePauseResumeBtn;
Button mRecordStopRedoBtn;
/**
* Show a dialog allowing the user to record narration for a Clip
*/
private void showClipNarrationDialog() {
View v = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.dialog_clip_narration, null);
/** Narrate dialog views */
final TextureView videoView = (TextureView) v.findViewById(R.id.textureView);
final ImageView thumbnailView = (ImageView) v.findViewById(R.id.thumbnail);
final TextView clipLength = (TextView) v.findViewById(R.id.clipLength);
final SeekBar playbackBar = (SeekBar) v.findViewById(R.id.playbackProgress);
mDonePauseResumeBtn = (Button) v.findViewById(R.id.donePauseResumeButton);
mRecordStopRedoBtn = (Button) v.findViewById(R.id.recordStopRedoButton);
/** Configure views for initial state */
changeRecordNarrationStateChanged(RecordNarrationState.READY);
final VideoWithNarrationSurfaceTextureListener surfaceListener = new VideoWithNarrationSurfaceTextureListener(videoView, mMediaCards, thumbnailView);
videoView.setSurfaceTextureListener(surfaceListener);
surfaceListener.setPlaybackProgressSeekBar(playbackBar);
clipLength.setText("Total: " + Util.makeTimeString(surfaceListener.getTotalClipCollectionDuration()));
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setView(v);
final Dialog dialog = builder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
Log.i(TAG, "Narrate Dialog Dismissed. Cleaning up");
surfaceListener.timer.cancel();
releaseMediaRecorder();
}
});
dialog.show();
mDonePauseResumeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (mRecordNarrationState) {
case STOPPED:
case READY:
// Done Button
dialog.dismiss();
// TODO Attach narration to clip if not already done
break;
case RECORDING:
// Pause Button
// TODO Pausing & resuming a recording will take some extra effort
//pauseRecordingNarration(player);
Toast.makeText(mContext, "Not yet supported", Toast.LENGTH_SHORT).show();
break;
case PAUSED:
// Resume Button
// TODO See above
Toast.makeText(mContext, "Not yet supported", Toast.LENGTH_SHORT).show();
break;
}
}
});
mRecordStopRedoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (mRecordNarrationState) {
case READY:
// Record Button
// TODO Show recording countdown first
switch (surfaceListener.currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
case Constants.AUDIO:
// TODO : If audio, show level meter or something
if(thumbnailView.getVisibility() == View.VISIBLE) {
thumbnailView.setVisibility(View.GONE);
}
break;
}
surfaceListener.stopPlayback();
changeRecordNarrationStateChanged(RecordNarrationState.RECORDING);
startRecordingNarration();
surfaceListener.startPlayback();
surfaceListener.isPlaying = true;
break;
case RECORDING:
case PAUSED:
// Stop Button
surfaceListener.stopPlayback();
surfaceListener.isPlaying = false;
stopRecordingNarration();
changeRecordNarrationStateChanged(RecordNarrationState.STOPPED);
break;
case STOPPED:
// Redo Button
// TODO Show recording countdown first
// TODO reset player to first clip
surfaceListener.stopPlayback();
startRecordingNarration();
changeRecordNarrationStateChanged(RecordNarrationState.RECORDING);
surfaceListener.startPlayback(); // Make sure to call this after changing state to RECORDING
surfaceListener.isPlaying = true;
break;
}
}
});
}
/**
* Set a thumbnail on the given ImageView for the given ClipCard
*/
private void setThumbnailForClip(@NonNull ImageView thumbnail, @NonNull ClipCard clipCard) {
// Clip has attached media. Show an appropriate preview
// e.g: A thumbnail for video
MediaFile mediaFile = clipCard.getStoryPath().loadMediaFile(clipCard.getSelectedClip().getUuid());
String medium = clipCard.getMedium();
if (medium.equals(Constants.VIDEO)) {
Bitmap thumbnailBitmap = mediaFile.getThumbnail(mContext);
if (thumbnailBitmap != null) {
thumbnail.setImageBitmap(thumbnailBitmap);
}
thumbnail.setVisibility(View.VISIBLE);
} else if (medium.equals(Constants.PHOTO)) {
Uri uri = Uri.parse(mediaFile.getPath());
thumbnail.setImageURI(uri);
thumbnail.setVisibility(View.VISIBLE);
} else if (medium.equals(Constants.AUDIO)) {
Uri myUri = Uri.parse(mediaFile.getPath());
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set background image
String clipType = clipCard.getClipType();
setClipExampleDrawables(clipType, thumbnail);
thumbnail.setVisibility(View.VISIBLE);
}
}
/**
* Set an example thumbnail on imageView for this clipType
*
* This should be called if no thumbnail directly representing the clip is available.
*/
private void setClipExampleDrawables(String clipType, ImageView imageView) {
Drawable drawable;
switch (clipType) {
case Constants.CHARACTER:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_character);
break;
case Constants.ACTION:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_action);
break;
case Constants.RESULT:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_result);
break;
case Constants.SIGNATURE:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_signature);
break;
case Constants.PLACE:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_place);
break;
default:
Log.d(TAG, "No clipType matching '" + clipType + "' found.");
drawable = mContext.getResources().getDrawable(R.drawable.ic_launcher); // FIXME replace with a sensible placeholder image
}
imageView.setImageDrawable(drawable);
}
/**
* Start recording an audio narration track synced and instruct player to
* begin playback simultaneously.
*/
private void startRecordingNarration() {
DateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String now = df.format(new Date());
mNarrationOutput = new File(Environment.getExternalStorageDirectory(), now + /*".aac"*/ ".mp4");
if (mMediaRecorder == null) mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioEncodingBitRate(96 * 1000);
mMediaRecorder.setAudioSamplingRate(44100);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); // raw AAC ADTS container records properly but results in Unknown MediaPlayer errors when playback attempted. :/
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mMediaRecorder.setOutputFile(mNarrationOutput.getAbsolutePath());
try {
mMediaRecorder.prepare();
mMediaRecorder.start();
Toast.makeText(mContext, "Recording Narration", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e(TAG, "prepare() failed");
}
// mClipCollectionPlayer.setVolume(0, 0); // Mute track volume while recording narration
// mClipCollectionPlayer.start();
}
/**
* Stop and reset {@link #mMediaRecorder} so it may be used again
*/
private void stopRecordingNarration() {
// if (mClipCollectionPlayer.isPlaying()) mClipCollectionPlayer.pause();
// mClipCollectionPlayer.setVolume(1, 1); // Restore track volume when finished recording narration
mMediaRecorder.stop();
mMediaRecorder.reset();
// Attach the just-recorded narration to ReviewCard
MediaFile narrationMediaFile = new MediaFile(mNarrationOutput.getAbsolutePath(), Constants.AUDIO);
mCardModel.setNarration(narrationMediaFile);
}
private void pauseRecordingNarration(MediaPlayer player) {
throw new UnsupportedOperationException("Pausing and resuming a recording is not yet supported!");
// TODO This is going to require Android 4.3's MediaCodec APIs or
// TODO file concatenation of multiple recordings.
}
/**
* Release {@link #mMediaRecorder} when no more recordings will be made
*/
private void releaseMediaRecorder() {
if (mMediaRecorder != null) mMediaRecorder.release();
}
/**
* Update the UI in response to a new value assignment to {@link #mRecordNarrationState}
*/
private void changeRecordNarrationStateChanged(RecordNarrationState newState) {
mRecordNarrationState = newState;
switch(mRecordNarrationState) {
case READY:
mRecordStopRedoBtn.setText(R.string.dialog_record);
mDonePauseResumeBtn.setText(R.string.dialog_done);
break;
case RECORDING:
mRecordStopRedoBtn.setText(R.string.dialog_stop);
mDonePauseResumeBtn.setText(R.string.dialog_pause);
break;
case PAUSED:
mRecordStopRedoBtn.setText(R.string.dialog_stop);
mDonePauseResumeBtn.setText(R.string.dialog_resume);
break;
case STOPPED:
mRecordStopRedoBtn.setText(R.string.dialog_redo);
mDonePauseResumeBtn.setText(R.string.dialog_done);
break;
}
}
/** A convenience SurfaceTextureListener to configure a TextureView for video playback of a Collection
* of ClipCards. Note the constructor argument is a list of Cards due to the nature of {@link scal.io.liger.model.StoryPath#gatherCards(String)}
* and inability to cast a typed Collection.
*/
private class VideoSurfaceTextureListener implements TextureView.SurfaceTextureListener {
Surface surface;
protected MediaPlayer mediaPlayer;
protected volatile boolean isPlaying; // Need a separate variable as images won't be processed by the MediaPlayer
protected ClipCard currentlyPlayingCard;
protected final List<Card> mediaCards;
/**
* Collection of cumulative duration parallel to mMediaCards.
* e.g: the first entry is the duration of the first clip, the second is the duration
* of the first and second clips etc. Used to properly report playback progress relative to
* entire mMediaCards collection.
*/
ArrayList<Integer> accumulatedDurationByMediaCard;
final AtomicInteger clipCollectionDuration = new AtomicInteger();
final ImageView ivThumbnail;
final TextureView tvVideo;
SeekBar sbPlaybackProgress;
Timer timer;
final int TIMER_INTERVAL_MS = 100;
int currentPhotoElapsedTime; // Keep track of how long current photo has been "playing" so we can advance state
public VideoSurfaceTextureListener(@NonNull TextureView textureView, @NonNull List<Card> mediaCards, @Nullable ImageView thumbnailView) {
ivThumbnail = thumbnailView;
tvVideo = textureView;
this.mediaCards = mediaCards;
init();
}
/** Set a SeekBar to represent playback progress. May be set at any time
*/
public void setPlaybackProgressSeekBar(SeekBar progress) {
sbPlaybackProgress = progress;
}
/**
* Return the total duration of all clips in the passed collection, accounting for start and
* stop trim times. Will return a valid value any time after construction.
*/
public int getTotalClipCollectionDuration() {
return clipCollectionDuration.get();
}
private void init() {
// Setup views
currentlyPlayingCard = (ClipCard) mediaCards.get(0);
setThumbnailForClip(ivThumbnail, currentlyPlayingCard);
ivThumbnail.setOnClickListener(getVideoPlaybackToggleClickListener());
tvVideo.setOnClickListener(getVideoPlaybackToggleClickListener());
clipCollectionDuration.set(calculateTotalClipCollectionLengthMs(mediaCards));
setupTimer();
}
private void setupTimer() {
// Poll MediaPlayer for position, ensuring it never exceeds stop point indicated by ClipMetadata
if (timer != null) timer.cancel(); // should never happen but JIC
timer = new Timer("mplayer");
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
if (isPlaying /*mediaPlayer != null && mediaPlayer.isPlaying() */) {
int currentClipElapsedTime = 0;
switch (currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
case Constants.AUDIO:
currentClipElapsedTime = mediaPlayer.getCurrentPosition();// - currentlyPlayingCard.getSelectedClip().getStartTime();
// Note that if getStopTime() is 0 clip advancing will be handled by the MediaPlayer onCompletionListener
if (currentlyPlayingCard.getSelectedClip().getStopTime() > 0 && currentClipElapsedTime > currentlyPlayingCard.getSelectedClip().getStopTime()) {
mediaPlayer.pause();
advanceToNextClip(mediaPlayer);
}
break;
case Constants.PHOTO:
currentPhotoElapsedTime += TIMER_INTERVAL_MS; // For Photo cards, this is reset on each call to advanceToNextClip
currentClipElapsedTime = currentPhotoElapsedTime;
if (currentClipElapsedTime > mCardModel.getStoryPath().getStoryPathLibrary().photoSlideDurationMs) advanceToNextClip(null);
break;
}
int durationOfPreviousClips = 0;
int currentlyPlayingCardIndex = mediaCards.indexOf(currentlyPlayingCard);
if (currentlyPlayingCardIndex > 0)
durationOfPreviousClips = accumulatedDurationByMediaCard.get(currentlyPlayingCardIndex - 1);
if (sbPlaybackProgress != null) {
sbPlaybackProgress.setProgress((int) (sbPlaybackProgress.getMax() * ((float) durationOfPreviousClips + currentClipElapsedTime) / clipCollectionDuration.get())); // Show progress relative to clip collection duration
}
// Log.i(TAG, "current clip elapsed time: " + currentClipElapsedTime);
}
} catch (IllegalStateException e) { /* MediaPlayer in invalid state. Ignore */}
}
},
50, // Initial delay ms
TIMER_INTERVAL_MS); // Repeat interval ms
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
surface = new Surface(surfaceTexture);
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(mContext, Uri.parse(currentlyPlayingCard.getSelectedMediaFile().getPath()));
mediaPlayer.setSurface(surface);
mediaPlayer.prepareAsync();
mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.seekTo(currentlyPlayingCard.getSelectedClip().getStartTime());
int currentClipIdx = mediaCards.indexOf(currentlyPlayingCard);
if (currentClipIdx == 0) {
Log.i(TAG, "prepared finished for first clip");
// This is the first clip
// Setup initial views requiring knowledge of clip media
if (currentlyPlayingCard.getSelectedClip().getStopTime() == 0)
currentlyPlayingCard.getSelectedClip().setStopTime(mediaPlayer.getDuration());
mediaPlayer.seekTo(currentlyPlayingCard.getSelectedClip().getStartTime());
// TODO Handle outside of this class
//clipLength.setText("Total : " + Util.makeTimeString(clipCollectionDuration.get()));
} else {
Log.i(TAG, "Auto starting subsequent clip");
// automatically begin playing subsequent clips
mediaPlayer.start();
}
}
});
/** MediaPlayer for narration recording */
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
advanceToNextClip(mp);
}
});
} catch (IllegalArgumentException | IllegalStateException | SecurityException | IOException e) {
e.printStackTrace();
}
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
Log.i(TAG, "surfaceTexture destroyed. releasing MediaPlayer and Timer");
mediaPlayer.release();
timer.cancel();
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
/**
* Calculates the cumulative length in ms of each selected clip of each Card in cards.
* Also populates {@link #accumulatedDurationByMediaCard}.
*
* @param cards An ArrayList of {@link scal.io.liger.model.ClipCard}s.
* Only cards of type ClipCard will be evaluated.
*
* Note we don't accept an ArrayList<ClipCard> due to the current operation of StoryPath#gatherCards(..)
*/
private int calculateTotalClipCollectionLengthMs(List<Card> cards) {
int totalDuration = 0;
int clipDuration;
accumulatedDurationByMediaCard = new ArrayList<>(cards.size());
for (Card card : cards) {
if (card instanceof ClipCard) {
clipDuration = 0;
switch (((ClipCard) card).getMedium()) {
case Constants.VIDEO:
ClipMetadata clipMeta = ((ClipCard) card).getSelectedClip();
MediaPlayer mp = MediaPlayer.create(mContext, Uri.parse(((ClipCard)card).getSelectedMediaFile().getPath()));
clipDuration = ( clipMeta.getStopTime() == 0 ? mp.getDuration() : (clipMeta.getStopTime() - clipMeta.getStartTime()) );
mp.release();
break;
case Constants.PHOTO:
clipDuration += mCardModel.getStoryPath().getStoryPathLibrary().photoSlideDurationMs;
break;
}
totalDuration += clipDuration;
accumulatedDurationByMediaCard.add(totalDuration);
Log.i(TAG, String.format("Got duration for media: %d", clipDuration));
Log.i(TAG, "Total duration now " + totalDuration);
}
}
return totalDuration;
}
/** Craft a OnClickListener to toggle video playback and thumbnail visibility */
protected View.OnClickListener getVideoPlaybackToggleClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
//if (mediaPlayer == null) return;
if (isPlaying /*mediaPlayer.isPlaying() */) {
// Pause playback
switch(currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
case Constants.AUDIO:
mediaPlayer.pause();
break;
case Constants.PHOTO:
// do nothing. Timer will pickup change in isPlaying
break;
}
isPlaying = false;
}
else {
// Resume playback
switch(currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
case Constants.AUDIO:
mediaPlayer.start();
if (ivThumbnail.getVisibility() == View.VISIBLE) ivThumbnail.setVisibility(View.GONE);
break;
case Constants.PHOTO:
// do nothing. Timer will pickup change in isPlaying
break;
}
//startClipCollectionPlaybackWithNarration();
isPlaying = true;
}
}
};
}
/**
* Advance the given MediaPlayer to the next clip in mMediaCards
* and ends with a call to {@link android.media.MediaPlayer#prepare()}. Therefore
* an OnPreparedListener must be set on MediaPlayer to start playback
*
* If this is a Photo card player may be null.
*/
protected void advanceToNextClip(@Nullable MediaPlayer player) {
Uri video;
int currentClipIdx = mediaCards.indexOf(currentlyPlayingCard);
if (currentClipIdx == (mediaCards.size() - 1)) {
// We've played through all the clips
// TODO Extend this class and override to add simultaneous narration playback
// if (mRecordNarrationState == RecordNarrationState.RECORDING) {
// stopRecordingNarration();
// changeRecordNarrationStateChanged(RecordNarrationState.STOPPED);
Log.i(TAG, "Played all clips. Resetting to first");
currentlyPlayingCard = (ClipCard) mediaCards.get(0);
} else {
// Advance to next clip
Log.i(TAG, "Advancing to next clip");
currentlyPlayingCard = (ClipCard) mediaCards.get(++currentClipIdx);
}
switch (currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
tvVideo.setVisibility(View.VISIBLE); // In case previous card wasn't video medium
video = Uri.parse(currentlyPlayingCard.getSelectedMediaFile().getPath());
try {
// Don't set isPlaying false. We're only 'stopping' to switch media sources
player.stop();
player.reset();
Log.i(TAG, "Setting player data source " + video.toString());
player.setDataSource(mContext, video);
player.setSurface(surface);
player.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
break;
case Constants.PHOTO:
currentPhotoElapsedTime = 0;
if (mediaCards.indexOf(currentlyPlayingCard) == 0) {
// Stop playback. With video / audio this would be handled onPreparedListener
isPlaying = false;
currentPhotoElapsedTime = 0;
}
ivThumbnail.post(new Runnable() {
@Override
public void run() {
setThumbnailForClip(ivThumbnail, currentlyPlayingCard);
mediaPlayer.seekTo(currentlyPlayingCard.getSelectedClip().getStartTime());
}
});
break;
}
}
}
private class VideoWithNarrationSurfaceTextureListener extends VideoSurfaceTextureListener {
MediaPlayer narrationPlayer;
public VideoWithNarrationSurfaceTextureListener(@NonNull TextureView textureView, @NonNull List<Card> mediaCards, @Nullable ImageView thumbnailView) {
super(textureView, mediaCards, thumbnailView);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
release();
return false;
}
/** Craft a OnClickListener to toggle video playback and thumbnail visibility */
@Override
protected View.OnClickListener getVideoPlaybackToggleClickListener() {
return new View.OnClickListener() {
boolean paused = false;
@Override
public void onClick(View v) {
if (currentlyPlayingCard.getMedium().equals(Constants.VIDEO) && mediaPlayer == null) return;
if (isPlaying /*mediaPlayer.isPlaying() */) {
pausePlayback();
paused = true;
isPlaying = false;
}
else if (paused){
// paused
resumePlayback();
paused = false;
isPlaying = true;
}
else {
// stopped
startPlayback();
isPlaying = true;
}
}
};
}
private void startPlayback() {
// Connect narrationPlayer to narration mediaFile on each request to start playback
// to ensure we have the most current narration recording
if (mCardModel.getSelectedNarrationFile() != null && !mRecordNarrationState.equals(RecordNarrationState.RECORDING)) {
Uri narrationUri = Uri.parse(mCardModel.getSelectedNarrationFile().getPath());
if (narrationPlayer == null) narrationPlayer = MediaPlayer.create(mContext, narrationUri);
else {
// TODO Only necessary if narration media file changed
try {
narrationPlayer.reset();
narrationPlayer.setDataSource(mContext, narrationUri);
narrationPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
narrationPlayer.start();
}
switch(currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
// Mute the main media volume if we're recording narration
if (mRecordNarrationState.equals(RecordNarrationState.RECORDING)) {
mediaPlayer.setVolume(0, 0);
} else {
mediaPlayer.setVolume(1, 1);
}
mediaPlayer.start();
if (ivThumbnail.getVisibility() == View.VISIBLE) {
ivThumbnail.setVisibility(View.GONE);
}
break;
}
}
private void pausePlayback() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
if (narrationPlayer != null && narrationPlayer.isPlaying()) {
narrationPlayer.pause();
}
}
private void resumePlayback() {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
if (narrationPlayer != null && !narrationPlayer.isPlaying()) {
narrationPlayer.start();
}
}
private void stopPlayback() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
}
if (narrationPlayer != null && narrationPlayer.isPlaying()) {
narrationPlayer.stop();
narrationPlayer.reset();
}
currentlyPlayingCard = (ClipCard) mediaCards.get(0);
}
private void release() {
if (narrationPlayer != null) narrationPlayer.release();
if (mediaPlayer != null) mediaPlayer.release();
}
/**
* Override to advance recording state if playback is complete
*/
@Override
protected void advanceToNextClip(MediaPlayer player) {
int currentClipIdx = mediaCards.indexOf(currentlyPlayingCard);
if (currentClipIdx == (mediaCards.size() - 1)) {
// We've played through all the clips
if (mRecordNarrationState == RecordNarrationState.RECORDING) {
stopRecordingNarration();
ivThumbnail.post(new Runnable() {
@Override
public void run() {
changeRecordNarrationStateChanged(RecordNarrationState.STOPPED);
}
});
}
}
// We need to check the current clip index *before* calling super(), which will advance it
super.advanceToNextClip(player);
}
}
}
|
package no.priv.garshol.duke;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.io.Writer;
import java.io.PrintWriter;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import no.priv.garshol.duke.matchers.MatchListener;
import no.priv.garshol.duke.matchers.PrintMatchListener;
import no.priv.garshol.duke.matchers.AbstractMatchListener;
import no.priv.garshol.duke.utils.Utils;
import no.priv.garshol.duke.utils.DefaultRecordIterator;
/**
* The class that implements the actual deduplication and record
* linkage logic.
*/
public class Processor {
private Configuration config;
private Collection<MatchListener> listeners;
private Logger logger;
private List<Property> proporder;
private double[] accprob;
private int threads;
private Database database1;
private Database database2;
private final static int DEFAULT_BATCH_SIZE = 40000;
// performance statistics
private long comparisons; // number of records compared
private long srcread; // ms spent reading from data sources
private long indexing; // ms spent indexing records
private long searching; // ms spent searching for records
private long comparing; // ms spent comparing records
private long callbacks; // ms spent in callbacks
private Profiler profiler;
private static ConcurrentMap<String, ConcurrentMap<String, Double>> calculatedReleations = new ConcurrentHashMap<String, ConcurrentMap<String, Double>>();
private Double sumOfHighPropertyProbability = null;
/**
* Creates a new processor, overwriting the existing Lucene index.
*/
public Processor(Configuration config) {
this(config, true);
}
/**
* Creates a new processor.
* @param overwrite If true, make new Lucene index. If false, leave
* existing data.
*/
public Processor(Configuration config, boolean overwrite) {
this(config, config.getDatabase(1, overwrite));
database2 = config.getDatabase(2, overwrite);
}
/**
* Creates a new processor, bound to the given database.
*/
public Processor(Configuration config, Database database) {
this.config = config;
this.database1 = database;
// using this List implementation so that listeners can be removed
// while Duke is running (see issue 117)
this.listeners = new CopyOnWriteArrayList<MatchListener>();
this.logger = new DummyLogger();
this.threads = 1;
// precomputing for later optimizations
this.proporder = new ArrayList();
for (Property p : config.getProperties())
if (!p.isIdProperty())
proporder.add(p);
Collections.sort(proporder, new PropertyComparator());
// still precomputing
double prob = 0.5;
accprob = new double[proporder.size()];
for (int ix = proporder.size() - 1; ix >= 0; ix
prob = Utils.computeBayes(prob, proporder.get(ix).getHighProbability());
accprob[ix] = prob;
}
}
/**
* Sets the logger to report to.
*/
public void setLogger(Logger logger) {
this.logger = logger;
}
/**
* Sets the number of threads to use for processing. The default is
* 1.
*/
public void setThreads(int threads) {
this.threads = threads;
}
/**
* Returns the number of threads.
*/
public int getThreads() {
return threads;
}
/**
* Adds a listener to be notified of processing events.
*/
public void addMatchListener(MatchListener listener) {
listeners.add(listener);
}
/**
* Removes a listener from being notified of the processing events.
* @since 1.1
*/
public boolean removeMatchListener(MatchListener listener) {
if (listener != null)
return listeners.remove(listener);
return true;
}
/**
* Returns all registered listeners.
*/
public Collection<MatchListener> getListeners() {
return listeners;
}
/**
* Returns the actual Lucene index being used. FIXME!!
*/
public Database getDatabase() {
return database1;
}
/**
* Returns the actual Lucene index being used. FIXME!!
*/
public Database getDatabase(int group) {
if (group == 1)
return database1;
else if (group == 2)
return database2;
throw new DukeException("Unknown group " + group);
}
/**
* Used to turn performance profiling on and off.
* @since 1.1
*/
public void setPerformanceProfiling(boolean profile) {
if (profile) {
if (profiler != null)
return; // we're already profiling
this.profiler = new Profiler();
addMatchListener(profiler);
} else {
// turn off profiling
if (profiler == null)
return; // we're not profiling, so nothing to do
removeMatchListener(profiler);
profiler = null;
}
}
/**
* Returns the performance profiler, if any.
* @since 1.1
*/
public Profiler getProfiler() {
return profiler;
}
/**
* Reads all available records from the data sources and processes
* them in batches, notifying the listeners throughout.
*/
public void deduplicate() {
deduplicate(config.getDataSources(), DEFAULT_BATCH_SIZE);
}
/**
* Reads all available records from the data sources and processes
* them in batches, notifying the listeners throughout.
*/
public void deduplicate(int batch_size) {
deduplicate(config.getDataSources(), batch_size);
}
/**
* Reads all available records from the data sources and processes
* them in batches, notifying the listeners throughout.
*/
public void deduplicate(Collection<DataSource> sources, int batch_size) {
int count = 0;
startProcessing();
Iterator<DataSource> it = sources.iterator();
while (it.hasNext()) {
DataSource source = it.next();
source.setLogger(logger);
RecordIterator it2 = source.getRecords();
try {
Collection<Record> batch = new ArrayList();
long start = System.currentTimeMillis();
while (it2.hasNext()) {
Record record = it2.next();
batch.add(record);
count++;
if (count % batch_size == 0) {
srcread += (System.currentTimeMillis() - start);
deduplicate(batch);
it2.batchProcessed();
batch = new ArrayList();
start = System.currentTimeMillis();
}
}
if (!batch.isEmpty()) {
deduplicate(batch);
it2.batchProcessed();
}
} finally {
it2.close();
}
}
endProcessing();
}
/**
* Deduplicates a newly arrived batch of records. The records may
* have been seen before.
*/
public void deduplicate(Collection<Record> records) {
logger.info("Deduplicating batch of " + records.size() + " records");
batchReady(records.size());
// prepare
long start = System.currentTimeMillis();
for (Record record : records)
database1.index(record);
database1.commit();
indexing += System.currentTimeMillis() - start;
// then match
match(records, true);
batchDone();
}
private void match(Collection<Record> records, boolean matchall) {
if (threads == 1)
for (Record record : records)
match(1, record, matchall);
else
threadedmatch(records, matchall);
}
private void threadedmatch(Collection<Record> records, boolean matchall) {
// split batch into n smaller batches
MatchThread[] threads = new MatchThread[this.threads];
for (int ix = 0; ix < threads.length; ix++) {
threads[ix] = new MatchThread(ix, records.size() / threads.length,
matchall);
}
int ix = 0;
for (Record record : records) {
threads[ix++ % threads.length].addRecord(record);
}
// kick off threads
for (ix = 0; ix < threads.length; ix++) {
threads[ix].start();
}
// wait for threads to finish
try {
for (ix = 0; ix < threads.length; ix++) {
threads[ix].join();
}
} catch (InterruptedException e) {
// argh
}
}
/**
* Does record linkage across the two groups, but does not link records within
* each group.
*/
public void link() {
link(config.getDataSources(1), config.getDataSources(2),
DEFAULT_BATCH_SIZE);
}
// FIXME: what about the general case, where there are more than 2 groups?
/**
* Does record linkage across the two groups, but does not link records within
* each group. With this method, <em>all</em> matches above threshold are
* passed on.
*/
public void link(Collection<DataSource> sources1,
Collection<DataSource> sources2,
int batch_size) {
link(sources1, sources2, true, batch_size);
}
/**
* Does record linkage across the two groups, but does not link records within
* each group.
*
* @param matchall If true, all matching records are accepted. If false, only
* the single best match for each record is accepted.
* @param batch_size The batch size to use.
* @since 1.1
*/
public void link(Collection<DataSource> sources1,
Collection<DataSource> sources2,
boolean matchall,
int batch_size) {
startProcessing();
// start with source 1
for (Collection<Record> batch : makeBatches(sources1, batch_size)) {
index(1, batch);
if (hasTwoDatabases()) {
linkBatch(2, batch, matchall);
}
}
// then source 2
for (Collection<Record> batch : makeBatches(sources2, batch_size)) {
if (hasTwoDatabases()) {
index(2, batch);
}
linkBatch(1, batch, matchall);
}
endProcessing();
}
/**
* Retrieve new records from data sources, and match them to previously
* indexed records. This method does <em>not</em> index the new records. With
* this method, <em>all</em> matches above threshold are passed on.
*
* @since 0.4
*/
public void linkRecords(Collection<DataSource> sources) {
linkRecords(sources, true);
}
/**
* Retrieve new records from data sources, and match them to previously
* indexed records. This method does <em>not</em> index the new records.
*
* @param matchall If true, all matching records are accepted. If false, only
* the single best match for each record is accepted.
* @since 0.5
*/
public void linkRecords(Collection<DataSource> sources, boolean matchall) {
linkRecords(sources, matchall, DEFAULT_BATCH_SIZE);
}
/**
* Retrieve new records from data sources, and match them to previously
* indexed records. This method does <em>not</em> index the new records.
*
* @param matchall If true, all matching records are accepted. If false, only
* the single best match for each record is accepted.
* @param batch_size The batch size to use.
* @since 1.0
*/
public void linkRecords(Collection<DataSource> sources, boolean matchall,
int batch_size) {
linkRecords(1, sources, matchall, batch_size);
}
/**
* Retrieve new records from data sources, and match them to previously
* indexed records in the given database. This method does <em>not</em>
* index the new records.
*
* @param dbno Which database to match against.
* @param matchall If true, all matching records are accepted. If false, only
* the single best match for each record is accepted.
* @param batch_size The batch size to use.
* @since 1.3
*/
public void linkRecords(int dbno, Collection<DataSource> sources,
boolean matchall, int batch_size) {
for (DataSource source : sources) {
source.setLogger(logger);
Collection<Record> batch = new ArrayList(batch_size);
RecordIterator it = source.getRecords();
while (it.hasNext()) {
batch.add(it.next());
if (batch.size() == batch_size) {
linkBatch(dbno, batch, matchall);
batch.clear();
}
}
it.close();
if (!batch.isEmpty()) {
linkBatch(dbno, batch, matchall);
}
}
endProcessing();
}
private void linkBatch(int dbno, Collection<Record> batch, boolean matchall) {
batchReady(batch.size());
for (Record r : batch) {
match(dbno, r, matchall);
}
batchDone();
}
/**
* Index all new records from the given data sources. This method does
* <em>not</em> do any matching.
*
* @since 0.4
*/
public void index(Collection<DataSource> sources, int batch_size) {
index(1, sources, batch_size);
}
/**
* Index all new records from the given data sources into the given database.
* This method does <em>not</em> do any matching.
*
* @since 1.3
*/
public void index(int dbno, Collection<DataSource> sources, int batch_size) {
Database thedb = getDB(dbno);
int count = 0;
for (DataSource source : sources) {
source.setLogger(logger);
RecordIterator it2 = source.getRecords();
while (it2.hasNext()) {
Record record = it2.next();
if (logger.isDebugEnabled()) {
logger.debug("Indexing record " + record);
}
thedb.index(record);
count++;
if (count % batch_size == 0) {
batchReady(batch_size);
}
}
it2.close();
}
if (count % batch_size == 0) {
batchReady(count % batch_size);
}
thedb.commit();
}
/**
* Index the records into the given database. This method does
* <em>not</em> do any matching.
*
* @since 1.3
*/
public void index(int dbno, Collection<Record> batch) {
Database thedb = getDB(dbno);
for (Record r : batch) {
if (logger.isDebugEnabled()) {
logger.debug("Indexing record " + r);
}
thedb.index(r);
}
thedb.commit();
}
/**
* Returns the number of records that have been compared.
*/
public long getComparisonCount() {
return comparisons;
}
private void match(int dbno, Record record, boolean matchall) {
long start = System.currentTimeMillis();
Collection<Record> candidates = getDB(dbno).findCandidateMatches(record);
if (config.getTreatRequiredPropertiesAsFilter()) {
candidates = filterByRequiredProps(record, candidates);
}
searching += System.currentTimeMillis() - start;
if (logger.isDebugEnabled()) {
logger.debug("Matching record "
+ PrintMatchListener.toString(record, config.getProperties())
+ " found " + candidates.size() + " candidates");
}
start = System.currentTimeMillis();
if (matchall) {
compareCandidatesSimple(record, candidates);
} else {
compareCandidatesBest(record, candidates);
}
comparing += System.currentTimeMillis() - start;
}
private Collection<Record> filterByRequiredProps(Record original, Collection<Record> candidates) {
Collection<Record> retCandidates = new ArrayList<Record>();
Collection<Property> required = config.getRequiredProperties();
for (Property property : required) {
String originalValue = original.getValue(property.getName());
if (originalValue == null) {
retCandidates.clear();
return retCandidates;
}
Iterator<Record> iter = candidates.iterator();
while (iter.hasNext()) {
Record candidate = iter.next();
String candidateValue = candidate.getValue(property.getName());
if (candidateValue != null && candidateValue.equalsIgnoreCase(originalValue)) {
retCandidates.add(candidate);
}
}
}
return retCandidates;
}
// the following two methods implement different record matching
// strategies. the first is used for deduplication, where we simply
// want all matches above the thresholds. the second is used for
// record linkage, to implement a simple greedy matching algorithm
// where we choose the best alternative above the threshold for each
// record.
// other, more advanced possibilities exist for record linkage, but
// they are not implemented yet. see the links below for more
// information.
/**
* Passes on all matches found.
*/
protected void compareCandidatesSimple(Record record,
Collection<Record> candidates) {
boolean found = false;
for (Record candidate : candidates) {
if (isSameAs(record, candidate)) {
continue;
}
double prob = compare(record, candidate);
if (prob > config.getThreshold()) {
found = true;
registerMatch(record, candidate, prob);
} else if (config.getMaybeThreshold() != 0.0
&& prob > config.getMaybeThreshold()) {
found = true; // I guess?
registerMatchPerhaps(record, candidate, prob);
}
}
if (!found) {
registerNoMatchFor(record);
}
}
/**
* Passes on only the best match for each record.
*/
protected void compareCandidatesBest(Record record,
Collection<Record> candidates) {
double max = 0.0;
Record best = null;
// go through all candidates, and find the best
for (Record candidate : candidates) {
if (isSameAs(record, candidate)) {
continue;
}
double prob = compare(record, candidate);
if (prob > max) {
max = prob;
best = candidate;
}
}
// pass on the best match, if any
if (logger.isDebugEnabled()) {
logger.debug("Best candidate at " + max + " is " + best);
}
if (max > config.getThreshold()) {
registerMatch(record, best, max);
} else if (config.getMaybeThreshold() != 0.0
&& max > config.getMaybeThreshold()) {
registerMatchPerhaps(record, best, max);
} else {
registerNoMatchFor(record);
}
}
/**
* Compares two records and returns the probability that they represent the
* same real-world entity.
*/
public double compare(Record r1, Record r2) {
boolean reverseOptimization = config.getReverseOptimization();
boolean linearMode = config.getLinearMode();
comparisons++;
Collection<Property> idproperties = config.getIdentityProperties();
//get first id property
Property idproperty = idproperties.iterator().next();
String fromId = r1.getValue(idproperty.getName());
String toId = r2.getValue(idproperty.getName());
ConcurrentMap<String, Double> related = null;
if (reverseOptimization) {
related = calculatedReleations.get(fromId);
if (related != null) {
Double relation = related.get(toId);
if (relation != null) {
return relation;
}
}
}
if (linearMode) {
//lazy initialiation
if (sumOfHighPropertyProbability == null) {
synchronized (Processor.class) {
if (sumOfHighPropertyProbability == null) {
sumOfHighPropertyProbability = 0.;
List<Property> properties = config.getProperties();
for (Property prop : properties) {
sumOfHighPropertyProbability += prop.getHighProbability();
}
}
}
}
}
double prob;
if (linearMode) {
prob = 0.0;
} else {
prob = 0.5;
}
for (String propname : r1.getProperties()) {
Property prop = config.getPropertyByName(propname);
if (prop == null) {
continue; // means the property is unknown
}
if (prop.isIdProperty() || prop.isIgnoreProperty()) {
continue;
}
Collection<String> vs1 = r1.getValues(propname);
Collection<String> vs2 = r2.getValues(propname);
if (vs1 == null || vs1.isEmpty() || vs2 == null || vs2.isEmpty()) {
continue; // no values to compare, so skip
}
double high = 0.0;
for (String v1 : vs1) {
if (v1.equals("")) // FIXME: these values shouldn't be here at all
{
continue;
}
for (String v2 : vs2) {
if (v2.equals("")) // FIXME: these values shouldn't be here at all
{
continue;
}
try {
double p = prop.compare(v1, v2);
high = Math.max(high, p);
} catch (Exception e) {
throw new DukeException("Comparison of values '" + v1 + "' and "
+ "'" + v2 + "' with "
+ prop.getComparator() + " failed", e);
}
}
}
//System.out.println("For property: " + propname + " value: " + high);
if (linearMode) {
prob += high;
} else {
prob = Utils.computeBayes(prob, high);
}
}
//and vice versa
if (reverseOptimization) {
synchronized (Processor.class) {
related = calculatedReleations.get(toId);
if (related == null) {
related = new ConcurrentHashMap<String, Double>();
calculatedReleations.put(toId, related);
}
}
}
double retVal = prob;
if (linearMode) {
retVal = prob / sumOfHighPropertyProbability;
}
if (reverseOptimization) {
related.put(fromId, retVal);
}
return retVal;
}
/**
* Commits all state to disk and frees up resources.
*/
public void close() {
database1.close();
if (hasTwoDatabases()) {
database2.close();
}
}
private Iterable<Collection<Record>> makeBatches(Collection<DataSource> sources, int batch_size) {
return new BatchIterator(sources, batch_size);
}
static class BatchIterator implements Iterable<Collection<Record>>,
Iterator<Collection<Record>> {
private BasicIterator it;
private int batch_size;
public BatchIterator(Collection<DataSource> sources, int batch_size) {
this.it = new BasicIterator(sources);
this.batch_size = batch_size;
}
public boolean hasNext() {
return it.hasNext();
}
public Collection<Record> next() {
Collection<Record> batch = new ArrayList();
while (it.hasNext()) {
batch.add(it.next());
}
return batch;
}
public Iterator<Collection<Record>> iterator() {
return this;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
static class BasicIterator implements Iterator<Record> {
private Iterator<DataSource> srcit;
private RecordIterator recit;
public BasicIterator(Collection<DataSource> sources) {
this.srcit = sources.iterator();
findNextIterator();
}
public boolean hasNext() {
return recit.hasNext();
}
public Record next() {
Record r = recit.next();
if (!recit.hasNext()) {
findNextIterator();
}
return r;
}
private void findNextIterator() {
if (srcit.hasNext()) {
DataSource src = srcit.next();
recit = src.getRecords();
} else {
recit = new DefaultRecordIterator(Collections.EMPTY_SET.iterator());
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public boolean hasTwoDatabases() {
return database2 != null;
}
private Database getDB(int no) {
if (no == 1) {
return database1;
} else if (no == 2) {
return database2;
} else {
throw new DukeException("Unknown database " + no);
}
}
private boolean isSameAs(Record r1, Record r2) {
for (Property idp : config.getIdentityProperties()) {
Collection<String> vs2 = r2.getValues(idp.getName());
Collection<String> vs1 = r1.getValues(idp.getName());
if (vs1 == null) {
continue;
}
for (String v1 : vs1) {
if (vs2.contains(v1)) {
return true;
}
}
}
return false;
}
private void startProcessing() {
if (logger.isDebugEnabled()) {
logger.debug("Start processing with " + database1 + " and " + database2);
}
long start = System.currentTimeMillis();
for (MatchListener listener : listeners) {
listener.startProcessing();
}
callbacks += (System.currentTimeMillis() - start);
}
private void endProcessing() {
long start = System.currentTimeMillis();
for (MatchListener listener : listeners) {
listener.endProcessing();
}
callbacks += (System.currentTimeMillis() - start);
}
private void batchReady(int size) {
long start = System.currentTimeMillis();
for (MatchListener listener : listeners) {
listener.batchReady(size);
}
callbacks += (System.currentTimeMillis() - start);
}
private void batchDone() {
long start = System.currentTimeMillis();
for (MatchListener listener : listeners) {
listener.batchDone();
}
callbacks += (System.currentTimeMillis() - start);
}
/**
* Records the statement that the two records match.
*/
private void registerMatch(Record r1, Record r2, double confidence) {
long start = System.currentTimeMillis();
for (MatchListener listener : listeners) {
listener.matches(r1, r2, confidence);
}
callbacks += (System.currentTimeMillis() - start);
}
/**
* Records the statement that the two records may match.
*/
private void registerMatchPerhaps(Record r1, Record r2, double confidence) {
long start = System.currentTimeMillis();
for (MatchListener listener : listeners) {
listener.matchesPerhaps(r1, r2, confidence);
}
callbacks += (System.currentTimeMillis() - start);
}
/**
* Notifies listeners that we found no matches for this record.
*/
private void registerNoMatchFor(Record current) {
long start = System.currentTimeMillis();
for (MatchListener listener : listeners) {
listener.noMatchFor(current);
}
callbacks += (System.currentTimeMillis() - start);
}
/**
* Sorts properties so that the properties with the lowest low probabilities
* come first.
*/
static class PropertyComparator implements Comparator<Property> {
public int compare(Property p1, Property p2) {
double diff = p1.getLowProbability() - p2.getLowProbability();
if (diff < 0) {
return -1;
} else if (diff > 0) {
return 1;
} else {
return 0;
}
}
}
/**
* The thread that actually runs parallell matching. It holds the thread's
* share of the current batch.
*/
class MatchThread extends Thread {
private Collection<Record> records;
private boolean matchall;
public MatchThread(int threadno, int recordcount, boolean matchall) {
super("MatchThread " + threadno);
this.records = new ArrayList(recordcount);
this.matchall = matchall;
}
public void run() {
for (Record record : records) {
match(1, record, matchall);
}
}
public void addRecord(Record record) {
records.add(record);
}
}
public class Profiler extends AbstractMatchListener {
private long processing_start;
private long batch_start;
private int batch_size;
private int records;
private PrintWriter out;
public Profiler() {
this.out = new PrintWriter(System.out);
}
/**
* Sets Writer to receive performance statistics. Defaults to System.out.
*/
public void setOutput(Writer outw) {
this.out = new PrintWriter(outw);
}
public void startProcessing() {
processing_start = System.currentTimeMillis();
System.out.println("Duke version " + Duke.getVersionString());
System.out.println(getDatabase());
if (hasTwoDatabases()) {
System.out.println(database2);
}
System.out.println("Threads: " + getThreads());
}
public void batchReady(int size) {
batch_start = System.currentTimeMillis();
batch_size = size;
}
public void batchDone() {
records += batch_size;
int rs = (int) ((1000.0 * batch_size)
/ (System.currentTimeMillis() - batch_start));
System.out.println("" + records + " processed, " + rs
+ " records/second; comparisons: "
+ getComparisonCount());
}
public void endProcessing() {
long end = System.currentTimeMillis();
double rs = (1000.0 * records) / (end - processing_start);
System.out.println("Run completed, " + (int) rs + " records/second");
System.out.println("" + records + " records total in "
+ ((end - processing_start) / 1000) + " seconds");
long total = srcread + indexing + searching + comparing + callbacks;
System.out.println("Reading from source: "
+ seconds(srcread) + " ("
+ percent(srcread, total) + "%)");
System.out.println("Indexing: "
+ seconds(indexing) + " ("
+ percent(indexing, total) + "%)");
System.out.println("Searching: "
+ seconds(searching) + " ("
+ percent(searching, total) + "%)");
System.out.println("Comparing: "
+ seconds(comparing) + " ("
+ percent(comparing, total) + "%)");
System.out.println("Callbacks: "
+ seconds(callbacks) + " ("
+ percent(callbacks, total) + "%)");
System.out.println();
Runtime r = Runtime.getRuntime();
System.out.println("Total memory: " + r.totalMemory() + ", "
+ "free memory: " + r.freeMemory() + ", "
+ "used memory: " + (r.totalMemory() - r.freeMemory()));
}
private String seconds(long ms) {
return "" + (int) (ms / 1000);
}
private String percent(long ms, long total) {
return "" + (int) ((double) (ms * 100) / (double) total);
}
}
}
|
package scal.io.liger.view;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.joanzapata.android.iconify.IconDrawable;
import com.joanzapata.android.iconify.Iconify;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import scal.io.liger.Constants;
import scal.io.liger.MainActivity;
import scal.io.liger.R;
import scal.io.liger.model.Card;
import scal.io.liger.model.ClipCard;
import scal.io.liger.model.ClipMetadata;
import scal.io.liger.model.MediaFile;
import scal.io.liger.model.ReviewCard;
/**
* ReviewCardView allows the user to review the order of clips
* attached to a ReviewCard's Story Path. This card will also support
* adding narration, changing the order of clips, and jumbling the order.
*/
public class ReviewCardView implements DisplayableCard {
public static final String TAG = "ReviewCardView";
private ReviewCard mCardModel;
private Context mContext;
private String mMedium;
/** Current Narration State. To change use
* {@link #changeRecordNarrationStateChanged(scal.io.liger.view.ReviewCardView.RecordNarrationState)}
*/
private RecordNarrationState mRecordNarrationState = RecordNarrationState.READY;
/** The ReviewCard Narration Dialog State */
static enum RecordNarrationState {
/** Done / Record Buttons present */
READY,
/** Recording countdown then Pause / Stop Buttons present */
RECORDING,
/** Recording paused. Resume / Stop Buttons present */
PAUSED,
/** Recording stopped. Done / Redo Buttons present */
STOPPED
}
public ReviewCardView(Context context, Card cardModel) {
Log.d("RevieCardView", "constructor");
mContext = context;
mCardModel = (ReviewCard) cardModel;
}
@Override
public View getCardView(final Context context) {
Log.d("RevieCardView", "getCardView");
if (mCardModel == null) {
return null;
}
View view = LayoutInflater.from(context).inflate(R.layout.card_review, null);
final ImageView ivCardPhoto = ((ImageView) view.findViewById(R.id.iv_thumbnail));
final TextureView tvCardVideo = ((TextureView) view.findViewById(R.id.tv_card_video));
Button btnJumble = ((Button) view.findViewById(R.id.btn_jumble));
Button btnOrder = ((Button) view.findViewById(R.id.btn_order));
Button btnNarrate = ((Button) view.findViewById(R.id.btn_narrate));
Button btnPublish = ((Button) view.findViewById(R.id.btn_publish));
btnJumble.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO
}
});
btnOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaCards.size() > 0)
Util.showOrderMediaPopup((Activity) mContext, mMedium, mMediaCards);
else
Toast.makeText(mContext, mContext.getString(R.string.add_clips_before_reordering), Toast.LENGTH_SHORT).show();
}
});
btnNarrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaCards.size() > 0)
showClipNarrationDialog();
else
Toast.makeText(mContext, mContext.getString(R.string.add_clips_before_narrating), Toast.LENGTH_SHORT).show();
}
});
btnPublish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity mainActivity = (MainActivity) mCardModel.getStoryPath().getContext(); // FIXME this isn't a safe cast as context can sometimes not be an activity (getApplicationContext())
Util.startPublishActivity(mainActivity, mCardModel.getStoryPath());
}
});
// Initialize mMediaCards from current StoryPath
getClipCardsWithAttachedMedia();
if (mMediaCards.size() > 0) {
switch (((ClipCard) mMediaCards.get(0)).getMedium()) {
case Constants.VIDEO:
case Constants.PHOTO:
case Constants.AUDIO:
// For now the SurfaceTextureListener handles all kinds of media playback and interaction
// TODO Move as much logic as possible to a "MixedMediaPlayer" that will handle the ImageView / TextureView
// as asppropriate for Audio, Video, and Photos
setThumbnailForClip(ivCardPhoto, (ClipCard) mMediaCards.get(0));
ivCardPhoto.setVisibility(View.VISIBLE);
tvCardVideo.setVisibility(View.VISIBLE);
tvCardVideo.setSurfaceTextureListener(new VideoWithNarrationSurfaceTextureListener(tvCardVideo, mMediaCards, ivCardPhoto));
break;
}
} else {
Log.e(TAG, "No Clips available");
}
// supports automated testing
view.setTag(mCardModel.getId());
return view;
}
/**
* Initializes the value of {@link #mMediaCards} to a List of ClipCards with attached media
* within the current StoryPath
*/
private void getClipCardsWithAttachedMedia() {
ArrayList<Card> mediaCards = mCardModel.getStoryPath().gatherCards("<<ClipCard>>");
Iterator iterator = mediaCards.iterator();
while (iterator.hasNext()) {
ClipCard clipCard = (ClipCard) iterator.next();
mMedium = clipCard.getMedium();
if ( clipCard.getClips() == null || clipCard.getClips().size() < 1 ) {
iterator.remove();
}
}
mMediaCards = mediaCards;
}
/** Record Narration Dialog */
/** Collection of ClipCards with attached media within the current StoryPath. */
ArrayList<Card> mMediaCards;
/** Records audio */
MediaRecorder mMediaRecorder;
File mNarrationOutput;
/** Record Narration Dialog Views */
Button mDonePauseResumeBtn;
Button mRecordStopRedoBtn;
/**
* Show a dialog allowing the user to record narration for a Clip
*/
private void showClipNarrationDialog() {
View v = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.dialog_clip_narration, null);
/** Narrate dialog views */
final TextureView videoView = (TextureView) v.findViewById(R.id.textureView);
final ImageView thumbnailView = (ImageView) v.findViewById(R.id.thumbnail);
final TextView clipLength = (TextView) v.findViewById(R.id.clipLength);
final SeekBar playbackBar = (SeekBar) v.findViewById(R.id.playbackProgress);
mDonePauseResumeBtn = (Button) v.findViewById(R.id.donePauseResumeButton);
mRecordStopRedoBtn = (Button) v.findViewById(R.id.recordStopRedoButton);
/** Configure views for initial state */
changeRecordNarrationStateChanged(RecordNarrationState.READY);
final VideoWithNarrationSurfaceTextureListener surfaceListener = new VideoWithNarrationSurfaceTextureListener(videoView, mMediaCards, thumbnailView);
videoView.setSurfaceTextureListener(surfaceListener);
surfaceListener.setPlaybackProgressSeekBar(playbackBar);
clipLength.setText("Total: " + Util.makeTimeString(surfaceListener.getTotalClipCollectionDuration()));
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setView(v);
final Dialog dialog = builder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
Log.i(TAG, "Narrate Dialog Dismissed. Cleaning up");
surfaceListener.timer.cancel();
releaseMediaRecorder();
}
});
dialog.show();
mDonePauseResumeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (mRecordNarrationState) {
case STOPPED:
case READY:
// Done Button
dialog.dismiss();
// TODO Attach narration to clip if not already done
break;
case RECORDING:
// Pause Button
// TODO Pausing & resuming a recording will take some extra effort
//pauseRecordingNarration(player);
Toast.makeText(mContext, "Not yet supported", Toast.LENGTH_SHORT).show();
break;
case PAUSED:
// Resume Button
// TODO See above
Toast.makeText(mContext, "Not yet supported", Toast.LENGTH_SHORT).show();
break;
}
}
});
mRecordStopRedoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (mRecordNarrationState) {
case READY:
// Record Button
// TODO Show recording countdown first
switch (surfaceListener.currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
case Constants.AUDIO:
// TODO : If audio, show level meter or something
if(thumbnailView.getVisibility() == View.VISIBLE) {
thumbnailView.setVisibility(View.GONE);
}
break;
}
surfaceListener.stopPlayback();
changeRecordNarrationStateChanged(RecordNarrationState.RECORDING);
startRecordingNarration();
surfaceListener.startPlayback();
surfaceListener.isPlaying = true;
break;
case RECORDING:
case PAUSED:
// Stop Button
surfaceListener.stopPlayback();
surfaceListener.isPlaying = false;
stopRecordingNarration();
changeRecordNarrationStateChanged(RecordNarrationState.STOPPED);
break;
case STOPPED:
// Redo Button
// TODO Show recording countdown first
// TODO reset player to first clip
surfaceListener.stopPlayback();
startRecordingNarration();
changeRecordNarrationStateChanged(RecordNarrationState.RECORDING);
surfaceListener.startPlayback(); // Make sure to call this after changing state to RECORDING
surfaceListener.isPlaying = true;
break;
}
}
});
}
/**
* Set a thumbnail on the given ImageView for the given ClipCard
*/
private void setThumbnailForClip(@NonNull ImageView thumbnail, @NonNull ClipCard clipCard) {
// Clip has attached media. Show an appropriate preview
// e.g: A thumbnail for video
MediaFile mediaFile = clipCard.getStoryPath().loadMediaFile(clipCard.getSelectedClip().getUuid());
String medium = clipCard.getMedium();
if (medium.equals(Constants.VIDEO)) {
Bitmap thumbnailBitmap = mediaFile.getThumbnail(mContext);
if (thumbnailBitmap != null) {
thumbnail.setImageBitmap(thumbnailBitmap);
}
thumbnail.setVisibility(View.VISIBLE);
} else if (medium.equals(Constants.PHOTO)) {
Uri uri = Uri.parse(mediaFile.getPath());
thumbnail.setImageURI(uri);
thumbnail.setVisibility(View.VISIBLE);
} else if (medium.equals(Constants.AUDIO)) {
Uri myUri = Uri.parse(mediaFile.getPath());
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set background image
String clipType = clipCard.getClipType();
setClipExampleDrawables(clipType, thumbnail);
thumbnail.setVisibility(View.VISIBLE);
}
}
/**
* Set an example thumbnail on imageView for this clipType
*
* This should be called if no thumbnail directly representing the clip is available.
*/
private void setClipExampleDrawables(String clipType, ImageView imageView) {
Drawable drawable;
switch (clipType) {
case Constants.CHARACTER:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_character);
break;
case Constants.ACTION:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_action);
break;
case Constants.RESULT:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_result);
break;
case Constants.SIGNATURE:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_signature);
break;
case Constants.PLACE:
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_place);
break;
default:
Log.d(TAG, "No clipType matching '" + clipType + "' found.");
drawable = mContext.getResources().getDrawable(R.drawable.ic_launcher); // FIXME replace with a sensible placeholder image
}
imageView.setImageDrawable(drawable);
}
/**
* Start recording an audio narration track synced and instruct player to
* begin playback simultaneously.
*/
private void startRecordingNarration() {
DateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String now = df.format(new Date());
mNarrationOutput = new File(Environment.getExternalStorageDirectory(), now + /*".aac"*/ ".mp4");
if (mMediaRecorder == null) mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioEncodingBitRate(96 * 1000);
mMediaRecorder.setAudioSamplingRate(44100);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); // raw AAC ADTS container records properly but results in Unknown MediaPlayer errors when playback attempted. :/
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mMediaRecorder.setOutputFile(mNarrationOutput.getAbsolutePath());
try {
mMediaRecorder.prepare();
mMediaRecorder.start();
Toast.makeText(mContext, "Recording Narration", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e(TAG, "prepare() failed");
}
// mClipCollectionPlayer.setVolume(0, 0); // Mute track volume while recording narration
// mClipCollectionPlayer.start();
}
/**
* Stop and reset {@link #mMediaRecorder} so it may be used again
*/
private void stopRecordingNarration() {
// if (mClipCollectionPlayer.isPlaying()) mClipCollectionPlayer.pause();
// mClipCollectionPlayer.setVolume(1, 1); // Restore track volume when finished recording narration
mMediaRecorder.stop();
mMediaRecorder.reset();
// Attach the just-recorded narration to ReviewCard
MediaFile narrationMediaFile = new MediaFile(mNarrationOutput.getAbsolutePath(), Constants.AUDIO);
mCardModel.setNarration(narrationMediaFile);
Log.i(TAG, "Saving narration file " + mNarrationOutput.getAbsolutePath());
}
private void pauseRecordingNarration(MediaPlayer player) {
throw new UnsupportedOperationException("Pausing and resuming a recording is not yet supported!");
// TODO This is going to require Android 4.3's MediaCodec APIs or
// TODO file concatenation of multiple recordings.
}
/**
* Release {@link #mMediaRecorder} when no more recordings will be made
*/
private void releaseMediaRecorder() {
if (mMediaRecorder != null) mMediaRecorder.release();
}
/**
* Update the UI in response to a new value assignment to {@link #mRecordNarrationState}
*/
private void changeRecordNarrationStateChanged(RecordNarrationState newState) {
mRecordNarrationState = newState;
switch(mRecordNarrationState) {
case READY:
mRecordStopRedoBtn.setText(R.string.dialog_record);
mDonePauseResumeBtn.setText(R.string.dialog_done);
break;
case RECORDING:
mRecordStopRedoBtn.setText(R.string.dialog_stop);
mDonePauseResumeBtn.setText(R.string.dialog_pause);
break;
case PAUSED:
mRecordStopRedoBtn.setText(R.string.dialog_stop);
mDonePauseResumeBtn.setText(R.string.dialog_resume);
break;
case STOPPED:
mRecordStopRedoBtn.setText(R.string.dialog_redo);
mDonePauseResumeBtn.setText(R.string.dialog_done);
break;
}
}
/** A convenience SurfaceTextureListener to configure a TextureView for video playback of a Collection
* of ClipCards. Note the constructor argument is a list of Cards due to the nature of {@link scal.io.liger.model.StoryPath#gatherCards(String)}
* and inability to cast a typed Collection.
*/
private abstract class VideoSurfaceTextureListener implements TextureView.SurfaceTextureListener {
Surface surface;
protected MediaPlayer mediaPlayer;
protected volatile boolean isPlaying; // Need a separate variable as images won't be processed by the MediaPlayer
protected boolean isPaused = false;
protected ClipCard currentlyPlayingCard;
protected final List<Card> mediaCards;
/**
* Collection of cumulative duration parallel to mMediaCards.
* e.g: the first entry is the duration of the first clip, the second is the duration
* of the first and second clips etc. Used to properly report playback progress relative to
* entire mMediaCards collection.
*/
ArrayList<Integer> accumulatedDurationByMediaCard;
final AtomicInteger clipCollectionDuration = new AtomicInteger();
final ImageView ivThumbnail;
final TextureView tvVideo;
SeekBar sbPlaybackProgress;
Timer timer;
final int TIMER_INTERVAL_MS = 100;
volatile int currentPhotoElapsedTime; // Keep track of how long current photo has been "playing" so we can advance state
volatile boolean advancingClip = false;
public VideoSurfaceTextureListener(@NonNull TextureView textureView, @NonNull List<Card> mediaCards, @Nullable ImageView thumbnailView) {
ivThumbnail = thumbnailView;
tvVideo = textureView;
this.mediaCards = mediaCards;
init();
}
/** Set a SeekBar to represent playback progress. May be set at any time
*/
public void setPlaybackProgressSeekBar(SeekBar progress) {
sbPlaybackProgress = progress;
}
/**
* Return the total duration of all clips in the passed collection, accounting for start and
* stop trim times. Will return a valid value any time after construction.
*/
public int getTotalClipCollectionDuration() {
return clipCollectionDuration.get();
}
private void init() {
// Setup views
currentlyPlayingCard = (ClipCard) mediaCards.get(0);
setThumbnailForClip(ivThumbnail, currentlyPlayingCard);
ivThumbnail.setOnClickListener(getVideoPlaybackToggleClickListener());
tvVideo.setOnClickListener(getVideoPlaybackToggleClickListener());
clipCollectionDuration.set(calculateTotalClipCollectionLengthMs(mediaCards));
setupTimer();
}
private void setupTimer() {
// Poll MediaPlayer for position, ensuring it never exceeds stop point indicated by ClipMetadata
if (timer != null) timer.cancel(); // should never happen but JIC
timer = new Timer("mplayer");
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
if (isPlaying ) {
int currentClipElapsedTime = 0;
switch (currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
case Constants.AUDIO:
currentClipElapsedTime = Math.min(mediaPlayer.getCurrentPosition(), mediaPlayer.getDuration());// Seen issues where getCurrentPosition returns
if (currentClipElapsedTime == 1957962536) {
Log.i("Timer", "WTF");
}
// If getStopTime() is equal to 0 or mediaPlayer.getDuration(), clip advancing will be handled by the MediaPlayer onCompletionListener
int clipStopTimeMs = currentlyPlayingCard.getSelectedClip().getStopTime();
if (!advancingClip && clipStopTimeMs > 0 && currentClipElapsedTime > clipStopTimeMs && clipStopTimeMs != mediaPlayer.getDuration()) {
//mediaPlayer.pause();
Log.i(TAG, String.format("video timer advancing clip. Clip stop time: %d. MediaPlayer duration: %d", clipStopTimeMs, mediaPlayer.getDuration()));
advanceToNextClip(mediaPlayer);
} else if (advancingClip) {
// MediaPlayer is transitioning and cannot report progress
Log.i("Timer", "MediaPlayer is advancing, using currentClipElapsedTime of 0");
currentClipElapsedTime = 0;
}
break;
case Constants.PHOTO:
//Log.i("Timer", String.format("Photo elapsed time %d / %d", currentPhotoElapsedTime, mCardModel.getStoryPath().getStoryPathLibrary().photoSlideDurationMs));
currentPhotoElapsedTime += TIMER_INTERVAL_MS; // For Photo cards, this is reset on each call to advanceToNextClip
currentClipElapsedTime = currentPhotoElapsedTime;
if (!advancingClip && currentClipElapsedTime > mCardModel.getStoryPath().getStoryPathLibrary().photoSlideDurationMs) {
//Log.i("Timer", "advancing photo");
Log.i(TAG, "photo timer advancing clip");
advanceToNextClip(null);
currentPhotoElapsedTime = 0;
currentClipElapsedTime = 0;
}
break;
}
int durationOfPreviousClips = 0;
int currentlyPlayingCardIndex = mediaCards.indexOf(currentlyPlayingCard);
if (currentlyPlayingCardIndex > 0)
durationOfPreviousClips = accumulatedDurationByMediaCard.get(currentlyPlayingCardIndex - 1);
if (sbPlaybackProgress != null) {
sbPlaybackProgress.setProgress((int) (sbPlaybackProgress.getMax() * ((float) durationOfPreviousClips + currentClipElapsedTime) / clipCollectionDuration.get())); // Show progress relative to clip collection duration
}
Log.i("Timer", String.format("current clip (%d) elapsed time: %d. max photo time: %d. progress: %d", currentlyPlayingCardIndex, currentClipElapsedTime, mCardModel.getStoryPath().getStoryPathLibrary().photoSlideDurationMs, sbPlaybackProgress == null ? 0 : sbPlaybackProgress.getProgress()));
}
} catch (IllegalStateException e) { /* MediaPlayer in invalid state. Ignore */}
}
},
50, // Initial delay ms
TIMER_INTERVAL_MS); // Repeat interval ms
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
surface = new Surface(surfaceTexture);
switch (currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
case Constants.AUDIO:
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(mContext, Uri.parse(currentlyPlayingCard.getSelectedMediaFile().getPath()));
mediaPlayer.setSurface(surface);
mediaPlayer.prepareAsync();
mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
advancingClip = false;
mediaPlayer.seekTo(currentlyPlayingCard.getSelectedClip().getStartTime());
int currentClipIdx = mediaCards.indexOf(currentlyPlayingCard);
if (currentClipIdx != 0) {
mediaPlayer.start();
} else {
isPlaying = false;
isPaused = false; // Next touch should initiate startPlaying
Log.i(TAG, "onPrepared setting isPaused false");
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.i(TAG, "mediaplayer onComplete. advancing clip");
if (!advancingClip) advanceToNextClip(mp);
}
});
} catch (IllegalArgumentException | IllegalStateException | SecurityException | IOException e) {
e.printStackTrace();
}
break;
case Constants.PHOTO:
// do nothing
break;
}
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
Log.i(TAG, "surfaceTexture destroyed. releasing MediaPlayer and Timer");
mediaPlayer.release();
timer.cancel();
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
/**
* Calculates the cumulative length in ms of each selected clip of each Card in cards.
* Also populates {@link #accumulatedDurationByMediaCard}.
*
* @param cards An ArrayList of {@link scal.io.liger.model.ClipCard}s.
* Only cards of type ClipCard will be evaluated.
*
* Note we don't accept an ArrayList<ClipCard> due to the current operation of StoryPath#gatherCards(..)
*/
private int calculateTotalClipCollectionLengthMs(List<Card> cards) {
int totalDuration = 0;
int clipDuration;
accumulatedDurationByMediaCard = new ArrayList<>(cards.size());
for (Card card : cards) {
if (card instanceof ClipCard) {
clipDuration = 0;
switch (((ClipCard) card).getMedium()) {
case Constants.VIDEO:
ClipMetadata clipMeta = ((ClipCard) card).getSelectedClip();
MediaPlayer mp = MediaPlayer.create(mContext, Uri.parse(((ClipCard)card).getSelectedMediaFile().getPath()));
clipDuration = ( clipMeta.getStopTime() == 0 ? mp.getDuration() : (clipMeta.getStopTime() - clipMeta.getStartTime()) );
mp.release();
break;
case Constants.PHOTO:
clipDuration += mCardModel.getStoryPath().getStoryPathLibrary().photoSlideDurationMs;
break;
}
totalDuration += clipDuration;
accumulatedDurationByMediaCard.add(totalDuration);
Log.i(TAG, String.format("Got duration for media: %d", clipDuration));
Log.i(TAG, "Total duration now " + totalDuration);
}
}
return totalDuration;
}
/** Craft a OnClickListener to toggle video playback and thumbnail visibility */
protected abstract View.OnClickListener getVideoPlaybackToggleClickListener();
/**
* Advance the given MediaPlayer to the next clip in mMediaCards
* and ends with a call to {@link android.media.MediaPlayer#prepare()}. Therefore
* an OnPreparedListener must be set on MediaPlayer to start playback
*
* If this is a Photo card player may be null.
*/
protected abstract void advanceToNextClip(@Nullable MediaPlayer player);
}
private class VideoWithNarrationSurfaceTextureListener extends VideoSurfaceTextureListener {
MediaPlayer narrationPlayer;
public VideoWithNarrationSurfaceTextureListener(@NonNull TextureView textureView, @NonNull List<Card> mediaCards, @Nullable ImageView thumbnailView) {
super(textureView, mediaCards, thumbnailView);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
release();
return false;
}
/** Craft a OnClickListener to toggle video playback and thumbnail visibility */
@Override
protected View.OnClickListener getVideoPlaybackToggleClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentlyPlayingCard.getMedium().equals(Constants.VIDEO) && mediaPlayer == null) return;
if (isPlaying) {
pausePlayback();
isPaused = true;
isPlaying = false;
}
else if (isPaused){
// paused
resumePlayback();
isPaused = false;
isPlaying = true;
}
else {
// stopped
startPlayback();
isPlaying = true;
}
}
};
}
private void startPlayback() {
// Connect narrationPlayer to narration mediaFile on each request to start playback
// to ensure we have the most current narration recording
if (mCardModel.getSelectedNarrationFile() != null && !mRecordNarrationState.equals(RecordNarrationState.RECORDING)) {
Uri narrationUri = Uri.parse(mCardModel.getSelectedNarrationFile().getPath());
if (narrationPlayer == null) narrationPlayer = MediaPlayer.create(mContext, narrationUri);
else {
// TODO Only necessary if narration media file changed
try {
narrationPlayer.reset();
narrationPlayer.setDataSource(mContext, narrationUri);
narrationPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i(TAG, "Starting narration player for uri " + narrationUri.toString());
narrationPlayer.start();
}
switch(currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
// Mute the main media volume if we're recording narration
if (mRecordNarrationState.equals(RecordNarrationState.RECORDING)) {
mediaPlayer.setVolume(0, 0);
} else {
mediaPlayer.setVolume(1, 1);
}
mediaPlayer.start();
if (ivThumbnail.getVisibility() == View.VISIBLE) {
ivThumbnail.setVisibility(View.GONE);
}
break;
case Constants.PHOTO:
ivThumbnail.setVisibility(View.VISIBLE);
setThumbnailForClip(ivThumbnail, currentlyPlayingCard);
break;
}
}
private void pausePlayback() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
if (narrationPlayer != null && narrationPlayer.isPlaying()) {
narrationPlayer.pause();
}
}
private void resumePlayback() {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
if (narrationPlayer != null && !narrationPlayer.isPlaying()) {
narrationPlayer.start();
}
}
private void stopPlayback() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
}
if (narrationPlayer != null && narrationPlayer.isPlaying()) {
narrationPlayer.stop();
narrationPlayer.reset();
}
currentlyPlayingCard = (ClipCard) mediaCards.get(0);
currentPhotoElapsedTime = 0;
}
private void release() {
if (narrationPlayer != null) narrationPlayer.release();
if (mediaPlayer != null) mediaPlayer.release();
}
/**
* Override to advance recording state if playback is complete
*/
@Override
protected void advanceToNextClip(MediaPlayer player) {
advancingClip = true;
int currentClipIdx = mediaCards.indexOf(currentlyPlayingCard);
if (currentClipIdx == (mediaCards.size() - 1)) {
// We've played through all the clips
if (mRecordNarrationState == RecordNarrationState.RECORDING) {
stopRecordingNarration();
ivThumbnail.post(new Runnable() {
@Override
public void run() {
changeRecordNarrationStateChanged(RecordNarrationState.STOPPED);
}
});
}
}
// We need to check the current clip index *before* calling super(), which will advance it
Uri video;
if (currentClipIdx == (mediaCards.size() - 1)) {
// We've played through all the clips
Log.i(TAG, "Played all clips. stopping");
isPlaying = false;
stopPlayback();
} else {
// Advance to next clip
currentlyPlayingCard = (ClipCard) mediaCards.get(++currentClipIdx);
Log.i(TAG, "Advancing to next clip " + mediaCards.indexOf(currentlyPlayingCard));
}
switch (currentlyPlayingCard.getMedium()) {
case Constants.VIDEO:
tvVideo.setVisibility(View.VISIBLE); // In case previous card wasn't video medium
video = Uri.parse(currentlyPlayingCard.getSelectedMediaFile().getPath());
try {
// Don't set isPlaying false. We're only 'stopping' to switch media sources
player.stop();
player.reset();
Log.i(TAG, "Setting player data source " + video.toString());
player.setDataSource(mContext, video);
player.setSurface(surface);
player.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
break;
case Constants.PHOTO:
Log.i(TAG, "set currentelapsedtime to 0");
if (mediaCards.indexOf(currentlyPlayingCard) == 0) {
// Stop playback. With video / audio this would be handled onPreparedListener
isPlaying = false;
stopPlayback();
}
if (ivThumbnail != null) {
ivThumbnail.post(new Runnable() {
@Override
public void run() {
setThumbnailForClip(ivThumbnail, currentlyPlayingCard);
if (!isPlaying && sbPlaybackProgress != null) sbPlaybackProgress.setProgress(0);
advancingClip = false;
}
});
}
break;
}
}
}
}
|
package ua.naiksoftware.stomp;
import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Completable;
import io.reactivex.CompletableSource;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.PublishSubject;
import ua.naiksoftware.stomp.dto.StompCommand;
import ua.naiksoftware.stomp.dto.StompMessage;
import ua.naiksoftware.stomp.pathmatcher.PathMatcher;
import ua.naiksoftware.stomp.pathmatcher.SimplePathMatcher;
import ua.naiksoftware.stomp.provider.ConnectionProvider;
import ua.naiksoftware.stomp.dto.LifecycleEvent;
import ua.naiksoftware.stomp.dto.StompHeader;
public class StompClient {
private static final String TAG = StompClient.class.getSimpleName();
public static final String SUPPORTED_VERSIONS = "1.1,1.2";
public static final String DEFAULT_ACK = "auto";
private final ConnectionProvider connectionProvider;
private ConcurrentHashMap<String, String> topics;
private boolean legacyWhitespace;
private PublishSubject<StompMessage> messageStream;
private BehaviorSubject<Boolean> connectionStream;
private ConcurrentHashMap<String, Flowable<StompMessage>> streamMap;
private PathMatcher pathMatcher;
private Disposable lifecycleDisposable;
private Disposable messagesDisposable;
private PublishSubject<LifecycleEvent> lifecyclePublishSubject;
private List<StompHeader> headers;
private HeartBeatTask heartBeatTask;
public StompClient(ConnectionProvider connectionProvider) {
this.connectionProvider = connectionProvider;
streamMap = new ConcurrentHashMap<>();
lifecyclePublishSubject = PublishSubject.create();
pathMatcher = new SimplePathMatcher();
heartBeatTask = new HeartBeatTask(this::sendHeartBeat, () -> {
lifecyclePublishSubject.onNext(new LifecycleEvent(LifecycleEvent.Type.FAILED_SERVER_HEARTBEAT));
});
}
/**
* Sets the heartbeat interval to request from the server.
* <p>
* Not very useful yet, because we don't have any heartbeat logic on our side.
*
* @param ms heartbeat time in milliseconds
*/
public StompClient withServerHeartbeat(int ms) {
heartBeatTask.setServerHeartbeat(ms);
return this;
}
/**
* Sets the heartbeat interval that client propose to send.
* <p>
* Not very useful yet, because we don't have any heartbeat logic on our side.
*
* @param ms heartbeat time in milliseconds
*/
public StompClient withClientHeartbeat(int ms) {
heartBeatTask.setClientHeartbeat(ms);
return this;
}
/**
* Connect without reconnect if connected
*/
public void connect() {
connect(null);
}
/**
* Connect to websocket. If already connected, this will silently fail.
*
* @param _headers HTTP headers to send in the INITIAL REQUEST, i.e. during the protocol upgrade
*/
public void connect(@Nullable List<StompHeader> _headers) {
Log.d(TAG, "Connect");
this.headers = _headers;
if (isConnected()) {
Log.d(TAG, "Already connected, ignore");
return;
}
lifecycleDisposable = connectionProvider.lifecycle()
.subscribe(lifecycleEvent -> {
switch (lifecycleEvent.getType()) {
case OPENED:
List<StompHeader> headers = new ArrayList<>();
headers.add(new StompHeader(StompHeader.VERSION, SUPPORTED_VERSIONS));
headers.add(new StompHeader(StompHeader.HEART_BEAT,
heartBeatTask.getClientHeartbeat() + "," + heartBeatTask.getServerHeartbeat()));
if (_headers != null) headers.addAll(_headers);
connectionProvider.send(new StompMessage(StompCommand.CONNECT, headers, null).compile(legacyWhitespace))
.subscribe(() -> {
Log.d(TAG, "Publish open");
lifecyclePublishSubject.onNext(lifecycleEvent);
});
break;
case CLOSED:
Log.d(TAG, "Socket closed");
disconnect();
break;
case ERROR:
Log.d(TAG, "Socket closed with error");
lifecyclePublishSubject.onNext(lifecycleEvent);
break;
}
});
messagesDisposable = connectionProvider.messages()
.map(StompMessage::from)
.filter(heartBeatTask::consumeHeartBeat)
.doOnNext(getMessageStream()::onNext)
.filter(msg -> msg.getStompCommand().equals(StompCommand.CONNECTED))
.subscribe(stompMessage -> {
getConnectionStream().onNext(true);
});
}
synchronized private BehaviorSubject<Boolean> getConnectionStream() {
if (connectionStream == null || connectionStream.hasComplete()) {
connectionStream = BehaviorSubject.createDefault(false);
}
return connectionStream;
}
synchronized private PublishSubject<StompMessage> getMessageStream() {
if (messageStream == null || messageStream.hasComplete()) {
messageStream = PublishSubject.create();
}
return messageStream;
}
public Completable send(String destination) {
return send(destination, null);
}
public Completable send(String destination, String data) {
return send(new StompMessage(
StompCommand.SEND,
Collections.singletonList(new StompHeader(StompHeader.DESTINATION, destination)),
data));
}
public Completable send(@NonNull StompMessage stompMessage) {
Completable completable = connectionProvider.send(stompMessage.compile(legacyWhitespace));
CompletableSource connectionComplete = getConnectionStream()
.filter(isConnected -> isConnected)
.firstElement().ignoreElement();
return completable
.startWith(connectionComplete);
}
@SuppressLint("CheckResult")
private void sendHeartBeat(@NonNull String pingMessage) {
Completable completable = connectionProvider.send(pingMessage);
CompletableSource connectionComplete = getConnectionStream()
.filter(isConnected -> isConnected)
.firstElement().ignoreElement();
completable.startWith(connectionComplete)
.onErrorComplete()
.subscribe();
}
public Flowable<LifecycleEvent> lifecycle() {
return lifecyclePublishSubject.toFlowable(BackpressureStrategy.BUFFER);
}
/**
* Disconnect from server, and then reconnect with the last-used headers
*/
@SuppressLint("CheckResult")
public void reconnect() {
disconnectCompletable()
.subscribe(() -> connect(headers),
e -> Log.e(TAG, "Disconnect error", e));
}
@SuppressLint("CheckResult")
public void disconnect() {
disconnectCompletable().subscribe(() -> {
}, e -> Log.e(TAG, "Disconnect error", e));
}
public Completable disconnectCompletable() {
heartBeatTask.shutdown();
if (lifecycleDisposable != null) {
lifecycleDisposable.dispose();
}
if (messagesDisposable != null) {
messagesDisposable.dispose();
}
return connectionProvider.disconnect()
.doFinally(() -> {
Log.d(TAG, "Stomp disconnected");
getConnectionStream().onComplete();
getMessageStream().onComplete();
lifecyclePublishSubject.onNext(new LifecycleEvent(LifecycleEvent.Type.CLOSED));
});
}
public Flowable<StompMessage> topic(String destinationPath) {
return topic(destinationPath, null);
}
public Flowable<StompMessage> topic(@NonNull String destPath, List<StompHeader> headerList) {
if (destPath == null)
return Flowable.error(new IllegalArgumentException("Topic path cannot be null"));
else if (!streamMap.containsKey(destPath))
streamMap.put(destPath,
subscribePath(destPath, headerList).andThen(
getMessageStream()
.filter(msg -> pathMatcher.matches(destPath, msg))
.toFlowable(BackpressureStrategy.BUFFER)
.doFinally(() -> unsubscribePath(destPath).subscribe())
.share())
);
return streamMap.get(destPath);
}
private Completable subscribePath(String destinationPath, @Nullable List<StompHeader> headerList) {
String topicId = UUID.randomUUID().toString();
if (topics == null) topics = new ConcurrentHashMap<>();
// Only continue if we don't already have a subscription to the topic
if (topics.containsKey(destinationPath)) {
Log.d(TAG, "Attempted to subscribe to already-subscribed path!");
return Completable.complete();
}
topics.put(destinationPath, topicId);
List<StompHeader> headers = new ArrayList<>();
headers.add(new StompHeader(StompHeader.ID, topicId));
headers.add(new StompHeader(StompHeader.DESTINATION, destinationPath));
headers.add(new StompHeader(StompHeader.ACK, DEFAULT_ACK));
if (headerList != null) headers.addAll(headerList);
return send(new StompMessage(StompCommand.SUBSCRIBE,
headers, null));
}
private Completable unsubscribePath(String dest) {
streamMap.remove(dest);
String topicId = topics.get(dest);
topics.remove(dest);
Log.d(TAG, "Unsubscribe path: " + dest + " id: " + topicId);
return send(new StompMessage(StompCommand.UNSUBSCRIBE,
Collections.singletonList(new StompHeader(StompHeader.ID, topicId)), null)).onErrorComplete();
}
/**
* Set the wildcard or other matcher for Topic subscription.
* <p>
* Right now, the only options are simple, rmq supported.
* But you can write you own matcher by implementing {@link PathMatcher}
* <p>
* When set to {@link ua.naiksoftware.stomp.pathmatcher.RabbitPathMatcher}, topic subscription allows for RMQ-style wildcards.
* <p>
*
* @param pathMatcher Set to {@link SimplePathMatcher} by default
*/
public void setPathMatcher(PathMatcher pathMatcher) {
this.pathMatcher = pathMatcher;
}
public boolean isConnected() {
return getConnectionStream().getValue();
}
public void setLegacyWhitespace(boolean legacyWhitespace) {
this.legacyWhitespace = legacyWhitespace;
}
}
|
package com.jme3.renderer.lwjgl;
import com.jme3.light.LightList;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.StencilOperation;
import com.jme3.material.RenderState.TestFunction;
import com.jme3.math.*;
import com.jme3.renderer.*;
import com.jme3.scene.Mesh;
import com.jme3.scene.Mesh.Mode;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Format;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.shader.Attribute;
import com.jme3.shader.Shader;
import com.jme3.shader.Shader.ShaderSource;
import com.jme3.shader.Shader.ShaderType;
import com.jme3.shader.Uniform;
import com.jme3.texture.FrameBuffer;
import com.jme3.texture.FrameBuffer.RenderBuffer;
import com.jme3.texture.Image;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapAxis;
import com.jme3.util.*;
import java.nio.*;
import java.util.EnumSet;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jme3tools.converters.MipMapGenerator;
import jme3tools.shader.ShaderDebug;
import org.lwjgl.opengl.*;
import static org.lwjgl.opengl.ARBTextureMultisample.*;
import static org.lwjgl.opengl.EXTFramebufferBlit.*;
import static org.lwjgl.opengl.EXTFramebufferMultisample.*;
import static org.lwjgl.opengl.EXTFramebufferObject.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL14.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
//import static org.lwjgl.opengl.ARBDrawInstanced.*;
public class LwjglRenderer implements Renderer {
private static final Logger logger = Logger.getLogger(LwjglRenderer.class.getName());
private static final boolean VALIDATE_SHADER = false;
private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250);
private final StringBuilder stringBuf = new StringBuilder(250);
private final IntBuffer intBuf1 = BufferUtils.createIntBuffer(1);
private final IntBuffer intBuf16 = BufferUtils.createIntBuffer(16);
private final RenderContext context = new RenderContext();
private final NativeObjectManager objManager = new NativeObjectManager();
private final EnumSet<Caps> caps = EnumSet.noneOf(Caps.class);
// current state
private Shader boundShader;
private int initialDrawBuf, initialReadBuf;
private int glslVer;
private int vertexTextureUnits;
private int fragTextureUnits;
private int vertexUniforms;
private int fragUniforms;
private int vertexAttribs;
private int maxFBOSamples;
private int maxFBOAttachs;
private int maxMRTFBOAttachs;
private int maxRBSize;
private int maxTexSize;
private int maxCubeTexSize;
private int maxVertCount;
private int maxTriCount;
private int maxColorTexSamples;
private int maxDepthTexSamples;
private FrameBuffer lastFb = null;
private FrameBuffer mainFbOverride = null;
private final Statistics statistics = new Statistics();
private int vpX, vpY, vpW, vpH;
private int clipX, clipY, clipW, clipH;
public LwjglRenderer() {
}
protected void updateNameBuffer() {
int len = stringBuf.length();
nameBuf.position(0);
nameBuf.limit(len);
for (int i = 0; i < len; i++) {
nameBuf.put((byte) stringBuf.charAt(i));
}
nameBuf.rewind();
}
public Statistics getStatistics() {
return statistics;
}
public EnumSet<Caps> getCaps() {
return caps;
}
@SuppressWarnings("fallthrough")
public void initialize() {
ContextCapabilities ctxCaps = GLContext.getCapabilities();
if (ctxCaps.OpenGL20) {
caps.add(Caps.OpenGL20);
if (ctxCaps.OpenGL21) {
caps.add(Caps.OpenGL21);
if (ctxCaps.OpenGL30) {
caps.add(Caps.OpenGL30);
if (ctxCaps.OpenGL31) {
caps.add(Caps.OpenGL31);
if (ctxCaps.OpenGL32) {
caps.add(Caps.OpenGL32);
}
}
}
}
}
String versionStr = null;
if (ctxCaps.OpenGL20) {
versionStr = glGetString(GL_SHADING_LANGUAGE_VERSION);
}
if (versionStr == null || versionStr.equals("")) {
glslVer = -1;
throw new UnsupportedOperationException("GLSL and OpenGL2 is "
+ "required for the LWJGL "
+ "renderer!");
}
// Fix issue in TestRenderToMemory when GL_FRONT is the main
// buffer being used.
initialDrawBuf = glGetInteger(GL_DRAW_BUFFER);
initialReadBuf = glGetInteger(GL_READ_BUFFER);
// XXX: This has to be GL_BACK for canvas on Mac
// Since initialDrawBuf is GL_FRONT for pbuffer, gotta
// change this value later on ...
// initialDrawBuf = GL_BACK;
// initialReadBuf = GL_BACK;
int spaceIdx = versionStr.indexOf(" ");
if (spaceIdx >= 1) {
versionStr = versionStr.substring(0, spaceIdx);
}
float version = Float.parseFloat(versionStr);
glslVer = (int) (version * 100);
switch (glslVer) {
default:
if (glslVer < 400) {
break;
}
// so that future OpenGL revisions wont break jme3
// fall through intentional
case 400:
case 330:
case 150:
caps.add(Caps.GLSL150);
case 140:
caps.add(Caps.GLSL140);
case 130:
caps.add(Caps.GLSL130);
case 120:
caps.add(Caps.GLSL120);
case 110:
caps.add(Caps.GLSL110);
case 100:
caps.add(Caps.GLSL100);
break;
}
if (!caps.contains(Caps.GLSL100)) {
logger.log(Level.WARNING, "Force-adding GLSL100 support, since OpenGL2 is supported.");
caps.add(Caps.GLSL100);
}
glGetInteger(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, intBuf16);
vertexTextureUnits = intBuf16.get(0);
logger.log(Level.FINER, "VTF Units: {0}", vertexTextureUnits);
if (vertexTextureUnits > 0) {
caps.add(Caps.VertexTextureFetch);
}
glGetInteger(GL_MAX_TEXTURE_IMAGE_UNITS, intBuf16);
fragTextureUnits = intBuf16.get(0);
logger.log(Level.FINER, "Texture Units: {0}", fragTextureUnits);
glGetInteger(GL_MAX_VERTEX_UNIFORM_COMPONENTS, intBuf16);
vertexUniforms = intBuf16.get(0);
logger.log(Level.FINER, "Vertex Uniforms: {0}", vertexUniforms);
glGetInteger(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, intBuf16);
fragUniforms = intBuf16.get(0);
logger.log(Level.FINER, "Fragment Uniforms: {0}", fragUniforms);
glGetInteger(GL_MAX_VERTEX_ATTRIBS, intBuf16);
vertexAttribs = intBuf16.get(0);
logger.log(Level.FINER, "Vertex Attributes: {0}", vertexAttribs);
glGetInteger(GL_SUBPIXEL_BITS, intBuf16);
int subpixelBits = intBuf16.get(0);
logger.log(Level.FINER, "Subpixel Bits: {0}", subpixelBits);
glGetInteger(GL_MAX_ELEMENTS_VERTICES, intBuf16);
maxVertCount = intBuf16.get(0);
logger.log(Level.FINER, "Preferred Batch Vertex Count: {0}", maxVertCount);
glGetInteger(GL_MAX_ELEMENTS_INDICES, intBuf16);
maxTriCount = intBuf16.get(0);
logger.log(Level.FINER, "Preferred Batch Index Count: {0}", maxTriCount);
glGetInteger(GL_MAX_TEXTURE_SIZE, intBuf16);
maxTexSize = intBuf16.get(0);
logger.log(Level.FINER, "Maximum Texture Resolution: {0}", maxTexSize);
glGetInteger(GL_MAX_CUBE_MAP_TEXTURE_SIZE, intBuf16);
maxCubeTexSize = intBuf16.get(0);
logger.log(Level.FINER, "Maximum CubeMap Resolution: {0}", maxCubeTexSize);
if (ctxCaps.GL_ARB_color_buffer_float) {
// XXX: Require both 16 and 32 bit float support for FloatColorBuffer.
if (ctxCaps.GL_ARB_half_float_pixel) {
caps.add(Caps.FloatColorBuffer);
}
}
if (ctxCaps.GL_ARB_depth_buffer_float) {
caps.add(Caps.FloatDepthBuffer);
}
if (ctxCaps.OpenGL30) {
caps.add(Caps.PackedDepthStencilBuffer);
}
if (ctxCaps.GL_ARB_draw_instanced) {
caps.add(Caps.MeshInstancing);
}
if (ctxCaps.GL_ARB_fragment_program) {
caps.add(Caps.ARBprogram);
}
if (ctxCaps.GL_ARB_texture_buffer_object) {
caps.add(Caps.TextureBuffer);
}
if (ctxCaps.GL_ARB_texture_float) {
if (ctxCaps.GL_ARB_half_float_pixel) {
caps.add(Caps.FloatTexture);
}
}
if (ctxCaps.GL_ARB_vertex_array_object) {
caps.add(Caps.VertexBufferArray);
}
if (ctxCaps.GL_ARB_texture_non_power_of_two) {
caps.add(Caps.NonPowerOfTwoTextures);
} else {
logger.log(Level.WARNING, "Your graphics card does not "
+ "support non-power-of-2 textures. "
+ "Some features might not work.");
}
boolean latc = ctxCaps.GL_EXT_texture_compression_latc;
if (latc) {
caps.add(Caps.TextureCompressionLATC);
}
if (ctxCaps.GL_EXT_packed_float) {
caps.add(Caps.PackedFloatColorBuffer);
if (ctxCaps.GL_ARB_half_float_pixel) {
// because textures are usually uploaded as RGB16F
// need half-float pixel
caps.add(Caps.PackedFloatTexture);
}
}
if (ctxCaps.GL_EXT_texture_array) {
caps.add(Caps.TextureArray);
}
if (ctxCaps.GL_EXT_texture_shared_exponent) {
caps.add(Caps.SharedExponentTexture);
}
if (ctxCaps.GL_EXT_framebuffer_object) {
caps.add(Caps.FrameBuffer);
glGetInteger(GL_MAX_RENDERBUFFER_SIZE_EXT, intBuf16);
maxRBSize = intBuf16.get(0);
logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize);
glGetInteger(GL_MAX_COLOR_ATTACHMENTS_EXT, intBuf16);
maxFBOAttachs = intBuf16.get(0);
logger.log(Level.FINER, "FBO Max renderbuffers: {0}", maxFBOAttachs);
if (ctxCaps.GL_EXT_framebuffer_multisample) {
caps.add(Caps.FrameBufferMultisample);
glGetInteger(GL_MAX_SAMPLES_EXT, intBuf16);
maxFBOSamples = intBuf16.get(0);
logger.log(Level.FINER, "FBO Max Samples: {0}", maxFBOSamples);
}
if (ctxCaps.GL_ARB_texture_multisample) {
caps.add(Caps.TextureMultisample);
glGetInteger(GL_MAX_COLOR_TEXTURE_SAMPLES, intBuf16);
maxColorTexSamples = intBuf16.get(0);
logger.log(Level.FINER, "Texture Multisample Color Samples: {0}", maxColorTexSamples);
glGetInteger(GL_MAX_DEPTH_TEXTURE_SAMPLES, intBuf16);
maxDepthTexSamples = intBuf16.get(0);
logger.log(Level.FINER, "Texture Multisample Depth Samples: {0}", maxDepthTexSamples);
}
glGetInteger(GL_MAX_DRAW_BUFFERS, intBuf16);
maxMRTFBOAttachs = intBuf16.get(0);
if (maxMRTFBOAttachs > 1) {
caps.add(Caps.FrameBufferMRT);
logger.log(Level.FINER, "FBO Max MRT renderbuffers: {0}", maxMRTFBOAttachs);
}
// if (ctxCaps.GL_ARB_draw_buffers) {
// caps.add(Caps.FrameBufferMRT);
// glGetInteger(ARBDrawBuffers.GL_MAX_DRAW_BUFFERS_ARB, intBuf16);
// maxMRTFBOAttachs = intBuf16.get(0);
// logger.log(Level.FINER, "FBO Max MRT renderbuffers: {0}", maxMRTFBOAttachs);
}
if (ctxCaps.GL_ARB_multisample) {
glGetInteger(ARBMultisample.GL_SAMPLE_BUFFERS_ARB, intBuf16);
boolean available = intBuf16.get(0) != 0;
glGetInteger(ARBMultisample.GL_SAMPLES_ARB, intBuf16);
int samples = intBuf16.get(0);
logger.log(Level.FINER, "Samples: {0}", samples);
boolean enabled = glIsEnabled(ARBMultisample.GL_MULTISAMPLE_ARB);
if (samples > 0 && available && !enabled) {
glEnable(ARBMultisample.GL_MULTISAMPLE_ARB);
}
}
logger.log(Level.INFO, "Caps: {0}", caps);
}
public void invalidateState() {
context.reset();
boundShader = null;
lastFb = null;
initialDrawBuf = glGetInteger(GL_DRAW_BUFFER);
initialReadBuf = glGetInteger(GL_READ_BUFFER);
}
public void resetGLObjects() {
logger.log(Level.INFO, "Reseting objects and invalidating state");
objManager.resetObjects();
statistics.clearMemory();
invalidateState();
}
public void cleanup() {
logger.log(Level.INFO, "Deleting objects and invalidating state");
objManager.deleteAllObjects(this);
statistics.clearMemory();
invalidateState();
}
private void checkCap(Caps cap) {
if (!caps.contains(cap)) {
throw new UnsupportedOperationException("Required capability missing: " + cap.name());
}
}
public void setDepthRange(float start, float end) {
glDepthRange(start, end);
}
public void clearBuffers(boolean color, boolean depth, boolean stencil) {
int bits = 0;
if (color) {
//See explanations of the depth below, we must enable color write to be able to clear the color buffer
if (context.colorWriteEnabled == false) {
glColorMask(true, true, true, true);
context.colorWriteEnabled = true;
}
bits = GL_COLOR_BUFFER_BIT;
}
if (depth) {
//glClear(GL_DEPTH_BUFFER_BIT) seems to not work when glDepthMask is false
//here s some link on openl board
//if depth clear is requested, we enable the depthMask
if (context.depthWriteEnabled == false) {
glDepthMask(true);
context.depthWriteEnabled = true;
}
bits |= GL_DEPTH_BUFFER_BIT;
}
if (stencil) {
bits |= GL_STENCIL_BUFFER_BIT;
}
if (bits != 0) {
glClear(bits);
}
}
public void setBackgroundColor(ColorRGBA color) {
glClearColor(color.r, color.g, color.b, color.a);
}
public void setAlphaToCoverage(boolean value) {
if (caps.contains(Caps.Multisample)) {
if (value) {
glEnable(ARBMultisample.GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
} else {
glDisable(ARBMultisample.GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
}
}
}
public void applyRenderState(RenderState state) {
if (state.isWireframe() && !context.wireframe) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
context.wireframe = true;
} else if (!state.isWireframe() && context.wireframe) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
context.wireframe = false;
}
if (state.isDepthTest() && !context.depthTestEnabled) {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
context.depthTestEnabled = true;
} else if (!state.isDepthTest() && context.depthTestEnabled) {
glDisable(GL_DEPTH_TEST);
context.depthTestEnabled = false;
}
if (state.isAlphaTest() && !context.alphaTestEnabled) {
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, state.getAlphaFallOff());
context.alphaTestEnabled = true;
} else if (!state.isAlphaTest() && context.alphaTestEnabled) {
glDisable(GL_ALPHA_TEST);
context.alphaTestEnabled = false;
}
if (state.isDepthWrite() && !context.depthWriteEnabled) {
glDepthMask(true);
context.depthWriteEnabled = true;
} else if (!state.isDepthWrite() && context.depthWriteEnabled) {
glDepthMask(false);
context.depthWriteEnabled = false;
}
if (state.isColorWrite() && !context.colorWriteEnabled) {
glColorMask(true, true, true, true);
context.colorWriteEnabled = true;
} else if (!state.isColorWrite() && context.colorWriteEnabled) {
glColorMask(false, false, false, false);
context.colorWriteEnabled = false;
}
if (state.isPointSprite() && !context.pointSprite) {
// Only enable/disable sprite
if (context.boundTextures[0] != null) {
if (context.boundTextureUnit != 0) {
glActiveTexture(GL_TEXTURE0);
context.boundTextureUnit = 0;
}
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
}
context.pointSprite = true;
} else if (!state.isPointSprite() && context.pointSprite) {
if (context.boundTextures[0] != null) {
if (context.boundTextureUnit != 0) {
glActiveTexture(GL_TEXTURE0);
context.boundTextureUnit = 0;
}
glDisable(GL_POINT_SPRITE);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
context.pointSprite = false;
}
}
if (state.isPolyOffset()) {
if (!context.polyOffsetEnabled) {
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(state.getPolyOffsetFactor(),
state.getPolyOffsetUnits());
context.polyOffsetEnabled = true;
context.polyOffsetFactor = state.getPolyOffsetFactor();
context.polyOffsetUnits = state.getPolyOffsetUnits();
} else {
if (state.getPolyOffsetFactor() != context.polyOffsetFactor
|| state.getPolyOffsetUnits() != context.polyOffsetUnits) {
glPolygonOffset(state.getPolyOffsetFactor(),
state.getPolyOffsetUnits());
context.polyOffsetFactor = state.getPolyOffsetFactor();
context.polyOffsetUnits = state.getPolyOffsetUnits();
}
}
} else {
if (context.polyOffsetEnabled) {
glDisable(GL_POLYGON_OFFSET_FILL);
context.polyOffsetEnabled = false;
context.polyOffsetFactor = 0;
context.polyOffsetUnits = 0;
}
}
if (state.getFaceCullMode() != context.cullMode) {
if (state.getFaceCullMode() == RenderState.FaceCullMode.Off) {
glDisable(GL_CULL_FACE);
} else {
glEnable(GL_CULL_FACE);
}
switch (state.getFaceCullMode()) {
case Off:
break;
case Back:
glCullFace(GL_BACK);
break;
case Front:
glCullFace(GL_FRONT);
break;
case FrontAndBack:
glCullFace(GL_FRONT_AND_BACK);
break;
default:
throw new UnsupportedOperationException("Unrecognized face cull mode: "
+ state.getFaceCullMode());
}
context.cullMode = state.getFaceCullMode();
}
if (state.getBlendMode() != context.blendMode) {
if (state.getBlendMode() == RenderState.BlendMode.Off) {
glDisable(GL_BLEND);
} else {
glEnable(GL_BLEND);
switch (state.getBlendMode()) {
case Off:
break;
case Additive:
glBlendFunc(GL_ONE, GL_ONE);
break;
case AlphaAdditive:
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
case Color:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
break;
case Alpha:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case PremultAlpha:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
break;
case Modulate:
glBlendFunc(GL_DST_COLOR, GL_ZERO);
break;
case ModulateX2:
glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
break;
default:
throw new UnsupportedOperationException("Unrecognized blend mode: "
+ state.getBlendMode());
}
}
context.blendMode = state.getBlendMode();
}
if (context.stencilTest != state.isStencilTest()
|| context.frontStencilStencilFailOperation != state.getFrontStencilStencilFailOperation()
|| context.frontStencilDepthFailOperation != state.getFrontStencilDepthFailOperation()
|| context.frontStencilDepthPassOperation != state.getFrontStencilDepthPassOperation()
|| context.backStencilStencilFailOperation != state.getBackStencilStencilFailOperation()
|| context.backStencilDepthFailOperation != state.getBackStencilDepthFailOperation()
|| context.backStencilDepthPassOperation != state.getBackStencilDepthPassOperation()
|| context.frontStencilFunction != state.getFrontStencilFunction()
|| context.backStencilFunction != state.getBackStencilFunction()) {
context.frontStencilStencilFailOperation = state.getFrontStencilStencilFailOperation(); //terrible looking, I know
context.frontStencilDepthFailOperation = state.getFrontStencilDepthFailOperation();
context.frontStencilDepthPassOperation = state.getFrontStencilDepthPassOperation();
context.backStencilStencilFailOperation = state.getBackStencilStencilFailOperation();
context.backStencilDepthFailOperation = state.getBackStencilDepthFailOperation();
context.backStencilDepthPassOperation = state.getBackStencilDepthPassOperation();
context.frontStencilFunction = state.getFrontStencilFunction();
context.backStencilFunction = state.getBackStencilFunction();
if (state.isStencilTest()) {
glEnable(GL_STENCIL_TEST);
glStencilOpSeparate(GL_FRONT,
convertStencilOperation(state.getFrontStencilStencilFailOperation()),
convertStencilOperation(state.getFrontStencilDepthFailOperation()),
convertStencilOperation(state.getFrontStencilDepthPassOperation()));
glStencilOpSeparate(GL_BACK,
convertStencilOperation(state.getBackStencilStencilFailOperation()),
convertStencilOperation(state.getBackStencilDepthFailOperation()),
convertStencilOperation(state.getBackStencilDepthPassOperation()));
glStencilFuncSeparate(GL_FRONT,
convertTestFunction(state.getFrontStencilFunction()),
0, Integer.MAX_VALUE);
glStencilFuncSeparate(GL_BACK,
convertTestFunction(state.getBackStencilFunction()),
0, Integer.MAX_VALUE);
} else {
glDisable(GL_STENCIL_TEST);
}
}
}
private int convertStencilOperation(StencilOperation stencilOp) {
switch (stencilOp) {
case Keep:
return GL_KEEP;
case Zero:
return GL_ZERO;
case Replace:
return GL_REPLACE;
case Increment:
return GL_INCR;
case IncrementWrap:
return GL_INCR_WRAP;
case Decrement:
return GL_DECR;
case DecrementWrap:
return GL_DECR_WRAP;
case Invert:
return GL_INVERT;
default:
throw new UnsupportedOperationException("Unrecognized stencil operation: " + stencilOp);
}
}
private int convertTestFunction(TestFunction testFunc) {
switch (testFunc) {
case Never:
return GL_NEVER;
case Less:
return GL_LESS;
case LessOrEqual:
return GL_LEQUAL;
case Greater:
return GL_GREATER;
case GreaterOrEqual:
return GL_GEQUAL;
case Equal:
return GL_EQUAL;
case NotEqual:
return GL_NOTEQUAL;
case Always:
return GL_ALWAYS;
default:
throw new UnsupportedOperationException("Unrecognized test function: " + testFunc);
}
}
public void setViewPort(int x, int y, int w, int h) {
if (x != vpX || vpY != y || vpW != w || vpH != h) {
glViewport(x, y, w, h);
vpX = x;
vpY = y;
vpW = w;
vpH = h;
}
}
public void setClipRect(int x, int y, int width, int height) {
if (!context.clipRectEnabled) {
glEnable(GL_SCISSOR_TEST);
context.clipRectEnabled = true;
}
if (clipX != x || clipY != y || clipW != width || clipH != height) {
glScissor(x, y, width, height);
clipX = x;
clipY = y;
clipW = width;
clipH = height;
}
}
public void clearClipRect() {
if (context.clipRectEnabled) {
glDisable(GL_SCISSOR_TEST);
context.clipRectEnabled = false;
clipX = 0;
clipY = 0;
clipW = 0;
clipH = 0;
}
}
public void onFrame() {
objManager.deleteUnused(this);
// statistics.clearFrame();
}
public void setWorldMatrix(Matrix4f worldMatrix) {
}
public void setViewProjectionMatrices(Matrix4f viewMatrix, Matrix4f projMatrix) {
}
protected void updateUniformLocation(Shader shader, Uniform uniform) {
stringBuf.setLength(0);
stringBuf.append(uniform.getName()).append('\0');
updateNameBuffer();
int loc = glGetUniformLocation(shader.getId(), nameBuf);
if (loc < 0) {
uniform.setLocation(-1);
// uniform is not declared in shader
logger.log(Level.INFO, "Uniform {0} is not declared in shader {1}.", new Object[]{uniform.getName(), shader.getSources()});
} else {
uniform.setLocation(loc);
}
}
protected void bindProgram(Shader shader) {
int shaderId = shader.getId();
if (context.boundShaderProgram != shaderId) {
glUseProgram(shaderId);
statistics.onShaderUse(shader, true);
boundShader = shader;
context.boundShaderProgram = shaderId;
} else {
statistics.onShaderUse(shader, false);
}
}
protected void updateUniform(Shader shader, Uniform uniform) {
int shaderId = shader.getId();
assert uniform.getName() != null;
assert shader.getId() > 0;
bindProgram(shader);
int loc = uniform.getLocation();
if (loc == -1) {
return;
}
if (loc == -2) {
// get uniform location
updateUniformLocation(shader, uniform);
if (uniform.getLocation() == -1) {
// not declared, ignore
uniform.clearUpdateNeeded();
return;
}
loc = uniform.getLocation();
}
if (uniform.getVarType() == null) {
return; // value not set yet..
}
statistics.onUniformSet();
uniform.clearUpdateNeeded();
FloatBuffer fb;
switch (uniform.getVarType()) {
case Float:
Float f = (Float) uniform.getValue();
glUniform1f(loc, f.floatValue());
break;
case Vector2:
Vector2f v2 = (Vector2f) uniform.getValue();
glUniform2f(loc, v2.getX(), v2.getY());
break;
case Vector3:
Vector3f v3 = (Vector3f) uniform.getValue();
glUniform3f(loc, v3.getX(), v3.getY(), v3.getZ());
break;
case Vector4:
Object val = uniform.getValue();
if (val instanceof ColorRGBA) {
ColorRGBA c = (ColorRGBA) val;
glUniform4f(loc, c.r, c.g, c.b, c.a);
} else if (val instanceof Vector4f) {
Vector4f c = (Vector4f) val;
glUniform4f(loc, c.x, c.y, c.z, c.w);
} else {
Quaternion c = (Quaternion) uniform.getValue();
glUniform4f(loc, c.getX(), c.getY(), c.getZ(), c.getW());
}
break;
case Boolean:
Boolean b = (Boolean) uniform.getValue();
glUniform1i(loc, b.booleanValue() ? GL_TRUE : GL_FALSE);
break;
case Matrix3:
fb = (FloatBuffer) uniform.getValue();
assert fb.remaining() == 9;
glUniformMatrix3(loc, false, fb);
break;
case Matrix4:
fb = (FloatBuffer) uniform.getValue();
assert fb.remaining() == 16;
glUniformMatrix4(loc, false, fb);
break;
case FloatArray:
fb = (FloatBuffer) uniform.getValue();
glUniform1(loc, fb);
break;
case Vector2Array:
fb = (FloatBuffer) uniform.getValue();
glUniform2(loc, fb);
break;
case Vector3Array:
fb = (FloatBuffer) uniform.getValue();
glUniform3(loc, fb);
break;
case Vector4Array:
fb = (FloatBuffer) uniform.getValue();
glUniform4(loc, fb);
break;
case Matrix4Array:
fb = (FloatBuffer) uniform.getValue();
glUniformMatrix4(loc, false, fb);
break;
case Int:
Integer i = (Integer) uniform.getValue();
glUniform1i(loc, i.intValue());
break;
default:
throw new UnsupportedOperationException("Unsupported uniform type: " + uniform.getVarType());
}
}
protected void updateShaderUniforms(Shader shader) {
ListMap<String, Uniform> uniforms = shader.getUniformMap();
// for (Uniform uniform : shader.getUniforms()){
for (int i = 0; i < uniforms.size(); i++) {
Uniform uniform = uniforms.getValue(i);
if (uniform.isUpdateNeeded()) {
updateUniform(shader, uniform);
}
}
}
protected void resetUniformLocations(Shader shader) {
ListMap<String, Uniform> uniforms = shader.getUniformMap();
// for (Uniform uniform : shader.getUniforms()){
for (int i = 0; i < uniforms.size(); i++) {
Uniform uniform = uniforms.getValue(i);
uniform.reset(); // e.g check location again
}
}
/*
* (Non-javadoc)
* Only used for fixed-function. Ignored.
*/
public void setLighting(LightList list) {
}
public int convertShaderType(ShaderType type) {
switch (type) {
case Fragment:
return GL_FRAGMENT_SHADER;
case Vertex:
return GL_VERTEX_SHADER;
// case Geometry:
// return ARBGeometryShader4.GL_GEOMETRY_SHADER_ARB;
default:
throw new UnsupportedOperationException("Unrecognized shader type.");
}
}
public void updateShaderSourceData(ShaderSource source, String language) {
int id = source.getId();
if (id == -1) {
// create id
id = glCreateShader(convertShaderType(source.getType()));
if (id <= 0) {
throw new RendererException("Invalid ID received when trying to create shader.");
}
source.setId(id);
} else {
throw new RendererException("Cannot recompile shader source");
}
// upload shader source
// merge the defines and source code
stringBuf.setLength(0);
if (language.startsWith("GLSL")) {
int version = Integer.parseInt(language.substring(4));
if (version > 100) {
stringBuf.append("#version ");
stringBuf.append(language.substring(4));
if (version >= 150) {
stringBuf.append(" core");
}
stringBuf.append("\n");
}
}
updateNameBuffer();
byte[] definesCodeData = source.getDefines().getBytes();
byte[] sourceCodeData = source.getSource().getBytes();
ByteBuffer codeBuf = BufferUtils.createByteBuffer(nameBuf.limit()
+ definesCodeData.length
+ sourceCodeData.length);
codeBuf.put(nameBuf);
codeBuf.put(definesCodeData);
codeBuf.put(sourceCodeData);
codeBuf.flip();
glShaderSource(id, codeBuf);
glCompileShader(id);
glGetShader(id, GL_COMPILE_STATUS, intBuf1);
boolean compiledOK = intBuf1.get(0) == GL_TRUE;
String infoLog = null;
if (VALIDATE_SHADER || !compiledOK) {
// even if compile succeeded, check
// log for warnings
glGetShader(id, GL_INFO_LOG_LENGTH, intBuf1);
int length = intBuf1.get(0);
if (length > 3) {
// get infos
ByteBuffer logBuf = BufferUtils.createByteBuffer(length);
glGetShaderInfoLog(id, null, logBuf);
byte[] logBytes = new byte[length];
logBuf.get(logBytes, 0, length);
// convert to string, etc
infoLog = new String(logBytes);
}
}
if (compiledOK) {
if (infoLog != null) {
logger.log(Level.INFO, "{0} compile success\n{1}",
new Object[]{source.getName(), infoLog});
} else {
logger.log(Level.FINE, "{0} compile success", source.getName());
}
} else {
logger.log(Level.WARNING, "Bad compile of:\n{0}",
new Object[]{ShaderDebug.formatShaderSource(source.getDefines(), source.getSource(), stringBuf.toString())});
if (infoLog != null) {
throw new RendererException("compile error in:" + source + " error:" + infoLog);
} else {
throw new RendererException("compile error in:" + source + " error: <not provided>");
}
}
source.clearUpdateNeeded();
// only usable if compiled
source.setUsable(compiledOK);
if (!compiledOK) {
// make sure to dispose id cause all program's
// shaders will be cleared later.
glDeleteShader(id);
} else {
// register for cleanup since the ID is usable
// NOTE: From now on cleanup is handled
// by the parent shader object so no need
// to register.
//objManager.registerForCleanup(source);
}
}
public void updateShaderData(Shader shader) {
int id = shader.getId();
boolean needRegister = false;
if (id == -1) {
// create program
id = glCreateProgram();
if (id == 0) {
throw new RendererException("Invalid ID (" + id + ") received when trying to create shader program.");
}
shader.setId(id);
needRegister = true;
}
for (ShaderSource source : shader.getSources()) {
if (source.isUpdateNeeded()) {
updateShaderSourceData(source, shader.getLanguage());
// shader has been compiled here
}
if (!source.isUsable()) {
// it's useless.. just forget about everything..
shader.setUsable(false);
shader.clearUpdateNeeded();
return;
}
glAttachShader(id, source.getId());
}
if (caps.contains(Caps.OpenGL30)) {
// Check if GLSL version is 1.5 for shader
GL30.glBindFragDataLocation(id, 0, "outFragColor");
for(int i = 0 ; i < maxMRTFBOAttachs ; i++) {
GL30.glBindFragDataLocation(id, i, "outFragData[" + i + "]");
}
}
// link shaders to program
glLinkProgram(id);
glGetProgram(id, GL_LINK_STATUS, intBuf1);
boolean linkOK = intBuf1.get(0) == GL_TRUE;
String infoLog = null;
if (VALIDATE_SHADER || !linkOK) {
glGetProgram(id, GL_INFO_LOG_LENGTH, intBuf1);
int length = intBuf1.get(0);
if (length > 3) {
// get infos
ByteBuffer logBuf = BufferUtils.createByteBuffer(length);
glGetProgramInfoLog(id, null, logBuf);
// convert to string, etc
byte[] logBytes = new byte[length];
logBuf.get(logBytes, 0, length);
infoLog = new String(logBytes);
}
}
if (linkOK) {
if (infoLog != null) {
logger.log(Level.INFO, "shader link success. \n{0}", infoLog);
} else {
logger.fine("shader link success");
}
} else {
if (infoLog != null) {
throw new RendererException("Shader link failure, shader:" + shader + " info:" + infoLog);
} else {
throw new RendererException("Shader link failure, shader:" + shader + " info: <not provided>");
}
}
shader.clearUpdateNeeded();
if (!linkOK) {
// failure.. forget about everything
shader.resetSources();
shader.setUsable(false);
deleteShader(shader);
} else {
shader.setUsable(true);
if (needRegister) {
objManager.registerForCleanup(shader);
statistics.onNewShader();
} else {
// OpenGL spec: uniform locations may change after re-link
resetUniformLocations(shader);
}
}
}
public void setShader(Shader shader) {
if (shader == null) {
throw new IllegalArgumentException("shader cannot be null");
// if (context.boundShaderProgram > 0) {
// glUseProgram(0);
// statistics.onShaderUse(null, true);
// context.boundShaderProgram = 0;
// boundShader = null;
} else {
if (shader.isUpdateNeeded()) {
updateShaderData(shader);
}
// NOTE: might want to check if any of the
// sources need an update?
if (!shader.isUsable()) {
return;
}
assert shader.getId() > 0;
updateShaderUniforms(shader);
bindProgram(shader);
}
}
public void deleteShaderSource(ShaderSource source) {
if (source.getId() < 0) {
logger.warning("Shader source is not uploaded to GPU, cannot delete.");
return;
}
source.setUsable(false);
source.clearUpdateNeeded();
glDeleteShader(source.getId());
source.resetObject();
}
public void deleteShader(Shader shader) {
if (shader.getId() == -1) {
logger.warning("Shader is not uploaded to GPU, cannot delete.");
return;
}
for (ShaderSource source : shader.getSources()) {
if (source.getId() != -1) {
glDetachShader(shader.getId(), source.getId());
deleteShaderSource(source);
}
}
// kill all references so sources can be collected
// if needed.
shader.resetSources();
glDeleteProgram(shader.getId());
statistics.onDeleteShader();
}
public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst) {
copyFrameBuffer(src, dst, true);
}
public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyDepth) {
if (GLContext.getCapabilities().GL_EXT_framebuffer_blit) {
int srcX = 0;
int srcY = 0;
int srcW = 0;
int srcH = 0;
int dstX = 0;
int dstY = 0;
int dstW = 0;
int dstH = 0;
int prevFBO = context.boundFBO;
if (mainFbOverride != null) {
if (src == null) {
src = mainFbOverride;
}
if (dst == null) {
dst = mainFbOverride;
}
}
if (src != null && src.isUpdateNeeded()) {
updateFrameBuffer(src);
}
if (dst != null && dst.isUpdateNeeded()) {
updateFrameBuffer(dst);
}
if (src == null) {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
srcX = vpX;
srcY = vpY;
srcW = vpW;
srcH = vpH;
} else {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, src.getId());
srcW = src.getWidth();
srcH = src.getHeight();
}
if (dst == null) {
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
dstX = vpX;
dstY = vpY;
dstW = vpW - 1;
dstH = vpH - 1;
} else {
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, dst.getId());
dstW = dst.getWidth() - 1;
dstH = dst.getHeight() - 1;
}
int mask = GL_COLOR_BUFFER_BIT;
if (copyDepth) {
mask |= GL_DEPTH_BUFFER_BIT;
}
glBlitFramebufferEXT(0, 0, srcW, srcH,
0, 0, dstW, dstH, mask,
GL_NEAREST);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, prevFBO);
try {
checkFrameBufferError();
} catch (IllegalStateException ex) {
logger.log(Level.SEVERE, "Source FBO:\n{0}", src);
logger.log(Level.SEVERE, "Dest FBO:\n{0}", dst);
throw ex;
}
} else {
throw new RendererException("EXT_framebuffer_blit required.");
// TODO: support non-blit copies?
}
}
private String getTargetBufferName(int buffer) {
switch (buffer) {
case GL_NONE:
return "NONE";
case GL_FRONT:
return "GL_FRONT";
case GL_BACK:
return "GL_BACK";
default:
if (buffer >= GL_COLOR_ATTACHMENT0_EXT
&& buffer <= GL_COLOR_ATTACHMENT15_EXT) {
return "GL_COLOR_ATTACHMENT"
+ (buffer - GL_COLOR_ATTACHMENT0_EXT);
} else {
return "UNKNOWN? " + buffer;
}
}
}
private void printRealRenderBufferInfo(FrameBuffer fb, RenderBuffer rb, String name) {
System.out.println("== Renderbuffer " + name + " ==");
System.out.println("RB ID: " + rb.getId());
System.out.println("Is proper? " + glIsRenderbufferEXT(rb.getId()));
int attachment = convertAttachmentSlot(rb.getSlot());
int type = glGetFramebufferAttachmentParameterEXT(GL_DRAW_FRAMEBUFFER_EXT,
attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT);
int rbName = glGetFramebufferAttachmentParameterEXT(GL_DRAW_FRAMEBUFFER_EXT,
attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT);
switch (type) {
case GL_NONE:
System.out.println("Type: None");
break;
case GL_TEXTURE:
System.out.println("Type: Texture");
break;
case GL_RENDERBUFFER_EXT:
System.out.println("Type: Buffer");
System.out.println("RB ID: " + rbName);
break;
}
}
private void printRealFrameBufferInfo(FrameBuffer fb) {
boolean doubleBuffer = glGetBoolean(GL_DOUBLEBUFFER);
String drawBuf = getTargetBufferName(glGetInteger(GL_DRAW_BUFFER));
String readBuf = getTargetBufferName(glGetInteger(GL_READ_BUFFER));
int fbId = fb.getId();
int curDrawBinding = glGetInteger(ARBFramebufferObject.GL_DRAW_FRAMEBUFFER_BINDING);
int curReadBinding = glGetInteger(ARBFramebufferObject.GL_READ_FRAMEBUFFER_BINDING);
System.out.println("=== OpenGL FBO State ===");
System.out.println("Context doublebuffered? " + doubleBuffer);
System.out.println("FBO ID: " + fbId);
System.out.println("Is proper? " + glIsFramebufferEXT(fbId));
System.out.println("Is bound to draw? " + (fbId == curDrawBinding));
System.out.println("Is bound to read? " + (fbId == curReadBinding));
System.out.println("Draw buffer: " + drawBuf);
System.out.println("Read buffer: " + readBuf);
if (context.boundFBO != fbId) {
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, fbId);
context.boundFBO = fbId;
}
if (fb.getDepthBuffer() != null) {
printRealRenderBufferInfo(fb, fb.getDepthBuffer(), "Depth");
}
for (int i = 0; i < fb.getNumColorBuffers(); i++) {
printRealRenderBufferInfo(fb, fb.getColorBuffer(i), "Color" + i);
}
}
private void checkFrameBufferError() {
int status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
switch (status) {
case GL_FRAMEBUFFER_COMPLETE_EXT:
break;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
//Choose different formats
throw new IllegalStateException("Framebuffer object format is "
+ "unsupported by the video hardware.");
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
throw new IllegalStateException("Framebuffer has erronous attachment.");
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
throw new IllegalStateException("Framebuffer doesn't have any renderbuffers attached.");
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
throw new IllegalStateException("Framebuffer attachments must have same dimensions.");
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
throw new IllegalStateException("Framebuffer attachments must have same formats.");
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
throw new IllegalStateException("Incomplete draw buffer.");
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
throw new IllegalStateException("Incomplete read buffer.");
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT:
throw new IllegalStateException("Incomplete multisample buffer.");
default:
//Programming error; will fail on all hardware
throw new IllegalStateException("Some video driver error "
+ "or programming error occured. "
+ "Framebuffer object status is invalid. ");
}
}
private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb) {
int id = rb.getId();
if (id == -1) {
glGenRenderbuffersEXT(intBuf1);
id = intBuf1.get(0);
rb.setId(id);
}
if (context.boundRB != id) {
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, id);
context.boundRB = id;
}
if (fb.getWidth() > maxRBSize || fb.getHeight() > maxRBSize) {
throw new RendererException("Resolution " + fb.getWidth()
+ ":" + fb.getHeight() + " is not supported.");
}
TextureUtil.GLImageFormat glFmt = TextureUtil.getImageFormatWithError(rb.getFormat());
if (fb.getSamples() > 1 && GLContext.getCapabilities().GL_EXT_framebuffer_multisample) {
int samples = fb.getSamples();
if (maxFBOSamples < samples) {
samples = maxFBOSamples;
}
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT,
samples,
glFmt.internalFormat,
fb.getWidth(),
fb.getHeight());
} else {
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
glFmt.internalFormat,
fb.getWidth(),
fb.getHeight());
}
}
private int convertAttachmentSlot(int attachmentSlot) {
// can also add support for stencil here
if (attachmentSlot == -100) {
return GL_DEPTH_ATTACHMENT_EXT;
} else if (attachmentSlot < 0 || attachmentSlot >= 16) {
throw new UnsupportedOperationException("Invalid FBO attachment slot: " + attachmentSlot);
}
return GL_COLOR_ATTACHMENT0_EXT + attachmentSlot;
}
public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) {
Texture tex = rb.getTexture();
Image image = tex.getImage();
if (image.isUpdateNeeded()) {
updateTexImageData(image, tex.getType(), tex.getMinFilter().usesMipMapLevels(), 0);
// NOTE: For depth textures, sets nearest/no-mips mode
// Required to fix "framebuffer unsupported"
// for old NVIDIA drivers!
setupTextureParams(tex);
}
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
convertAttachmentSlot(rb.getSlot()),
convertTextureType(tex.getType(), image.getMultiSamples(), rb.getFace()),
image.getId(),
0);
}
public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) {
boolean needAttach;
if (rb.getTexture() == null) {
// if it hasn't been created yet, then attach is required.
needAttach = rb.getId() == -1;
updateRenderBuffer(fb, rb);
} else {
needAttach = false;
updateRenderTexture(fb, rb);
}
if (needAttach) {
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
convertAttachmentSlot(rb.getSlot()),
GL_RENDERBUFFER_EXT,
rb.getId());
}
}
public void updateFrameBuffer(FrameBuffer fb) {
int id = fb.getId();
if (id == -1) {
// create FBO
glGenFramebuffersEXT(intBuf1);
id = intBuf1.get(0);
fb.setId(id);
objManager.registerForCleanup(fb);
statistics.onNewFrameBuffer();
}
if (context.boundFBO != id) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id);
// binding an FBO automatically sets draw buf to GL_COLOR_ATTACHMENT0
context.boundDrawBuf = 0;
context.boundFBO = id;
}
FrameBuffer.RenderBuffer depthBuf = fb.getDepthBuffer();
if (depthBuf != null) {
updateFrameBufferAttachment(fb, depthBuf);
}
for (int i = 0; i < fb.getNumColorBuffers(); i++) {
FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i);
updateFrameBufferAttachment(fb, colorBuf);
}
fb.clearUpdateNeeded();
}
public Vector2f[] getFrameBufferSamplePositions(FrameBuffer fb) {
if (fb.getSamples() <= 1) {
throw new IllegalArgumentException("Framebuffer must be multisampled");
}
setFrameBuffer(fb);
Vector2f[] samplePositions = new Vector2f[fb.getSamples()];
FloatBuffer samplePos = BufferUtils.createFloatBuffer(2);
for (int i = 0; i < samplePositions.length; i++) {
glGetMultisample(GL_SAMPLE_POSITION, i, samplePos);
samplePos.clear();
samplePositions[i] = new Vector2f(samplePos.get(0) - 0.5f,
samplePos.get(1) - 0.5f);
}
return samplePositions;
}
public void setMainFrameBufferOverride(FrameBuffer fb) {
mainFbOverride = fb;
}
public void setFrameBuffer(FrameBuffer fb) {
if (fb == null && mainFbOverride != null) {
fb = mainFbOverride;
}
if (lastFb == fb) {
if (fb == null || !fb.isUpdateNeeded()) {
return;
}
}
// generate mipmaps for last FB if needed
if (lastFb != null) {
for (int i = 0; i < lastFb.getNumColorBuffers(); i++) {
RenderBuffer rb = lastFb.getColorBuffer(i);
Texture tex = rb.getTexture();
if (tex != null
&& tex.getMinFilter().usesMipMapLevels()) {
setTexture(0, rb.getTexture());
int textureType = convertTextureType(tex.getType(), tex.getImage().getMultiSamples(), rb.getFace());
glEnable(textureType);
glGenerateMipmapEXT(textureType);
glDisable(textureType);
}
}
}
if (fb == null) {
// unbind any fbos
if (context.boundFBO != 0) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
statistics.onFrameBufferUse(null, true);
context.boundFBO = 0;
}
// select back buffer
if (context.boundDrawBuf != -1) {
glDrawBuffer(initialDrawBuf);
context.boundDrawBuf = -1;
}
if (context.boundReadBuf != -1) {
glReadBuffer(initialReadBuf);
context.boundReadBuf = -1;
}
lastFb = null;
} else {
if (fb.getNumColorBuffers() == 0 && fb.getDepthBuffer() == null) {
throw new IllegalArgumentException("The framebuffer: " + fb
+ "\nDoesn't have any color/depth buffers");
}
if (fb.isUpdateNeeded()) {
updateFrameBuffer(fb);
}
if (context.boundFBO != fb.getId()) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb.getId());
statistics.onFrameBufferUse(fb, true);
// update viewport to reflect framebuffer's resolution
setViewPort(0, 0, fb.getWidth(), fb.getHeight());
context.boundFBO = fb.getId();
} else {
statistics.onFrameBufferUse(fb, false);
}
if (fb.getNumColorBuffers() == 0) {
// make sure to select NONE as draw buf
// no color buffer attached. select NONE
if (context.boundDrawBuf != -2) {
glDrawBuffer(GL_NONE);
context.boundDrawBuf = -2;
}
if (context.boundReadBuf != -2) {
glReadBuffer(GL_NONE);
context.boundReadBuf = -2;
}
} else {
if (fb.getNumColorBuffers() > maxFBOAttachs) {
throw new RendererException("Framebuffer has more color "
+ "attachments than are supported"
+ " by the video hardware!");
}
if (fb.isMultiTarget()) {
if (fb.getNumColorBuffers() > maxMRTFBOAttachs) {
throw new RendererException("Framebuffer has more"
+ " multi targets than are supported"
+ " by the video hardware!");
}
if (context.boundDrawBuf != 100 + fb.getNumColorBuffers()) {
intBuf16.clear();
for (int i = 0; i < fb.getNumColorBuffers(); i++) {
intBuf16.put(GL_COLOR_ATTACHMENT0_EXT + i);
}
intBuf16.flip();
glDrawBuffers(intBuf16);
context.boundDrawBuf = 100 + fb.getNumColorBuffers();
}
} else {
RenderBuffer rb = fb.getColorBuffer(fb.getTargetIndex());
// select this draw buffer
if (context.boundDrawBuf != rb.getSlot()) {
glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT + rb.getSlot());
context.boundDrawBuf = rb.getSlot();
}
}
}
assert fb.getId() >= 0;
assert context.boundFBO == fb.getId();
lastFb = fb;
try {
checkFrameBufferError();
} catch (IllegalStateException ex) {
logger.log(Level.SEVERE, "=== jMonkeyEngine FBO State ===\n{0}", fb);
printRealFrameBufferInfo(fb);
throw ex;
}
}
}
public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) {
if (fb != null) {
RenderBuffer rb = fb.getColorBuffer();
if (rb == null) {
throw new IllegalArgumentException("Specified framebuffer"
+ " does not have a colorbuffer");
}
setFrameBuffer(fb);
if (context.boundReadBuf != rb.getSlot()) {
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT + rb.getSlot());
context.boundReadBuf = rb.getSlot();
}
} else {
setFrameBuffer(null);
}
glReadPixels(vpX, vpY, vpW, vpH, /*GL_RGBA*/ GL_BGRA, GL_UNSIGNED_BYTE, byteBuf);
}
private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb) {
intBuf1.put(0, rb.getId());
glDeleteRenderbuffersEXT(intBuf1);
}
public void deleteFrameBuffer(FrameBuffer fb) {
if (fb.getId() != -1) {
if (context.boundFBO == fb.getId()) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
context.boundFBO = 0;
}
if (fb.getDepthBuffer() != null) {
deleteRenderBuffer(fb, fb.getDepthBuffer());
}
if (fb.getColorBuffer() != null) {
deleteRenderBuffer(fb, fb.getColorBuffer());
}
intBuf1.put(0, fb.getId());
glDeleteFramebuffersEXT(intBuf1);
fb.resetObject();
statistics.onDeleteFrameBuffer();
}
}
private int convertTextureType(Texture.Type type, int samples, int face) {
switch (type) {
case TwoDimensional:
if (samples > 1) {
return ARBTextureMultisample.GL_TEXTURE_2D_MULTISAMPLE;
} else {
return GL_TEXTURE_2D;
}
case TwoDimensionalArray:
if (samples > 1) {
return ARBTextureMultisample.GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
} else {
return EXTTextureArray.GL_TEXTURE_2D_ARRAY_EXT;
}
case ThreeDimensional:
return GL_TEXTURE_3D;
case CubeMap:
if (face < 0) {
return GL_TEXTURE_CUBE_MAP;
} else if (face < 6) {
return GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;
} else {
throw new UnsupportedOperationException("Invalid cube map face index: " + face);
}
default:
throw new UnsupportedOperationException("Unknown texture type: " + type);
}
}
private int convertMagFilter(Texture.MagFilter filter) {
switch (filter) {
case Bilinear:
return GL_LINEAR;
case Nearest:
return GL_NEAREST;
default:
throw new UnsupportedOperationException("Unknown mag filter: " + filter);
}
}
private int convertMinFilter(Texture.MinFilter filter) {
switch (filter) {
case Trilinear:
return GL_LINEAR_MIPMAP_LINEAR;
case BilinearNearestMipMap:
return GL_LINEAR_MIPMAP_NEAREST;
case NearestLinearMipMap:
return GL_NEAREST_MIPMAP_LINEAR;
case NearestNearestMipMap:
return GL_NEAREST_MIPMAP_NEAREST;
case BilinearNoMipMaps:
return GL_LINEAR;
case NearestNoMipMaps:
return GL_NEAREST;
default:
throw new UnsupportedOperationException("Unknown min filter: " + filter);
}
}
private int convertWrapMode(Texture.WrapMode mode) {
switch (mode) {
case BorderClamp:
return GL_CLAMP_TO_BORDER;
case Clamp:
return GL_CLAMP;
case EdgeClamp:
return GL_CLAMP_TO_EDGE;
case Repeat:
return GL_REPEAT;
case MirroredRepeat:
return GL_MIRRORED_REPEAT;
default:
throw new UnsupportedOperationException("Unknown wrap mode: " + mode);
}
}
@SuppressWarnings("fallthrough")
private void setupTextureParams(Texture tex) {
Image image = tex.getImage();
int target = convertTextureType(tex.getType(), image != null ? image.getMultiSamples() : 1, -1);
// filter things
int minFilter = convertMinFilter(tex.getMinFilter());
int magFilter = convertMagFilter(tex.getMagFilter());
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter);
if (tex.getAnisotropicFilter() > 1) {
if (GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic) {
glTexParameterf(target,
EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT,
tex.getAnisotropicFilter());
}
}
if (context.pointSprite) {
return; // Attempt to fix glTexParameter crash for some ATI GPUs
}
// repeat modes
switch (tex.getType()) {
case ThreeDimensional:
case CubeMap: // cubemaps use 3D coords
glTexParameteri(target, GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R)));
case TwoDimensional:
case TwoDimensionalArray:
glTexParameteri(target, GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T)));
// fall down here is intentional..
// case OneDimensional:
glTexParameteri(target, GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S)));
break;
default:
throw new UnsupportedOperationException("Unknown texture type: " + tex.getType());
}
// R to Texture compare mode
if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off) {
glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
glTexParameteri(target, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual) {
glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_GEQUAL);
} else {
glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
}
}
}
public void updateTexImageData(Image img, Texture.Type type, boolean mips, int unit) {
int texId = img.getId();
if (texId == -1) {
// create texture
glGenTextures(intBuf1);
texId = intBuf1.get(0);
img.setId(texId);
objManager.registerForCleanup(img);
statistics.onNewTexture();
}
// bind texture
int target = convertTextureType(type, img.getMultiSamples(), -1);
if (context.boundTextureUnit != unit) {
glActiveTexture(GL_TEXTURE0 + unit);
context.boundTextureUnit = unit;
}
if (context.boundTextures[unit] != img) {
glBindTexture(target, texId);
context.boundTextures[unit] = img;
statistics.onTextureUse(img, true);
}
if (!img.hasMipmaps() && mips) {
// No pregenerated mips available,
// generate from base level if required
if (!GLContext.getCapabilities().OpenGL30) {
glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE);
}
} else {
// glTexParameteri(target, GL_TEXTURE_BASE_LEVEL, 0 );
if (img.getMipMapSizes() != null) {
glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, img.getMipMapSizes().length - 1);
}
}
int imageSamples = img.getMultiSamples();
if (imageSamples > 1) {
if (img.getFormat().isDepthFormat()) {
img.setMultiSamples(Math.min(maxDepthTexSamples, imageSamples));
} else {
img.setMultiSamples(Math.min(maxColorTexSamples, imageSamples));
}
}
// Yes, some OpenGL2 cards (GeForce 5) still dont support NPOT.
if (!GLContext.getCapabilities().GL_ARB_texture_non_power_of_two) {
if (img.getWidth() != 0 && img.getHeight() != 0) {
if (!FastMath.isPowerOfTwo(img.getWidth())
|| !FastMath.isPowerOfTwo(img.getHeight())) {
if (img.getData(0) == null) {
throw new RendererException("non-power-of-2 framebuffer textures are not supported by the video hardware");
} else {
MipMapGenerator.resizeToPowerOf2(img);
}
}
}
}
// Check if graphics card doesn't support multisample textures
if (!GLContext.getCapabilities().GL_ARB_texture_multisample) {
if (img.getMultiSamples() > 1) {
throw new RendererException("Multisample textures not supported by graphics hardware");
}
}
if (target == GL_TEXTURE_CUBE_MAP) {
List<ByteBuffer> data = img.getData();
if (data.size() != 6) {
logger.log(Level.WARNING, "Invalid texture: {0}\n"
+ "Cubemap textures must contain 6 data units.", img);
return;
}
for (int i = 0; i < 6; i++) {
TextureUtil.uploadTexture(img, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, 0);
}
} else if (target == EXTTextureArray.GL_TEXTURE_2D_ARRAY_EXT) {
List<ByteBuffer> data = img.getData();
// -1 index specifies prepare data for 2D Array
TextureUtil.uploadTexture(img, target, -1, 0);
for (int i = 0; i < data.size(); i++) {
// upload each slice of 2D array in turn
// this time with the appropriate index
TextureUtil.uploadTexture(img, target, i, 0);
}
} else {
TextureUtil.uploadTexture(img, target, 0, 0);
}
if (img.getMultiSamples() != imageSamples) {
img.setMultiSamples(imageSamples);
}
if (GLContext.getCapabilities().OpenGL30) {
if (!img.hasMipmaps() && mips && img.getData() != null) {
// XXX: Required for ATI
glEnable(target);
glGenerateMipmapEXT(target);
glDisable(target);
}
}
img.clearUpdateNeeded();
}
public void setTexture(int unit, Texture tex) {
Image image = tex.getImage();
if (image.isUpdateNeeded()) {
updateTexImageData(image, tex.getType(), tex.getMinFilter().usesMipMapLevels(), unit);
}
int texId = image.getId();
assert texId != -1;
Image[] textures = context.boundTextures;
int type = convertTextureType(tex.getType(), image.getMultiSamples(), -1);
// if (!context.textureIndexList.moveToNew(unit)) {
// if (context.boundTextureUnit != unit){
// glActiveTexture(GL_TEXTURE0 + unit);
// context.boundTextureUnit = unit;
// glEnable(type);
if (context.boundTextureUnit != unit) {
glActiveTexture(GL_TEXTURE0 + unit);
context.boundTextureUnit = unit;
}
if (textures[unit] != image) {
glBindTexture(type, texId);
textures[unit] = image;
statistics.onTextureUse(image, true);
} else {
statistics.onTextureUse(image, false);
}
setupTextureParams(tex);
}
public void clearTextureUnits() {
// IDList textureList = context.textureIndexList;
// Image[] textures = context.boundTextures;
// for (int i = 0; i < textureList.oldLen; i++) {
// int idx = textureList.oldList[i];
// if (context.boundTextureUnit != idx){
// glActiveTexture(GL_TEXTURE0 + idx);
// context.boundTextureUnit = idx;
// glDisable(convertTextureType(textures[idx].getType()));
// textures[idx] = null;
// context.textureIndexList.copyNewToOld();
}
public void deleteImage(Image image) {
int texId = image.getId();
if (texId != -1) {
intBuf1.put(0, texId);
intBuf1.position(0).limit(1);
glDeleteTextures(intBuf1);
image.resetObject();
statistics.onDeleteTexture();
}
}
private int convertUsage(Usage usage) {
switch (usage) {
case Static:
return GL_STATIC_DRAW;
case Dynamic:
return GL_DYNAMIC_DRAW;
case Stream:
return GL_STREAM_DRAW;
default:
throw new UnsupportedOperationException("Unknown usage type.");
}
}
private int convertFormat(Format format) {
switch (format) {
case Byte:
return GL_BYTE;
case UnsignedByte:
return GL_UNSIGNED_BYTE;
case Short:
return GL_SHORT;
case UnsignedShort:
return GL_UNSIGNED_SHORT;
case Int:
return GL_INT;
case UnsignedInt:
return GL_UNSIGNED_INT;
// case Half:
// return NVHalfFloat.GL_HALF_FLOAT_NV;
// return ARBHalfFloatVertex.GL_HALF_FLOAT;
case Float:
return GL_FLOAT;
case Double:
return GL_DOUBLE;
default:
throw new UnsupportedOperationException("Unknown buffer format.");
}
}
public void updateBufferData(VertexBuffer vb) {
int bufId = vb.getId();
boolean created = false;
if (bufId == -1) {
// create buffer
glGenBuffers(intBuf1);
bufId = intBuf1.get(0);
vb.setId(bufId);
objManager.registerForCleanup(vb);
//statistics.onNewVertexBuffer();
created = true;
}
// bind buffer
int target;
if (vb.getBufferType() == VertexBuffer.Type.Index) {
target = GL_ELEMENT_ARRAY_BUFFER;
if (context.boundElementArrayVBO != bufId) {
glBindBuffer(target, bufId);
context.boundElementArrayVBO = bufId;
//statistics.onVertexBufferUse(vb, true);
} else {
//statistics.onVertexBufferUse(vb, false);
}
} else {
target = GL_ARRAY_BUFFER;
if (context.boundArrayVBO != bufId) {
glBindBuffer(target, bufId);
context.boundArrayVBO = bufId;
//statistics.onVertexBufferUse(vb, true);
} else {
//statistics.onVertexBufferUse(vb, false);
}
}
int usage = convertUsage(vb.getUsage());
vb.getData().rewind();
if (created || vb.hasDataSizeChanged()) {
// upload data based on format
switch (vb.getFormat()) {
case Byte:
case UnsignedByte:
glBufferData(target, (ByteBuffer) vb.getData(), usage);
break;
// case Half:
case Short:
case UnsignedShort:
glBufferData(target, (ShortBuffer) vb.getData(), usage);
break;
case Int:
case UnsignedInt:
glBufferData(target, (IntBuffer) vb.getData(), usage);
break;
case Float:
glBufferData(target, (FloatBuffer) vb.getData(), usage);
break;
case Double:
glBufferData(target, (DoubleBuffer) vb.getData(), usage);
break;
default:
throw new UnsupportedOperationException("Unknown buffer format.");
}
} else {
switch (vb.getFormat()) {
case Byte:
case UnsignedByte:
glBufferSubData(target, 0, (ByteBuffer) vb.getData());
break;
case Short:
case UnsignedShort:
glBufferSubData(target, 0, (ShortBuffer) vb.getData());
break;
case Int:
case UnsignedInt:
glBufferSubData(target, 0, (IntBuffer) vb.getData());
break;
case Float:
glBufferSubData(target, 0, (FloatBuffer) vb.getData());
break;
case Double:
glBufferSubData(target, 0, (DoubleBuffer) vb.getData());
break;
default:
throw new UnsupportedOperationException("Unknown buffer format.");
}
}
// }else{
// if (created || vb.hasDataSizeChanged()){
// glBufferData(target, vb.getData().capacity() * vb.getFormat().getComponentSize(), usage);
// ByteBuffer buf = glMapBuffer(target,
// GL_WRITE_ONLY,
// vb.getMappedData());
// if (buf != vb.getMappedData()){
// buf = buf.order(ByteOrder.nativeOrder());
// vb.setMappedData(buf);
// buf.clear();
// switch (vb.getFormat()){
// case Byte:
// case UnsignedByte:
// buf.put( (ByteBuffer) vb.getData() );
// break;
// case Short:
// case UnsignedShort:
// buf.asShortBuffer().put( (ShortBuffer) vb.getData() );
// break;
// case Int:
// case UnsignedInt:
// buf.asIntBuffer().put( (IntBuffer) vb.getData() );
// break;
// case Float:
// buf.asFloatBuffer().put( (FloatBuffer) vb.getData() );
// break;
// case Double:
// break;
// default:
// throw new RuntimeException("Unknown buffer format.");
// glUnmapBuffer(target);
vb.clearUpdateNeeded();
}
public void deleteBuffer(VertexBuffer vb) {
int bufId = vb.getId();
if (bufId != -1) {
// delete buffer
intBuf1.put(0, bufId);
intBuf1.position(0).limit(1);
glDeleteBuffers(intBuf1);
vb.resetObject();
//statistics.onDeleteVertexBuffer();
}
}
public void clearVertexAttribs() {
IDList attribList = context.attribIndexList;
for (int i = 0; i < attribList.oldLen; i++) {
int idx = attribList.oldList[i];
glDisableVertexAttribArray(idx);
context.boundAttribs[idx] = null;
}
context.attribIndexList.copyNewToOld();
}
public void setVertexAttrib(VertexBuffer vb, VertexBuffer idb) {
if (vb.getBufferType() == VertexBuffer.Type.Index) {
throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib");
}
int programId = context.boundShaderProgram;
if (programId > 0) {
Attribute attrib = boundShader.getAttribute(vb.getBufferType());
int loc = attrib.getLocation();
if (loc == -1) {
return; // not defined
}
if (loc == -2) {
stringBuf.setLength(0);
stringBuf.append("in").append(vb.getBufferType().name()).append('\0');
updateNameBuffer();
loc = glGetAttribLocation(programId, nameBuf);
// not really the name of it in the shader (inPosition\0) but
// the internal name of the enum (Position).
if (loc < 0) {
attrib.setLocation(-1);
return; // not available in shader.
} else {
attrib.setLocation(loc);
}
}
if (vb.isUpdateNeeded() && idb == null) {
updateBufferData(vb);
}
VertexBuffer[] attribs = context.boundAttribs;
if (!context.attribIndexList.moveToNew(loc)) {
glEnableVertexAttribArray(loc);
//System.out.println("Enabled ATTRIB IDX: "+loc);
}
if (attribs[loc] != vb) {
// NOTE: Use id from interleaved buffer if specified
int bufId = idb != null ? idb.getId() : vb.getId();
assert bufId != -1;
if (context.boundArrayVBO != bufId) {
glBindBuffer(GL_ARRAY_BUFFER, bufId);
context.boundArrayVBO = bufId;
//statistics.onVertexBufferUse(vb, true);
} else {
//statistics.onVertexBufferUse(vb, false);
}
glVertexAttribPointer(loc,
vb.getNumComponents(),
convertFormat(vb.getFormat()),
vb.isNormalized(),
vb.getStride(),
vb.getOffset());
attribs[loc] = vb;
}
} else {
throw new IllegalStateException("Cannot render mesh without shader bound");
}
}
public void setVertexAttrib(VertexBuffer vb) {
setVertexAttrib(vb, null);
}
public void drawTriangleArray(Mesh.Mode mode, int count, int vertCount) {
if (count > 1) {
ARBDrawInstanced.glDrawArraysInstancedARB(convertElementMode(mode), 0,
vertCount, count);
} else {
glDrawArrays(convertElementMode(mode), 0, vertCount);
}
}
public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) {
if (indexBuf.getBufferType() != VertexBuffer.Type.Index) {
throw new IllegalArgumentException("Only index buffers are allowed as triangle lists.");
}
if (indexBuf.isUpdateNeeded()) {
updateBufferData(indexBuf);
}
int bufId = indexBuf.getId();
assert bufId != -1;
if (context.boundElementArrayVBO != bufId) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufId);
context.boundElementArrayVBO = bufId;
//statistics.onVertexBufferUse(indexBuf, true);
} else {
//statistics.onVertexBufferUse(indexBuf, true);
}
int vertCount = mesh.getVertexCount();
boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing);
if (mesh.getMode() == Mode.Hybrid) {
int[] modeStart = mesh.getModeStart();
int[] elementLengths = mesh.getElementLengths();
int elMode = convertElementMode(Mode.Triangles);
int fmt = convertFormat(indexBuf.getFormat());
int elSize = indexBuf.getFormat().getComponentSize();
int listStart = modeStart[0];
int stripStart = modeStart[1];
int fanStart = modeStart[2];
int curOffset = 0;
for (int i = 0; i < elementLengths.length; i++) {
if (i == stripStart) {
elMode = convertElementMode(Mode.TriangleStrip);
} else if (i == fanStart) {
elMode = convertElementMode(Mode.TriangleStrip);
}
int elementLength = elementLengths[i];
if (useInstancing) {
ARBDrawInstanced.glDrawElementsInstancedARB(elMode,
elementLength,
fmt,
curOffset,
count);
} else {
glDrawRangeElements(elMode,
0,
vertCount,
elementLength,
fmt,
curOffset);
}
curOffset += elementLength * elSize;
}
} else {
if (useInstancing) {
ARBDrawInstanced.glDrawElementsInstancedARB(convertElementMode(mesh.getMode()),
indexBuf.getData().limit(),
convertFormat(indexBuf.getFormat()),
0,
count);
} else {
glDrawRangeElements(convertElementMode(mesh.getMode()),
0,
vertCount,
indexBuf.getData().limit(),
convertFormat(indexBuf.getFormat()),
0);
}
}
}
public int convertElementMode(Mesh.Mode mode) {
switch (mode) {
case Points:
return GL_POINTS;
case Lines:
return GL_LINES;
case LineLoop:
return GL_LINE_LOOP;
case LineStrip:
return GL_LINE_STRIP;
case Triangles:
return GL_TRIANGLES;
case TriangleFan:
return GL_TRIANGLE_FAN;
case TriangleStrip:
return GL_TRIANGLE_STRIP;
default:
throw new UnsupportedOperationException("Unrecognized mesh mode: " + mode);
}
}
public void updateVertexArray(Mesh mesh) {
int id = mesh.getId();
if (id == -1) {
IntBuffer temp = intBuf1;
ARBVertexArrayObject.glGenVertexArrays(temp);
id = temp.get(0);
mesh.setId(id);
}
if (context.boundVertexArray != id) {
ARBVertexArrayObject.glBindVertexArray(id);
context.boundVertexArray = id;
}
VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData);
if (interleavedData != null && interleavedData.isUpdateNeeded()) {
updateBufferData(interleavedData);
}
for (VertexBuffer vb : mesh.getBufferList().getArray()) {
if (vb.getBufferType() == Type.InterleavedData
|| vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers
|| vb.getBufferType() == Type.Index) {
continue;
}
if (vb.getStride() == 0) {
// not interleaved
setVertexAttrib(vb);
} else {
// interleaved
setVertexAttrib(vb, interleavedData);
}
}
}
private void renderMeshVertexArray(Mesh mesh, int lod, int count) {
if (mesh.getId() == -1) {
updateVertexArray(mesh);
} else {
// TODO: Check if it was updated
}
if (context.boundVertexArray != mesh.getId()) {
ARBVertexArrayObject.glBindVertexArray(mesh.getId());
context.boundVertexArray = mesh.getId();
}
// IntMap<VertexBuffer> buffers = mesh.getBuffers();
VertexBuffer indices;
if (mesh.getNumLodLevels() > 0) {
indices = mesh.getLodLevel(lod);
} else {
indices = mesh.getBuffer(Type.Index);
}
if (indices != null) {
drawTriangleList(indices, mesh, count);
} else {
drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount());
}
clearVertexAttribs();
clearTextureUnits();
}
private void renderMeshDefault(Mesh mesh, int lod, int count) {
VertexBuffer indices = null;
VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData);
if (interleavedData != null && interleavedData.isUpdateNeeded()) {
updateBufferData(interleavedData);
}
// IntMap<VertexBuffer> buffers = mesh.getBuffers();
SafeArrayList<VertexBuffer> buffersList = mesh.getBufferList();
if (mesh.getNumLodLevels() > 0) {
indices = mesh.getLodLevel(lod);
} else {
indices = mesh.getBuffer(Type.Index);
}
// for (Entry<VertexBuffer> entry : buffers) {
// VertexBuffer vb = entry.getValue();
for (VertexBuffer vb : mesh.getBufferList().getArray()) {
if (vb.getBufferType() == Type.InterleavedData
|| vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers
|| vb.getBufferType() == Type.Index) {
continue;
}
if (vb.getStride() == 0) {
// not interleaved
setVertexAttrib(vb);
} else {
// interleaved
setVertexAttrib(vb, interleavedData);
}
}
if (indices != null) {
drawTriangleList(indices, mesh, count);
} else {
drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount());
}
clearVertexAttribs();
clearTextureUnits();
}
public void renderMesh(Mesh mesh, int lod, int count) {
if (mesh.getVertexCount() == 0) {
return;
}
if (context.pointSprite && mesh.getMode() != Mode.Points) {
// XXX: Hack, disable point sprite mode if mesh not in point mode
if (context.boundTextures[0] != null) {
if (context.boundTextureUnit != 0) {
glActiveTexture(GL_TEXTURE0);
context.boundTextureUnit = 0;
}
glDisable(GL_POINT_SPRITE);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
context.pointSprite = false;
}
}
if (context.pointSize != mesh.getPointSize()) {
glPointSize(mesh.getPointSize());
context.pointSize = mesh.getPointSize();
}
if (context.lineWidth != mesh.getLineWidth()) {
glLineWidth(mesh.getLineWidth());
context.lineWidth = mesh.getLineWidth();
}
statistics.onMeshDrawn(mesh, lod);
// if (GLContext.getCapabilities().GL_ARB_vertex_array_object){
// renderMeshVertexArray(mesh, lod, count);
// }else{
renderMeshDefault(mesh, lod, count);
}
}
|
package hotchemi.android.rate;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import java.util.Date;
import static hotchemi.android.rate.DialogManager.create;
import static hotchemi.android.rate.PreferenceHelper.getEventTimes;
import static hotchemi.android.rate.PreferenceHelper.getInstallDate;
import static hotchemi.android.rate.PreferenceHelper.getIsAgreeShowDialog;
import static hotchemi.android.rate.PreferenceHelper.getLaunchTimes;
import static hotchemi.android.rate.PreferenceHelper.getRemindInterval;
import static hotchemi.android.rate.PreferenceHelper.isFirstLaunch;
import static hotchemi.android.rate.PreferenceHelper.setInstallDate;
public class AppRate {
private static AppRate singleton;
private final Context context;
private final DialogOptions options = new DialogOptions();
private int installDate = 10;
private int launchTimes = 10;
private int remindInterval = 1;
private int eventsTimes = -1;
private boolean isDebug = false;
private AppRate(Context context) {
this.context = context.getApplicationContext();
}
public static AppRate with(Context context) {
if (singleton == null) {
synchronized (AppRate.class) {
if (singleton == null) {
singleton = new AppRate(context);
}
}
}
return singleton;
}
public AppRate setLaunchTimes(int launchTimes) {
this.launchTimes = launchTimes;
return this;
}
public AppRate setInstallDays(int installDate) {
this.installDate = installDate;
return this;
}
public AppRate setRemindInterval(int remindInterval) {
this.remindInterval = remindInterval;
return this;
}
public AppRate setShowLaterButton(boolean isShowNeutralButton) {
options.setShowNeutralButton(isShowNeutralButton);
return this;
}
public AppRate setEventsTimes(int eventsTimes) {
this.eventsTimes = eventsTimes;
return this;
}
public AppRate setShowTitle(boolean isShowTitle) {
options.setShowTitle(isShowTitle);
return this;
}
public AppRate clearAgreeShowDialog() {
PreferenceHelper.setAgreeShowDialog(context, true);
return this;
}
public AppRate setAgreeShowDialog(boolean clear) {
PreferenceHelper.setAgreeShowDialog(context, clear);
return this;
}
public AppRate setDebug(boolean isDebug) {
this.isDebug = isDebug;
return this;
}
public AppRate setView(View view) {
options.setView(view);
return this;
}
public AppRate setOnClickButtonListener(OnClickButtonListener listener) {
options.setListener(listener);
return this;
}
public AppRate setTitle(int resourceId) {
options.setTitleResId(resourceId);
return this;
}
public AppRate setMessage(int resourceId) {
options.setMessageResId(resourceId);
return this;
}
public AppRate setTextRateNow(int resourceId) {
options.setTextPositiveResId(resourceId);
return this;
}
public AppRate setTextLater(int resourceId) {
options.setTextNeutralResId(resourceId);
return this;
}
public AppRate setTextNever(int resourceId) {
options.setTextNegativeResId(resourceId);
return this;
}
public AppRate setCancelable(boolean cancelable) {
options.setCancelable(cancelable);
return this;
}
public void monitor() {
if (isFirstLaunch(context)) {
setInstallDate(context);
}
PreferenceHelper.setLaunchTimes(context, getLaunchTimes(context) + 1);
}
public static boolean showRateDialogIfMeetsConditions(Activity activity) {
boolean isMeetsConditions = singleton.isDebug || singleton.shouldShowRateDialog();
if (isMeetsConditions) {
singleton.showRateDialog(activity);
}
return isMeetsConditions;
}
public static boolean passSignificantEvent(Activity activity) {
return passSignificantEvent(activity, true);
}
public static boolean passSignificantEventAndConditions(Activity activity) {
return passSignificantEvent(activity, singleton.shouldShowRateDialog());
}
private static boolean passSignificantEvent(Activity activity, boolean shouldShow) {
int eventTimes = getEventTimes(activity);
PreferenceHelper.setEventTimes(activity, ++eventTimes);
boolean isMeetsConditions = singleton.isDebug || (singleton.isOverEventPass() && shouldShow);
if (isMeetsConditions) {
singleton.showRateDialog(activity);
}
return isMeetsConditions;
}
public void showRateDialog(Activity activity) {
if (!activity.isFinishing()) {
create(activity, options).show();
}
}
public boolean isOverEventPass() {
return eventsTimes != -1 && getEventTimes(context) > eventsTimes;
}
public boolean shouldShowRateDialog() {
return getIsAgreeShowDialog(context) &&
isOverLaunchTimes() &&
isOverInstallDate() &&
isOverRemindDate();
}
private boolean isOverLaunchTimes() {
return getLaunchTimes(context) >= launchTimes;
}
private boolean isOverInstallDate() {
return isOverDate(getInstallDate(context), installDate);
}
private boolean isOverRemindDate() {
return isOverDate(getRemindInterval(context), remindInterval);
}
private static boolean isOverDate(long targetDate, int threshold) {
return new Date().getTime() - targetDate >= threshold * 24 * 60 * 60 * 1000;
}
public boolean isDebug() {
return isDebug;
}
}
|
package com.jme3.scene.plugins.ogre;
import com.jme3.animation.AnimControl;
import com.jme3.animation.Animation;
import com.jme3.animation.SkeletonControl;
import com.jme3.asset.*;
import com.jme3.material.Material;
import com.jme3.material.MaterialList;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.VertexBuffer.Format;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.scene.plugins.ogre.matext.OgreMaterialKey;
import com.jme3.util.BufferUtils;
import com.jme3.util.IntMap;
import com.jme3.util.IntMap.Entry;
import com.jme3.util.PlaceholderAssets;
import static com.jme3.util.xml.SAXUtil.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* Loads Ogre3D mesh.xml files.
*/
public class MeshLoader extends DefaultHandler implements AssetLoader {
private static final Logger logger = Logger.getLogger(MeshLoader.class.getName());
public static boolean AUTO_INTERLEAVE = true;
public static boolean HARDWARE_SKINNING = false;
private static final Type[] TEXCOORD_TYPES =
new Type[]{
Type.TexCoord,
Type.TexCoord2,
Type.TexCoord3,
Type.TexCoord4,
Type.TexCoord5,
Type.TexCoord6,
Type.TexCoord7,
Type.TexCoord8,};
private AssetKey key;
private String meshName;
private String folderName;
private AssetManager assetManager;
private MaterialList materialList;
// Data per submesh/sharedgeom
private ShortBuffer sb;
private IntBuffer ib;
private FloatBuffer fb;
private VertexBuffer vb;
private Mesh mesh;
private Geometry geom;
private ByteBuffer indicesData;
private FloatBuffer weightsFloatData;
private boolean actuallyHasWeights = false;
private int vertCount;
private boolean usesSharedVerts;
private boolean usesBigIndices;
private boolean submeshNamesHack;
// Global data
private Mesh sharedMesh;
private int meshIndex = 0;
private int texCoordIndex = 0;
private String ignoreUntilEnd = null;
private List<Geometry> geoms = new ArrayList<Geometry>();
private ArrayList<Boolean> usesSharedMesh = new ArrayList<Boolean>();
private IntMap<List<VertexBuffer>> lodLevels = new IntMap<List<VertexBuffer>>();
private AnimData animData;
public MeshLoader() {
super();
}
@Override
public void startDocument() {
geoms.clear();
lodLevels.clear();
sb = null;
ib = null;
fb = null;
vb = null;
mesh = null;
geom = null;
sharedMesh = null;
usesSharedMesh.clear();
usesSharedVerts = false;
vertCount = 0;
meshIndex = 0;
texCoordIndex = 0;
ignoreUntilEnd = null;
animData = null;
actuallyHasWeights = false;
submeshNamesHack = false;
indicesData = null;
weightsFloatData = null;
}
@Override
public void endDocument() {
}
private void pushIndex(int index){
if (ib != null){
ib.put(index);
}else{
sb.put((short)index);
}
}
private void pushFace(String v1, String v2, String v3) throws SAXException {
// TODO: fan/strip support
switch (mesh.getMode()){
case Triangles:
pushIndex(parseInt(v1));
pushIndex(parseInt(v2));
pushIndex(parseInt(v3));
break;
case Lines:
pushIndex(parseInt(v1));
pushIndex(parseInt(v2));
break;
case Points:
pushIndex(parseInt(v1));
break;
}
}
// private boolean isUsingSharedVerts(Geometry geom) {
// Old code for buffer sharer
//return geom.getUserData(UserData.JME_SHAREDMESH) != null;
private void startFaces(String count) throws SAXException {
int numFaces = parseInt(count);
int indicesPerFace = 0;
switch (mesh.getMode()){
case Triangles:
indicesPerFace = 3;
break;
case Lines:
indicesPerFace = 2;
break;
case Points:
indicesPerFace = 1;
break;
default:
throw new SAXException("Strips or fans not supported!");
}
int numIndices = indicesPerFace * numFaces;
vb = new VertexBuffer(VertexBuffer.Type.Index);
if (!usesBigIndices) {
sb = BufferUtils.createShortBuffer(numIndices);
ib = null;
vb.setupData(Usage.Static, indicesPerFace, Format.UnsignedShort, sb);
} else {
ib = BufferUtils.createIntBuffer(numIndices);
sb = null;
vb.setupData(Usage.Static, indicesPerFace, Format.UnsignedInt, ib);
}
mesh.setBuffer(vb);
}
private void applyMaterial(Geometry geom, String matName) {
Material mat = null;
if (matName.endsWith(".j3m")) {
// load as native jme3 material instance
try {
mat = assetManager.loadMaterial(matName);
} catch (AssetNotFoundException ex){
// Warning will be raised (see below)
if (!ex.getMessage().equals(matName)){
throw ex;
}
}
} else {
if (materialList != null) {
mat = materialList.get(matName);
}
}
if (mat == null) {
logger.log(Level.WARNING, "Cannot locate {0} for model {1}", new Object[]{matName, key});
mat = PlaceholderAssets.getPlaceholderMaterial(assetManager);
//mat.setKey(new MaterialKey(matName));
}
if (mat.isTransparent()) {
geom.setQueueBucket(Bucket.Transparent);
}
geom.setMaterial(mat);
}
private void startSubMesh(String matName, String usesharedvertices, String use32bitIndices, String opType) throws SAXException {
mesh = new Mesh();
if (opType == null || opType.equals("triangle_list")) {
mesh.setMode(Mesh.Mode.Triangles);
//} else if (opType.equals("triangle_strip")) {
// mesh.setMode(Mesh.Mode.TriangleStrip);
//} else if (opType.equals("triangle_fan")) {
// mesh.setMode(Mesh.Mode.TriangleFan);
} else if (opType.equals("line_list")) {
mesh.setMode(Mesh.Mode.Lines);
} else {
throw new SAXException("Unsupported operation type: " + opType);
}
usesBigIndices = parseBool(use32bitIndices, false);
usesSharedVerts = parseBool(usesharedvertices, false);
if (usesSharedVerts) {
usesSharedMesh.add(true);
// Old code for buffer sharer
// import vertexbuffers from shared geom
// IntMap<VertexBuffer> sharedBufs = sharedMesh.getBuffers();
// for (Entry<VertexBuffer> entry : sharedBufs) {
// mesh.setBuffer(entry.getValue());
}else{
usesSharedMesh.add(false);
}
if (meshName == null) {
geom = new Geometry("OgreSubmesh-" + (++meshIndex), mesh);
} else {
geom = new Geometry(meshName + "-geom-" + (++meshIndex), mesh);
}
if (usesSharedVerts) {
// Old code for buffer sharer
// this mesh is shared!
//geom.setUserData(UserData.JME_SHAREDMESH, sharedMesh);
}
applyMaterial(geom, matName);
geoms.add(geom);
}
private void startSharedGeom(String vertexcount) throws SAXException {
sharedMesh = new Mesh();
vertCount = parseInt(vertexcount);
usesSharedVerts = false;
geom = null;
mesh = sharedMesh;
}
private void startGeometry(String vertexcount) throws SAXException {
vertCount = parseInt(vertexcount);
}
/**
* Normalizes weights if needed and finds largest amount of weights used
* for all vertices in the buffer.
*/
private void endBoneAssigns() {
// if (mesh != sharedMesh && isUsingSharedVerts(geom)) {
// return;
if (!actuallyHasWeights){
// No weights were actually written (the tag didn't have any entries)
// remove those buffers
mesh.clearBuffer(Type.BoneIndex);
mesh.clearBuffer(Type.BoneWeight);
weightsFloatData = null;
indicesData = null;
return;
}
//int vertCount = mesh.getVertexCount();
int maxWeightsPerVert = 0;
weightsFloatData.rewind();
for (int v = 0; v < vertCount; v++) {
float w0 = weightsFloatData.get(),
w1 = weightsFloatData.get(),
w2 = weightsFloatData.get(),
w3 = weightsFloatData.get();
if (w3 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 4);
} else if (w2 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 3);
} else if (w1 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 2);
} else if (w0 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 1);
}
float sum = w0 + w1 + w2 + w3;
if (sum != 1f) {
weightsFloatData.position(weightsFloatData.position() - 4);
// compute new vals based on sum
float sumToB = sum == 0 ? 0 : 1f / sum;
weightsFloatData.put(w0 * sumToB);
weightsFloatData.put(w1 * sumToB);
weightsFloatData.put(w2 * sumToB);
weightsFloatData.put(w3 * sumToB);
}
}
weightsFloatData.rewind();
actuallyHasWeights = false;
weightsFloatData = null;
indicesData = null;
mesh.setMaxNumWeights(maxWeightsPerVert);
}
private void startBoneAssigns() {
if (mesh != sharedMesh && usesSharedVerts) {
// will use bone assignments from shared mesh (?)
return;
}
// current mesh will have bone assigns
//int vertCount = mesh.getVertexCount();
// each vertex has
// - 4 bone weights
// - 4 bone indices
if (HARDWARE_SKINNING) {
weightsFloatData = BufferUtils.createFloatBuffer(vertCount * 4);
indicesData = BufferUtils.createByteBuffer(vertCount * 4);
} else {
// create array-backed buffers if software skinning for access speed
weightsFloatData = FloatBuffer.allocate(vertCount * 4);
indicesData = ByteBuffer.allocate(vertCount * 4);
}
VertexBuffer weights = new VertexBuffer(Type.BoneWeight);
VertexBuffer indices = new VertexBuffer(Type.BoneIndex);
Usage usage = HARDWARE_SKINNING ? Usage.Static : Usage.CpuOnly;
weights.setupData(usage, 4, Format.Float, weightsFloatData);
indices.setupData(usage, 4, Format.UnsignedByte, indicesData);
mesh.setBuffer(weights);
mesh.setBuffer(indices);
}
private void startVertexBuffer(Attributes attribs) throws SAXException {
if (parseBool(attribs.getValue("positions"), false)) {
vb = new VertexBuffer(Type.Position);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("normals"), false)) {
vb = new VertexBuffer(Type.Normal);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("colours_diffuse"), false)) {
vb = new VertexBuffer(Type.Color);
fb = BufferUtils.createFloatBuffer(vertCount * 4);
vb.setupData(Usage.Static, 4, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("tangents"), false)) {
int dimensions = parseInt(attribs.getValue("tangent_dimensions"), 3);
vb = new VertexBuffer(Type.Tangent);
fb = BufferUtils.createFloatBuffer(vertCount * dimensions);
vb.setupData(Usage.Static, dimensions, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("binormals"), false)) {
vb = new VertexBuffer(Type.Binormal);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
int texCoords = parseInt(attribs.getValue("texture_coords"), 0);
for (int i = 0; i < texCoords; i++) {
int dims = parseInt(attribs.getValue("texture_coord_dimensions_" + i), 2);
if (dims < 1 || dims > 4) {
throw new SAXException("Texture coord dimensions must be 1 <= dims <= 4");
}
if (i <= 7) {
vb = new VertexBuffer(TEXCOORD_TYPES[i]);
} else {
// more than 8 texture coordinates are not supported by ogre.
throw new SAXException("More than 8 texture coordinates not supported");
}
fb = BufferUtils.createFloatBuffer(vertCount * dims);
vb.setupData(Usage.Static, dims, Format.Float, fb);
mesh.setBuffer(vb);
}
}
private void startVertex() {
texCoordIndex = 0;
}
private void pushAttrib(Type type, Attributes attribs) throws SAXException {
try {
FloatBuffer buf = (FloatBuffer) mesh.getBuffer(type).getData();
buf.put(parseFloat(attribs.getValue("x"))).put(parseFloat(attribs.getValue("y"))).put(parseFloat(attribs.getValue("z")));
} catch (Exception ex) {
throw new SAXException("Failed to push attrib", ex);
}
}
private void pushTangent(Attributes attribs) throws SAXException {
try {
VertexBuffer tangentBuf = mesh.getBuffer(Type.Tangent);
FloatBuffer buf = (FloatBuffer) tangentBuf.getData();
buf.put(parseFloat(attribs.getValue("x"))).put(parseFloat(attribs.getValue("y"))).put(parseFloat(attribs.getValue("z")));
if (tangentBuf.getNumComponents() == 4) {
buf.put(parseFloat(attribs.getValue("w")));
}
} catch (Exception ex) {
throw new SAXException("Failed to push attrib", ex);
}
}
private void pushTexCoord(Attributes attribs) throws SAXException {
if (texCoordIndex >= 8) {
return; // More than 8 not supported by ogre.
}
Type type = TEXCOORD_TYPES[texCoordIndex];
VertexBuffer tcvb = mesh.getBuffer(type);
FloatBuffer buf = (FloatBuffer) tcvb.getData();
buf.put(parseFloat(attribs.getValue("u")));
if (tcvb.getNumComponents() >= 2) {
buf.put(parseFloat(attribs.getValue("v")));
if (tcvb.getNumComponents() >= 3) {
buf.put(parseFloat(attribs.getValue("w")));
if (tcvb.getNumComponents() == 4) {
buf.put(parseFloat(attribs.getValue("x")));
}
}
}
texCoordIndex++;
}
private void pushColor(Attributes attribs) throws SAXException {
FloatBuffer buf = (FloatBuffer) mesh.getBuffer(Type.Color).getData();
String value = parseString(attribs.getValue("value"));
String[] vals = value.split("\\s");
if (vals.length != 3 && vals.length != 4) {
throw new SAXException("Color value must contain 3 or 4 components");
}
ColorRGBA color = new ColorRGBA();
color.r = parseFloat(vals[0]);
color.g = parseFloat(vals[1]);
color.b = parseFloat(vals[2]);
if (vals.length == 3) {
color.a = 1f;
} else {
color.a = parseFloat(vals[3]);
}
buf.put(color.r).put(color.g).put(color.b).put(color.a);
}
private void startLodFaceList(String submeshindex, String numfaces) {
int index = Integer.parseInt(submeshindex);
mesh = geoms.get(index).getMesh();
int faceCount = Integer.parseInt(numfaces);
VertexBuffer originalIndexBuffer = mesh.getBuffer(Type.Index);
vb = new VertexBuffer(VertexBuffer.Type.Index);
if (originalIndexBuffer.getFormat() == Format.UnsignedInt){
// LOD buffer should also be integer
ib = BufferUtils.createIntBuffer(faceCount * 3);
sb = null;
vb.setupData(Usage.Static, 3, Format.UnsignedInt, ib);
}else{
sb = BufferUtils.createShortBuffer(faceCount * 3);
ib = null;
vb.setupData(Usage.Static, 3, Format.UnsignedShort, sb);
}
List<VertexBuffer> levels = lodLevels.get(index);
if (levels == null) {
// Create the LOD levels list
levels = new ArrayList<VertexBuffer>();
// Add the first LOD level (always the original index buffer)
levels.add(originalIndexBuffer);
lodLevels.put(index, levels);
}
levels.add(vb);
}
private void startLevelOfDetail(String numlevels) {
// numLevels = Integer.parseInt(numlevels);
}
private void endLevelOfDetail() {
// set the lod data for each mesh
for (Entry<List<VertexBuffer>> entry : lodLevels) {
Mesh m = geoms.get(entry.getKey()).getMesh();
List<VertexBuffer> levels = entry.getValue();
VertexBuffer[] levelArray = new VertexBuffer[levels.size()];
levels.toArray(levelArray);
m.setLodLevels(levelArray);
}
}
private void startLodGenerated(String depthsqr) {
}
private void pushBoneAssign(String vertIndex, String boneIndex, String weight) throws SAXException {
int vert = parseInt(vertIndex);
float w = parseFloat(weight);
byte bone = (byte) parseInt(boneIndex);
assert bone >= 0;
assert vert >= 0 && vert < mesh.getVertexCount();
int i;
float v = 0;
// see which weights are unused for a given bone
for (i = vert * 4; i < vert * 4 + 4; i++) {
v = weightsFloatData.get(i);
if (v == 0) {
break;
}
}
if (v != 0) {
logger.log(Level.WARNING, "Vertex {0} has more than 4 weights per vertex! Ignoring..", vert);
return;
}
weightsFloatData.put(i, w);
indicesData.put(i, bone);
actuallyHasWeights = true;
}
private void startSkeleton(String name) {
AssetKey assetKey = new AssetKey(folderName + name + ".xml");
try {
animData = (AnimData) assetManager.loadAsset(assetKey);
} catch (AssetNotFoundException ex){
logger.log(Level.WARNING, "Cannot locate {0} for model {1}", new Object[]{assetKey, key});
animData = null;
}
}
private void startSubmeshName(String indexStr, String nameStr) {
int index = Integer.parseInt(indexStr);
geoms.get(index).setName(nameStr);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attribs) throws SAXException {
if (ignoreUntilEnd != null) {
return;
}
if (qName.equals("texcoord")) {
pushTexCoord(attribs);
} else if (qName.equals("vertexboneassignment")) {
pushBoneAssign(attribs.getValue("vertexindex"),
attribs.getValue("boneindex"),
attribs.getValue("weight"));
} else if (qName.equals("face")) {
pushFace(attribs.getValue("v1"),
attribs.getValue("v2"),
attribs.getValue("v3"));
} else if (qName.equals("position")) {
pushAttrib(Type.Position, attribs);
} else if (qName.equals("normal")) {
pushAttrib(Type.Normal, attribs);
} else if (qName.equals("tangent")) {
pushTangent(attribs);
} else if (qName.equals("binormal")) {
pushAttrib(Type.Binormal, attribs);
} else if (qName.equals("colour_diffuse")) {
pushColor(attribs);
} else if (qName.equals("vertex")) {
startVertex();
} else if (qName.equals("faces")) {
startFaces(attribs.getValue("count"));
} else if (qName.equals("geometry")) {
String count = attribs.getValue("vertexcount");
if (count == null) {
count = attribs.getValue("count");
}
startGeometry(count);
} else if (qName.equals("vertexbuffer")) {
startVertexBuffer(attribs);
} else if (qName.equals("lodfacelist")) {
startLodFaceList(attribs.getValue("submeshindex"),
attribs.getValue("numfaces"));
} else if (qName.equals("lodgenerated")) {
startLodGenerated(attribs.getValue("fromdepthsquared"));
} else if (qName.equals("levelofdetail")) {
startLevelOfDetail(attribs.getValue("numlevels"));
} else if (qName.equals("boneassignments")) {
startBoneAssigns();
} else if (qName.equals("submesh")) {
if (submeshNamesHack) {
// Hack for blender2ogre only
startSubmeshName(attribs.getValue("index"), attribs.getValue("name"));
} else {
startSubMesh(attribs.getValue("material"),
attribs.getValue("usesharedvertices"),
attribs.getValue("use32bitindexes"),
attribs.getValue("operationtype"));
}
} else if (qName.equals("sharedgeometry")) {
String count = attribs.getValue("vertexcount");
if (count == null) {
count = attribs.getValue("count");
}
if (count != null && !count.equals("0")) {
startSharedGeom(count);
}
} else if (qName.equals("submeshes")) {
} else if (qName.equals("skeletonlink")) {
startSkeleton(attribs.getValue("name"));
} else if (qName.equals("submeshnames")) {
// setting submeshNamesHack to true will make "submesh" tag be interpreted
// as a "submeshname" tag.
submeshNamesHack = true;
} else if (qName.equals("submeshname")) {
startSubmeshName(attribs.getValue("index"), attribs.getValue("name"));
} else if (qName.equals("mesh")) {
} else {
logger.log(Level.WARNING, "Unknown tag: {0}. Ignoring.", qName);
ignoreUntilEnd = qName;
}
}
@Override
public void endElement(String uri, String name, String qName) {
if (ignoreUntilEnd != null) {
if (ignoreUntilEnd.equals(qName)) {
ignoreUntilEnd = null;
}
return;
}
// If submesh hack is enabled, ignore any submesh/submeshes
// end tags.
if (qName.equals("submesh") && !submeshNamesHack) {
usesBigIndices = false;
geom = null;
mesh = null;
} else if (qName.equals("submeshes") && !submeshNamesHack) {
// IMPORTANT: restore sharedmesh, for use with shared boneweights
geom = null;
mesh = sharedMesh;
usesSharedVerts = false;
} else if (qName.equals("faces")) {
if (ib != null) {
ib.flip();
} else {
sb.flip();
}
vb = null;
ib = null;
sb = null;
} else if (qName.equals("vertexbuffer")) {
fb = null;
vb = null;
} else if (qName.equals("geometry")
|| qName.equals("sharedgeometry")) {
// finish writing to buffers
for (VertexBuffer buf : mesh.getBufferList().getArray()) {
Buffer data = buf.getData();
if (data.position() != 0) {
data.flip();
}
}
mesh.updateBound();
mesh.setStatic();
if (qName.equals("sharedgeometry")) {
geom = null;
mesh = null;
}
} else if (qName.equals("lodfacelist")) {
sb.flip();
vb = null;
sb = null;
} else if (qName.equals("levelofdetail")) {
endLevelOfDetail();
} else if (qName.equals("boneassignments")) {
endBoneAssigns();
} else if (qName.equals("submeshnames")) {
// Restore default handling for "submesh" tag.
submeshNamesHack = false;
}
}
@Override
public void characters(char ch[], int start, int length) {
}
private Node compileModel() {
Node model = new Node(meshName + "-ogremesh");
for (int i = 0; i < geoms.size(); i++) {
Geometry g = geoms.get(i);
Mesh m = g.getMesh();
// New code for buffer extract
if (sharedMesh != null && usesSharedMesh.get(i)) {
m.extractVertexData(sharedMesh);
}
// Old code for buffer sharer
//if (sharedMesh != null && isUsingSharedVerts(g)) {
// m.setBound(sharedMesh.getBound().clone());
model.attachChild(geoms.get(i));
}
// Do not attach shared geometry to the node!
if (animData != null) {
// This model uses animation
// Old code for buffer sharer
// generate bind pose for mesh
// ONLY if not using shared geometry
// This includes the shared geoemtry itself actually
//if (sharedMesh != null) {
// sharedMesh.generateBindPose(!HARDWARE_SKINNING);
for (int i = 0; i < geoms.size(); i++) {
Geometry g = geoms.get(i);
Mesh m = geoms.get(i).getMesh();
m.generateBindPose(!HARDWARE_SKINNING);
// Old code for buffer sharer
//boolean useShared = isUsingSharedVerts(g);
//if (!useShared) {
// create bind pose
//m.generateBindPose(!HARDWARE_SKINNING);
}
// Put the animations in the AnimControl
HashMap<String, Animation> anims = new HashMap<String, Animation>();
ArrayList<Animation> animList = animData.anims;
for (int i = 0; i < animList.size(); i++) {
Animation anim = animList.get(i);
anims.put(anim.getName(), anim);
}
AnimControl ctrl = new AnimControl(animData.skeleton);
ctrl.setAnimations(anims);
model.addControl(ctrl);
// Put the skeleton in the skeleton control
SkeletonControl skeletonControl = new SkeletonControl(animData.skeleton);
// This will acquire the targets from the node
model.addControl(skeletonControl);
}
return model;
}
public Object load(AssetInfo info) throws IOException {
try {
key = info.getKey();
meshName = key.getName();
folderName = key.getFolder();
String ext = key.getExtension();
meshName = meshName.substring(0, meshName.length() - ext.length() - 1);
if (folderName != null && folderName.length() > 0) {
meshName = meshName.substring(folderName.length());
}
assetManager = info.getManager();
if (key instanceof OgreMeshKey) {
// OgreMeshKey is being used, try getting the material list
// from it
OgreMeshKey meshKey = (OgreMeshKey) key;
materialList = meshKey.getMaterialList();
String materialName = meshKey.getMaterialName();
// Material list not set but material name is available
if (materialList == null && materialName != null) {
OgreMaterialKey materialKey = new OgreMaterialKey(folderName + materialName + ".material");
try {
materialList = (MaterialList) assetManager.loadAsset(materialKey);
} catch (AssetNotFoundException e) {
logger.log(Level.WARNING, "Cannot locate {0} for model {1}", new Object[]{materialKey, key});
}
}
}else{
// Make sure to reset it to null so that previous state
// doesn't leak onto this one
materialList = null;
}
// If for some reason material list could not be found through
// OgreMeshKey, or if regular ModelKey specified, load using
// default method.
if (materialList == null){
OgreMaterialKey materialKey = new OgreMaterialKey(folderName + meshName + ".material");
try {
materialList = (MaterialList) assetManager.loadAsset(materialKey);
} catch (AssetNotFoundException e) {
logger.log(Level.WARNING, "Cannot locate {0} for model {1}", new Object[]{ materialKey, key });
}
}
// Added by larynx 25.06.2011
// Android needs the namespace aware flag set to true
// Kirill 30.06.2011
// Now, hack is applied for both desktop and android to avoid
// checking with JmeSystem.
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
XMLReader xr = factory.newSAXParser().getXMLReader();
xr.setContentHandler(this);
xr.setErrorHandler(this);
InputStreamReader r = null;
try {
r = new InputStreamReader(info.openStream());
xr.parse(new InputSource(r));
} finally {
if (r != null){
r.close();
}
}
return compileModel();
} catch (SAXException ex) {
IOException ioEx = new IOException("Error while parsing Ogre3D mesh.xml");
ioEx.initCause(ex);
throw ioEx;
} catch (ParserConfigurationException ex) {
IOException ioEx = new IOException("Error while parsing Ogre3D mesh.xml");
ioEx.initCause(ex);
throw ioEx;
}
}
}
|
package etomica.conjugategradient;
import Jama.Matrix;
/**
* @author taitan
* @author msellers
*
*/
public class SteepestDescent {
protected int imax;
protected Matrix A;
protected Matrix B, X, R, Q;
public SteepestDescent(Matrix A, Matrix x, Matrix b, int iter){
this.imax = iter;
this.B = b;
this.A = A;
this.X = x;
}
/** Steepest Descent solution for
* Ax = b
@param A Matrix (square, symmetric, and positive-definite/indefinite)
@param x Vector (initial guess for unknown solution)
@param b Vector
@return x Vector (solution)
*/
public Matrix SteepestDescentAlgorithm(){
/*
* an error tolerance, 0 <= epsilon < 1
* as default, let epsilon equal to 0.0001
*/
double epsilon = 0.000001;
double delta;
double delta0;
double alpha;
double e2d0;
int i = 0;
// r = b - A*x
R = B.copy();
R.minusEquals(A.times(X));
// delta = r^T*r
delta = ((R.transpose()).times(R)).trace();
delta0 = delta;
e2d0 = epsilon*epsilon*delta0;
while (i < imax && delta > e2d0 ){
Q = A.times(R);
alpha = delta / ((R.transpose()).times(Q)).trace();
X.plusEquals(R.times(alpha));
//Check for exact residual computation or fast recursive formula. As default, exact set every 50 iterations.
if (i%50 == 0){
R = B.copy();
R.minusEquals(A.times(X));
}
else if (delta <= e2d0){
R = B.copy();
R.minusEquals(A.times(X));
}
else {
R.minusEquals(Q.times(alpha));
}
delta = ((R.transpose()).times(R)).trace();
i++;
}
return X;
}
public static void main (String [] args){
double[][] valsA = {{3.,2.},{2.,6.}};
Matrix A = new Matrix(valsA);
double[][] valsB = {{2.},{-8.}};
Matrix b = new Matrix(valsB);
double[][] valsX = {{-8.},{8.}};
Matrix x = new Matrix(valsX);
A.print(10,3);
b.print(10,3);
x.print(10,3);
SteepestDescent steepestDescent = new SteepestDescent(A, x, b, 150);
x = steepestDescent.SteepestDescentAlgorithm();
x.print(10, 4);
}
}
|
package net.sf.farrago.type;
import java.nio.charset.Charset;
import java.sql.*;
import java.util.*;
import javax.jmi.model.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.core.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.fem.sql2003.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.type.runtime.*;
import net.sf.farrago.util.*;
import openjava.mop.*;
import openjava.ptree.*;
import org.eigenbase.oj.*;
import org.eigenbase.oj.util.*;
import org.eigenbase.rel.*;
import org.eigenbase.reltype.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.util.*;
import org.eigenbase.resource.EigenbaseResource;
import java.util.List;
/**
* FarragoTypeFactoryImpl is the Farrago-specific implementation of the
* RelDataTypeFactory interface.
*
* @author John V. Sichi
* @version $Id$
*/
public class FarragoTypeFactoryImpl extends OJTypeFactoryImpl
implements FarragoTypeFactory
{
private static final int unknownCharPrecision = 1024;
/** Repos for type object definitions. */
private final FarragoRepos repos;
private int nextGeneratedClassId;
private Map mapTypeToOJClass;
public FarragoTypeFactoryImpl(FarragoRepos repos)
{
super(new OJClassMap(FarragoSyntheticObject.class));
this.repos = repos;
mapTypeToOJClass = new HashMap();
}
// implement FarragoTypeFactory
public FarragoRepos getRepos()
{
return repos;
}
// override RelDataTypeFactoryImpl
public RelDataType createJoinType(RelDataType [] types)
{
assert (types.length == 2);
return JoinRel.createJoinType(this, types[0], types[1], null);
}
// implement FarragoTypeFactory
public RelDataType createCwmElementType(
FemAbstractTypedElement abstractElement)
{
FemSqltypedElement element = FarragoCatalogUtil.toFemSqltypedElement(
abstractElement);
CwmClassifier classifier = element.getType();
RelDataType type = createCwmTypeImpl(classifier, element);
boolean isNullable = true;
if (abstractElement instanceof CwmColumn) {
isNullable = FarragoCatalogUtil.isColumnNullable(
getRepos(), (CwmColumn) abstractElement);
}
type = createTypeWithNullability(type, isNullable);
return type;
}
// implement FarragoTypeFactory
public RelDataType createCwmType(
CwmSqldataType cwmType)
{
return createCwmTypeImpl(cwmType, null);
}
protected RelDataType createCwmTypeImpl(
CwmClassifier classifier,
FemSqltypedElement element)
{
if (classifier instanceof CwmSqlsimpleType) {
CwmSqlsimpleType simpleType = (CwmSqlsimpleType) classifier;
SqlTypeName typeName = SqlTypeName.get(simpleType.getName());
assert(typeName != null);
Integer pPrecision = null;
Integer pScale = null;
if (element != null) {
pPrecision = element.getLength();
if (pPrecision == null) {
pPrecision = element.getPrecision();
}
pScale = element.getScale();
}
RelDataType type;
if (pScale != null) {
assert(pPrecision != null);
type = createSqlType(
typeName,
pPrecision.intValue(),
pScale.intValue());
} else if (pPrecision != null) {
type = createSqlType(
typeName,
pPrecision.intValue());
} else {
type = createSqlType(
typeName);
}
if (element != null) {
String charsetName = element.getCharacterSetName();
SqlCollation collation;
if (!charsetName.equals("")) {
// TODO: collation in CWM
collation = new SqlCollation(
SqlCollation.Coercibility.Implicit);
Charset charSet = Charset.forName(charsetName);
type = createTypeWithCharsetAndCollation(
type,
charSet,
collation);
}
}
return type;
} else if (classifier instanceof FemSqlcollectionType) {
FemSqlcollectionType collectionType =
(FemSqlcollectionType) classifier;
assert(collectionType instanceof FemSqlmultisetType) :
"todo array type creation not yet implemented";
FemSqltypeAttribute femComponentType = (FemSqltypeAttribute)
collectionType.getFeature().get(0);
RelDataType componentType =
createCwmElementType(femComponentType);
if (!componentType.isStruct()) {
// REVIEW jvs 12-Feb-2005: what is this for?
componentType = createStructType(
new RelDataType[]{componentType},
new String[]{"EXP$0"});
}
return createMultisetType(componentType, -1);
} else if (classifier instanceof FemSqldistinguishedType) {
FemSqldistinguishedType type = (FemSqldistinguishedType) classifier;
RelDataType predefinedType = createCwmElementType(type);
RelDataTypeField field = new RelDataTypeFieldImpl(
"PREDEFINED",
0,
predefinedType);
SqlIdentifier id = FarragoCatalogUtil.getQualifiedName(type);
return canonize(
new ObjectSqlType(
SqlTypeName.Distinct, id, false,
new RelDataTypeField [] {field},
getUserDefinedComparability(type)));
} else if (classifier instanceof FemSqlobjectType) {
FemSqlobjectType objectType =
(FemSqlobjectType) classifier;
// first, create an anonymous row type
RelDataType structType = createStructTypeFromClassifier(
objectType);
// then, christen it
SqlIdentifier id = FarragoCatalogUtil.getQualifiedName(objectType);
return canonize(
new ObjectSqlType(
SqlTypeName.Structured, id, false, structType.getFields(),
getUserDefinedComparability(objectType)));
} else if (classifier instanceof FemSqlrowType) {
FemSqlrowType rowType = (FemSqlrowType) classifier;
RelDataType structType = createStructTypeFromClassifier(rowType);
return canonize(structType);
} else {
throw Util.needToImplement(classifier);
}
}
private RelDataTypeComparability getUserDefinedComparability(
FemUserDefinedType type)
{
if (type.getOrdering().isEmpty()) {
return RelDataTypeComparability.None;
}
assert(type.getOrdering().size() == 1);
FemUserDefinedOrdering udo =
(FemUserDefinedOrdering) type.getOrdering().iterator().next();
if (udo.isFull()) {
return RelDataTypeComparability.All;
} else {
return RelDataTypeComparability.Unordered;
}
}
// implement FarragoTypeFactory
public RelDataType createStructTypeFromClassifier(
CwmClassifier classifier)
{
final List featureList =
FarragoCatalogUtil.getStructuralFeatures(classifier);
if (featureList.isEmpty()) {
return null;
}
return createStructType(
new RelDataTypeFactory.FieldInfo() {
public int getFieldCount()
{
return featureList.size();
}
public String getFieldName(int index)
{
final FemAbstractTypedElement element =
(FemAbstractTypedElement) featureList.get(index);
return element.getName();
}
public RelDataType getFieldType(int index)
{
final FemAbstractTypedElement element =
(FemAbstractTypedElement) featureList.get(index);
RelDataType type = createCwmElementType(element);
return type;
}
});
}
// implement FarragoTypeFactory
public RelDataType createResultSetType(
final ResultSetMetaData metaData,
final boolean substitute)
{
return createStructType(
new RelDataTypeFactory.FieldInfo() {
public int getFieldCount()
{
try {
return metaData.getColumnCount();
} catch (SQLException ex) {
throw newSqlTypeException(ex);
}
}
public String getFieldName(int index)
{
int iOneBased = index + 1;
try {
return metaData.getColumnName(iOneBased);
} catch (SQLException ex) {
throw newSqlTypeException(ex);
}
}
public RelDataType getFieldType(int index)
{
int iOneBased = index + 1;
try {
int typeOrdinal = metaData.getColumnType(iOneBased);
int precision = metaData.getPrecision(iOneBased);
int scale = metaData.getScale(iOneBased);
boolean isNullable =
(metaData.isNullable(iOneBased)
!= ResultSetMetaData.columnNoNulls);
try {
RelDataType type = createJdbcType(
typeOrdinal, precision, scale, isNullable,
substitute);
return (RelDataType) type;
} catch (Throwable ex) {
throw newUnsupportedJdbcType(
metaData.getTableName(iOneBased),
metaData.getColumnName(iOneBased),
metaData.getColumnTypeName(iOneBased),
typeOrdinal,
precision,
scale,
ex);
}
} catch (Throwable ex) {
throw newSqlTypeException(ex);
}
}
});
}
// implement FarragoTypeFactory
public RelDataType createJdbcColumnType(
ResultSet getColumnsResultSet,
boolean substitute)
{
try {
int typeOrdinal = getColumnsResultSet.getInt(5);
int precision = getColumnsResultSet.getInt(7);
int scale = getColumnsResultSet.getInt(9);
boolean isNullable =
getColumnsResultSet.getInt(11)
!= DatabaseMetaData.columnNoNulls;
try {
RelDataType type =
createJdbcType(
typeOrdinal, precision, scale, isNullable,
substitute);
return (RelDataType) type;
} catch (Throwable ex) {
throw newUnsupportedJdbcType(
getColumnsResultSet.getString(3),
getColumnsResultSet.getString(4),
getColumnsResultSet.getString(6),
typeOrdinal,
precision,
scale,
ex);
}
} catch (Throwable ex) {
throw newSqlTypeException(ex);
}
}
private RelDataType createJdbcType(
int typeOrdinal,
int precision,
int scale,
boolean isNullable,
boolean substitute)
throws Throwable
{
RelDataType type;
// TODO jvs 1-Mar-2006: Avoid using try/catch for substitution;
// instead, get lower levels to participate. Particularly bad is
// catching Throwable, which could be an assertion error which has
// nothing to do with type construction. Also, supply more information
// in cases where we currently just throw a plain
// UnsupportedOperationException.
try {
SqlTypeName typeName = SqlTypeName.getNameForJdbcType(typeOrdinal);
if (typeName == null) {
if (!substitute) {
throw new UnsupportedOperationException();
}
typeName = SqlTypeName.Varchar;
precision = unknownCharPrecision;
}
if (SqlTypeUtil.inCharFamily(typeName)) {
// NOTE jvs 4-Mar-2004: This is for drivers like hsqldb which
// return 0 or large numbers to indicate unlimited precision.
if ((precision == 0) || (precision > 65535)) {
if (!substitute) {
throw new UnsupportedOperationException();
}
precision = unknownCharPrecision;
}
}
// TODO jvs 7-Dec-2005: proper datetime precision lowering once we
// support anything greater than 0 for datetime precision; for now
// we just toss datetime precision.
boolean isDatetime =
SqlTypeFamily.Datetime.getTypeNames().contains(typeName);
if (typeName == SqlTypeName.Decimal) {
// Limit DECIMAL precision and scale.
int maxPrecision = SqlTypeName.Decimal.MAX_NUMERIC_PRECISION;
if (precision == 0) {
// Deal with bogus precision 0, e.g. from Oracle
precision = maxPrecision;
}
if ((precision > maxPrecision) || (scale > precision)) {
if (!substitute) {
throw new UnsupportedOperationException();
}
precision = maxPrecision;
// In the case where we lost precision, we cap the scale at
// 6. This is an arbitrary decision just like the scale of
// division, and we expect to have to revisit it; perhaps
// we could allow it to be overridden via a column-level
// SQL/MED storage option.
int cappedScale = 6;
if (scale > cappedScale) {
scale = cappedScale;
}
}
if (scale < 0) {
if (!substitute) {
throw new UnsupportedOperationException();
}
scale = 0;
}
type = createSqlType(
typeName,
precision,
scale);
} else if (typeName.allowsScale()) {
// This is probably never used because Decimal is the
// only type which supports scale.
type = createSqlType(
typeName, precision, scale);
} else if (typeName.allowsPrec() && !isDatetime) {
type = createSqlType(
typeName, precision);
} else {
type = createSqlType(
typeName);
}
} catch (Throwable ex) {
if (substitute) {
// last resort
type = createSqlType(
SqlTypeName.Varchar,
unknownCharPrecision);
} else {
// Rethrow
throw ex;
}
}
type = createTypeWithNullability(
type, isNullable);
return type;
}
private EigenbaseException newSqlTypeException(Throwable ex)
{
return FarragoResource.instance().JdbcDriverTypeInfoFailed.ex(ex);
}
private EigenbaseException newUnsupportedJdbcType(
String tableName,
String columnName,
String typeName,
int typeOrdinal,
int precision,
int scale,
Throwable ex)
{
if (ex instanceof UnsupportedOperationException) {
// hide this because it's not a real excn
ex = null;
}
return FarragoResource.instance().JdbcDriverTypeUnsupported.ex(
repos.getLocalizedObjectName(tableName),
repos.getLocalizedObjectName(columnName),
repos.getLocalizedObjectName(typeName),
typeOrdinal,
precision,
scale,
ex);
}
int generateClassId()
{
return nextGeneratedClassId++;
}
// implement FarragoTypeFactory
public RelDataType createMofType(StructuralFeature feature)
{
boolean isNullable = true;
SqlTypeName typeName = null;
if (feature != null) {
Classifier classifier = feature.getType();
String mofTypeName = classifier.getName();
if (mofTypeName.equals("Boolean")) {
typeName = SqlTypeName.Boolean;
} else if (mofTypeName.equals("Byte")) {
typeName = SqlTypeName.Tinyint;
} else if (mofTypeName.equals("Double")) {
typeName = SqlTypeName.Double;
} else if (mofTypeName.equals("Float")) {
typeName = SqlTypeName.Real;
} else if (mofTypeName.equals("Integer")) {
typeName = SqlTypeName.Integer;
} else if (mofTypeName.equals("Long")) {
typeName = SqlTypeName.Bigint;
} else if (mofTypeName.equals("Short")) {
typeName = SqlTypeName.Smallint;
}
isNullable = (feature.getMultiplicity().getLower() == 0);
}
RelDataType type;
if (typeName == null) {
// TODO: cleanup
type = createSqlType(SqlTypeName.Varchar, unknownCharPrecision);
} else {
type = createSqlType(typeName);
}
type = createTypeWithNullability(
type,
isNullable);
return type;
}
// override OJTypeFactoryImpl
public OJClass toOJClass(
OJClass declarer,
RelDataType type)
{
if (type.getSqlTypeName() == SqlTypeName.Null) {
return OJSystem.OBJECT;
} else if (type instanceof AbstractSqlType) {
OJClass ojClass = (OJClass) mapTypeToOJClass.get(type);
if (ojClass != null) {
return ojClass;
}
ojClass = newOJClass(declarer, type);
mapTypeToOJClass.put(type, ojClass);
mapOJClassToType.put(ojClass, type);
return ojClass;
} else {
return super.toOJClass(declarer, type);
}
}
private OJClass newOJClass(
OJClass declarer,
RelDataType type)
{
switch (type.getSqlTypeName().getOrdinal()) {
case SqlTypeName.Boolean_ordinal:
if (type.isNullable()) {
return OJClass.forClass(
NullablePrimitive.NullableBoolean.class);
} else {
return OJSystem.BOOLEAN;
}
case SqlTypeName.Tinyint_ordinal:
if (type.isNullable()) {
return OJClass.forClass(
NullablePrimitive.NullableByte.class);
} else {
return OJSystem.BYTE;
}
case SqlTypeName.Smallint_ordinal:
if (type.isNullable()) {
return OJClass.forClass(
NullablePrimitive.NullableShort.class);
} else {
return OJSystem.SHORT;
}
case SqlTypeName.Symbol_ordinal:
case SqlTypeName.Integer_ordinal:
if (type.isNullable()) {
return OJClass.forClass(
NullablePrimitive.NullableInteger.class);
} else {
return OJSystem.INT;
}
case SqlTypeName.Bigint_ordinal:
if (type.isNullable()) {
return OJClass.forClass(
NullablePrimitive.NullableLong.class);
} else {
return OJSystem.LONG;
}
case SqlTypeName.Decimal_ordinal:
return newDecimalOJClass(
declarer, type);
case SqlTypeName.Real_ordinal:
if (type.isNullable()) {
return OJClass.forClass(
NullablePrimitive.NullableFloat.class);
} else {
return OJSystem.FLOAT;
}
case SqlTypeName.Float_ordinal:
case SqlTypeName.Double_ordinal:
if (type.isNullable()) {
return OJClass.forClass(
NullablePrimitive.NullableDouble.class);
} else {
return OJSystem.DOUBLE;
}
case SqlTypeName.Date_ordinal:
return newDatetimeOJClass(
SqlDateTimeWithoutTZ.SqlDate.class, declarer, type);
case SqlTypeName.Time_ordinal:
return newDatetimeOJClass(
SqlDateTimeWithoutTZ.SqlTime.class, declarer, type);
case SqlTypeName.Timestamp_ordinal:
return newDatetimeOJClass(
SqlDateTimeWithoutTZ.SqlTimestamp.class, declarer, type);
case SqlTypeName.Char_ordinal:
case SqlTypeName.Varchar_ordinal:
case SqlTypeName.Binary_ordinal:
case SqlTypeName.Varbinary_ordinal:
case SqlTypeName.Multiset_ordinal:
return newStringOJClass(
declarer, type);
case SqlTypeName.Structured_ordinal:
return createOJClassForRecordType(declarer, type);
default:
throw new AssertionError();
}
}
private OJClass newDecimalOJClass(
OJClass declarer, RelDataType type)
{
Class superclass = EncodedSqlDecimal.class;
MemberDeclarationList memberDecls = new MemberDeclarationList();
memberDecls.add(
new MethodDeclaration(
new ModifierList(ModifierList.PROTECTED),
OJUtil.typeNameForClass(int.class),
EncodedSqlDecimal.GET_PRECISION_METHOD_NAME,
new ParameterList(),
new TypeName[0],
new StatementList(
new ReturnStatement(
Literal.makeLiteral(type.getPrecision())))));
memberDecls.add(
new MethodDeclaration(
new ModifierList(ModifierList.PROTECTED),
OJUtil.typeNameForClass(int.class),
EncodedSqlDecimal.GET_SCALE_METHOD_NAME,
new ParameterList(),
new TypeName[0],
new StatementList(
new ReturnStatement(
Literal.makeLiteral(type.getScale())))));
return newHolderOJClass(
superclass, memberDecls, declarer, type);
}
private OJClass newDatetimeOJClass(
Class superclass, OJClass declarer, RelDataType type)
{
return newHolderOJClass(
superclass, new MemberDeclarationList(), declarer, type);
}
private OJClass newStringOJClass(
OJClass declarer, RelDataType type)
{
Class superclass;
MemberDeclarationList memberDecls = new MemberDeclarationList();
if (type.getCharset() == null) {
superclass = BytePointer.class;
} else {
String charsetName = type.getCharset().name();
superclass = EncodedCharPointer.class;
memberDecls.add(
new MethodDeclaration(
new ModifierList(ModifierList.PROTECTED),
OJUtil.typeNameForClass(String.class),
"getCharsetName",
new ParameterList(),
new TypeName[0],
new StatementList(
new ReturnStatement(
Literal.makeLiteral(charsetName)))));
}
return newHolderOJClass(
superclass, memberDecls, declarer, type);
}
private OJClass newHolderOJClass(
Class superclass,
MemberDeclarationList memberDecls,
OJClass declarer,
RelDataType type)
{
TypeName [] superDecl =
new TypeName [] { OJUtil.typeNameForClass(superclass) };
TypeName [] interfaceDecls = null;
if (type.isNullable()) {
interfaceDecls =
new TypeName [] {
OJUtil.typeNameForClass(NullableValue.class)
};
}
ClassDeclaration decl =
new ClassDeclaration(new ModifierList(ModifierList.PUBLIC
| ModifierList.STATIC),
"Oj_inner_" + generateClassId(),
superDecl,
interfaceDecls,
memberDecls);
OJClass ojClass = new OJTypedClass(declarer, decl, type);
try {
declarer.addClass(ojClass);
} catch (CannotAlterException e) {
throw Util.newInternal(e, "holder class must be OJClassSourceCode");
}
Environment env = declarer.getEnvironment();
OJUtil.recordMemberClass(
env,
declarer.getName(),
decl.getName());
OJUtil.getGlobalEnvironment(env).record(
ojClass.getName(),
ojClass);
return ojClass;
}
// implement FarragoTypeFactory
public Expression getValueAccessExpression(
RelDataType type,
Expression expr)
{
if (SqlTypeUtil.isDatetime(type) ||
SqlTypeUtil.isDecimal(type) ||
((getClassForPrimitive(type) != null) && type.isNullable()))
{
return new FieldAccess(expr, NullablePrimitive.VALUE_FIELD_NAME);
} else {
return expr;
}
}
// implement FarragoTypeFactory
public Class getClassForPrimitive(
RelDataType type)
{
SqlTypeName typeName = type.getSqlTypeName();
if (typeName == null) {
return null;
}
switch(typeName.getOrdinal()) {
case SqlTypeName.Boolean_ordinal:
return boolean.class;
case SqlTypeName.Tinyint_ordinal:
return byte.class;
case SqlTypeName.Smallint_ordinal:
return short.class;
case SqlTypeName.Integer_ordinal:
return int.class;
case SqlTypeName.Bigint_ordinal:
case SqlTypeName.Decimal_ordinal:
return long.class;
case SqlTypeName.Real_ordinal:
return float.class;
case SqlTypeName.Float_ordinal:
case SqlTypeName.Double_ordinal:
return double.class;
case SqlTypeName.Date_ordinal:
case SqlTypeName.Time_ordinal:
case SqlTypeName.Timestamp_ordinal:
return SqlDateTimeWithoutTZ.getPrimitiveClass();
default:
return null;
}
}
// implement FarragoTypeFactory
public Class getClassForJavaParamStyle(
RelDataType type)
{
SqlTypeName typeName = type.getSqlTypeName();
if (typeName == null) {
return null;
}
// NOTE jvs 11-Jan-2005: per
// SQL:2003 Part 13 Section 4.5,
// these mappings are based on Appendix B of the JDBC 3.0
// spec
switch(typeName.getOrdinal()) {
case SqlTypeName.Decimal_ordinal:
return java.math.BigDecimal.class;
case SqlTypeName.Char_ordinal:
case SqlTypeName.Varchar_ordinal:
return String.class;
case SqlTypeName.Binary_ordinal:
case SqlTypeName.Varbinary_ordinal:
return byte [].class;
case SqlTypeName.Date_ordinal:
return java.sql.Date.class;
case SqlTypeName.Time_ordinal:
return java.sql.Time.class;
case SqlTypeName.Timestamp_ordinal:
return java.sql.Timestamp.class;
default:
return getClassForPrimitive(type);
}
}
// implement RelDataTypeFactory
public RelDataType createJavaType(
Class clazz)
{
RelDataType type = super.createJavaType(clazz);
return addDefaultAttributes(type);
}
// implement RelDataTypeFactory
public RelDataType createSqlType(
SqlTypeName typeName)
{
RelDataType type = super.createSqlType(typeName);
return addDefaultAttributes(type);
}
// implement RelDataTypeFactory
public RelDataType createSqlType(
SqlTypeName typeName,
int precision)
{
RelDataType type = super.createSqlType(typeName, precision);
return addDefaultAttributes(type);
}
// implement RelDataTypeFactory
public RelDataType createSqlType(
SqlTypeName typeName,
int precision,
int scale)
{
RelDataType type = super.createSqlType(typeName, precision, scale);
return addDefaultAttributes(type);
}
private RelDataType addDefaultAttributes(RelDataType type)
{
if (SqlTypeUtil.inCharFamily(type)) {
Charset charset = getDefaultCharset();
SqlCollation collation = new SqlCollation(
SqlCollation.Coercibility.Coercible);
type = createTypeWithCharsetAndCollation(
type,
charset,
collation);
}
return type;
}
/**
* Returns the default {@link Charset} for string types.
*/
protected Charset getDefaultCharset()
{
String charsetName = repos.getDefaultCharsetName();
Charset charset = Charset.forName(charsetName);
return charset;
}
}
// End FarragoTypeFactoryImpl.java
|
package org.fastframework.util;
import com.sun.org.apache.bcel.internal.generic.RET;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.util.JSONPObject;
import org.fastframework.mvc.annotation.MediaTypes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class WebUtil {
/**
*
*
* @param request
* @return
*/
public static List<Object> getRequestParamMap(HttpServletRequest request, Class<?>[] controllerParamTypes) {
List<Object> requestParamList = new ArrayList<>();
Enumeration<String> paramNames = request.getParameterNames();
int i = 0;
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
if (paramValues != null) {
if (1 == paramValues.length) {
String paramValue = paramValues[0];
Class<?> paramType = controllerParamTypes[i];
// int/Integerlong/Longdouble/DoubleString
if (paramType.equals(int.class) || paramType.equals(Integer.class)) {
requestParamList.add(Integer.parseInt(paramValue));
} else if (paramType.equals(long.class) || paramType.equals(Long.class)) {
requestParamList.add(Long.parseLong(paramValue));
} else if (paramType.equals(double.class) || paramType.equals(Double.class)) {
requestParamList.add(Double.parseDouble(paramValue));
} else if (paramType.equals(String.class)) {
requestParamList.add(paramValue);
}
}
// TODO
}
i++;
}
return requestParamList;
}
public static Object getRequestBody(HttpServletRequest request, Class<?> clzz) {
InputStream is;
String tempStr;
Object result = null;
try {
is = request.getInputStream();
if (request.getContentType().equals(MediaTypes.TEXT_PLAIN)) {
result = IOUtils.toString(is);
} else if (request.getContentType().equals(MediaTypes.JSON_UTF_8)) {
tempStr = IOUtils.toString(is, Charset.forName("UTF-8"));
result = JSONUtil.toObject(tempStr, clzz);
} else if (request.getContentType().equals(MediaTypes.JSON)) {
tempStr = IOUtils.toString(is);
result = JSONUtil.toObject(tempStr, clzz);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
|
package liquibase.diff;
import liquibase.database.Database;
import liquibase.diff.compare.CompareControl;
import liquibase.diff.compare.DatabaseObjectComparatorFactory;
import liquibase.exception.DatabaseException;
import liquibase.snapshot.DatabaseSnapshot;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Catalog;
import liquibase.structure.core.Column;
import liquibase.structure.core.Schema;
import liquibase.util.StringUtils;
import java.io.*;
import java.util.*;
public class DiffResult {
private DatabaseSnapshot referenceSnapshot;
private DatabaseSnapshot comparisonSnapshot;
private CompareControl compareControl;
private StringDiff productNameDiff;
private StringDiff productVersionDiff;
private Set<DatabaseObject> missingObjects = new HashSet<DatabaseObject>();
private Set<DatabaseObject> unexpectedObjects = new HashSet<DatabaseObject>();
private Map<DatabaseObject, ObjectDifferences> changedObjects = new HashMap<DatabaseObject, ObjectDifferences>();
public DiffResult(DatabaseSnapshot referenceDatabaseSnapshot, DatabaseSnapshot comparisonDatabaseSnapshot, CompareControl compareControl) {
this.referenceSnapshot = referenceDatabaseSnapshot;
this.comparisonSnapshot = comparisonDatabaseSnapshot;
this.compareControl = compareControl;
}
public DatabaseSnapshot getReferenceSnapshot() {
return referenceSnapshot;
}
public DatabaseSnapshot getComparisonSnapshot() {
return comparisonSnapshot;
}
public StringDiff getProductNameDiff() {
return productNameDiff;
}
public void setProductNameDiff(StringDiff productNameDiff) {
this.productNameDiff = productNameDiff;
}
public StringDiff getProductVersionDiff() {
return productVersionDiff;
}
public void setProductVersionDiff(StringDiff productVersionDiff) {
this.productVersionDiff = productVersionDiff;
}
public CompareControl getCompareControl() {
return compareControl;
}
public Set<? extends DatabaseObject> getMissingObjects() {
return missingObjects;
}
public <T extends DatabaseObject> Set<T> getMissingObjects(Class<T> type) {
Set returnSet = new HashSet();
for (DatabaseObject obj : missingObjects) {
if (type.isAssignableFrom(obj.getClass())) {
returnSet.add(obj);
}
}
return returnSet;
}
public <T extends DatabaseObject> SortedSet<T> getMissingObjects(Class<T> type, Comparator<DatabaseObject> comparator) {
TreeSet<T> set = new TreeSet<T>(comparator);
set.addAll(getMissingObjects(type));
return set;
}
public <T extends DatabaseObject> T getMissingObject(T example, CompareControl.SchemaComparison[] schemaComparisons) {
Database accordingTo = getComparisonSnapshot().getDatabase();
DatabaseObjectComparatorFactory comparator = DatabaseObjectComparatorFactory.getInstance();
for (T obj : (Set<T>) getMissingObjects(example.getClass())) {
if (comparator.isSameObject(obj, example, schemaComparisons, accordingTo)) {
return obj;
}
}
return null;
}
public void addMissingObject(DatabaseObject obj) {
if (obj instanceof Column && ((Column) obj).getComputed() != null && ((Column) obj).getComputed()) {
return; //not really missing, it's a virtual column
}
missingObjects.add(obj);
}
public Set<? extends DatabaseObject> getUnexpectedObjects() {
return unexpectedObjects;
}
public <T extends DatabaseObject> Set<T> getUnexpectedObjects(Class<T> type) {
Set returnSet = new HashSet();
for (DatabaseObject obj : unexpectedObjects) {
if (type.isAssignableFrom(obj.getClass())) {
returnSet.add(obj);
}
}
return returnSet;
}
public <T extends DatabaseObject> SortedSet<T> getUnexpectedObjects(Class<T> type, Comparator<DatabaseObject> comparator) {
TreeSet<T> set = new TreeSet<T>(comparator);
set.addAll(getUnexpectedObjects(type));
return set;
}
public <T extends DatabaseObject> T getUnexpectedObject(T example, CompareControl.SchemaComparison[] schemaComparisons) {
Database accordingTo = this.getComparisonSnapshot().getDatabase();
DatabaseObjectComparatorFactory comparator = DatabaseObjectComparatorFactory.getInstance();
for (T obj : (Set<T>) getUnexpectedObjects(example.getClass())) {
if (comparator.isSameObject(obj, example, schemaComparisons, accordingTo)) {
return obj;
}
}
return null;
}
public void addUnexpectedObject(DatabaseObject obj) {
unexpectedObjects.add(obj);
}
public Map<DatabaseObject, ObjectDifferences> getChangedObjects() {
return changedObjects;
}
public <T extends DatabaseObject> Map<T, ObjectDifferences> getChangedObjects(Class<T> type) {
Map returnSet = new HashMap();
for (Map.Entry<DatabaseObject, ObjectDifferences> obj : changedObjects.entrySet()) {
if (type.isAssignableFrom(obj.getKey().getClass())) {
returnSet.put(obj.getKey(), obj.getValue());
}
}
return returnSet;
}
public <T extends DatabaseObject> SortedMap<T, ObjectDifferences> getChangedObjects(Class<T> type, Comparator<DatabaseObject> comparator) {
SortedMap<T, ObjectDifferences> map = new TreeMap<T, ObjectDifferences>(comparator);
map.putAll(getChangedObjects(type));
return map;
}
public ObjectDifferences getChangedObject(DatabaseObject example, CompareControl.SchemaComparison[] schemaComparisons) {
Database accordingTo = this.getComparisonSnapshot().getDatabase();
DatabaseObjectComparatorFactory comparator = DatabaseObjectComparatorFactory.getInstance();
for (Map.Entry<? extends DatabaseObject, ObjectDifferences> entry : getChangedObjects(example.getClass()).entrySet()) {
if (comparator.isSameObject(entry.getKey(), example, schemaComparisons, accordingTo)) {
return entry.getValue();
}
}
return null;
}
public void addChangedObject(DatabaseObject obj, ObjectDifferences differences) {
if (obj instanceof Catalog || obj instanceof Schema) {
if (differences.getSchemaComparisons() != null && differences.getDifferences().size() == 1 && differences.getDifference("name") != null) {
if (obj instanceof Catalog && this.getReferenceSnapshot().getDatabase().supportsSchemas()) { //still save name
changedObjects.put(obj, differences);
return;
} else {
return; //don't save name differences
}
}
}
changedObjects.put(obj, differences);
}
public boolean areEqual() throws DatabaseException, IOException {
// boolean differencesInData = false;
// if (compareControl.shouldDiffData()) {
// List<ChangeSet> changeSets = new ArrayList<ChangeSet>();
// addInsertDataChanges(changeSets, dataDir);
// differencesInData = !changeSets.isEmpty();
return missingObjects.size() == 0 && unexpectedObjects.size() == 0 && changedObjects.size() == 0;
}
public Set<Class<? extends DatabaseObject>> getComparedTypes() {
return compareControl.getComparedTypes();
}
}
|
package io.mangoo.crypto;
import java.util.Base64;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import com.google.common.base.Charsets;
import io.mangoo.configuration.Config;
import io.mangoo.core.Application;
import io.mangoo.enums.Key;
/**
* Convenient class for encryption and decryption
*
* @author svenkubiak
*
*/
public class Crypto {
private static final Logger LOG = LogManager.getLogger(Crypto.class);
private static final Config CONFIG = Application.getConfig();
private static final int KEYINDEX_START = 0;
private static final int BLOCK_SIZE = 16;
private static final int KEYLENGTH_16 = 16;
private static final int KEYLENGTH_24 = 24;
private static final int KEYLENGTH_32 = 32;
private static final Base64.Encoder base64Encoder = Base64.getEncoder();
private static final Base64.Decoder base64Decoder = Base64.getDecoder();
private final PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
/**
* Decrypts an given encrypted text using the application secret property (application.secret) as key
*
* @param encrytedText The encrypted text
* @return The clear text or null if decryption fails
*/
public String decrypt(String encrytedText) {
Objects.requireNonNull(encrytedText, "encrytedText can not be null");
return decrypt(encrytedText, getSizedKey(CONFIG.getString(Key.APPLICATION_SECRET)));
}
/**
* Decrypts an given encrypted text using the given key
*
* @param encrytedText The encrypted text
* @param key The encryption key
* @return The clear text or null if decryption fails
*/
public String decrypt(String encrytedText, String key) {
Objects.requireNonNull(encrytedText, "encrytedText can not be null");
Objects.requireNonNull(key, "key can not be null");
CipherParameters cipherParameters = new ParametersWithIV(new KeyParameter(getSizedKey(key).getBytes(Charsets.UTF_8)), new byte[BLOCK_SIZE]);
this.cipher.init(false, cipherParameters);
return new String(cipherData(base64Decoder.decode(encrytedText)), Charsets.UTF_8);
}
/**
* Encrypts a given plain text using the application secret property (application.secret) as key
*
* Encryption is done by using AES and CBC Cipher and a key length of 128/192/256 bit depending on
* the size of the application.secret property length (16/24/32 characters)
*
* @param plainText The plain text to encrypt
* @return The encrypted text or null if encryption fails
*/
public String encrypt(String plainText) {
Objects.requireNonNull(plainText, "plainText can not be null");
return encrypt(plainText, getSizedKey(CONFIG.getApplicationSecret()));
}
/**
* Encrypts a given plain text using the given key
*
* Encryption is done by using AES and CBC Cipher and a key length of 128/192/256 bit depending on
* the size of the application.secret property length (16/24/32 characters)
*
* @param plainText The plain text to encrypt
* @param key The key to use for encryption
* @return The encrypted text or null if encryption fails
*/
public String encrypt(String plainText, String key) {
Objects.requireNonNull(plainText, "plainText can not be null");
Objects.requireNonNull(key, "key can not be null");
CipherParameters cipherParameters = new ParametersWithIV(new KeyParameter(getSizedKey(key).getBytes(Charsets.UTF_8)), new byte[BLOCK_SIZE]);
this.cipher.init(true, cipherParameters);
return new String(base64Encoder.encode(cipherData(plainText.getBytes(Charsets.UTF_8))), Charsets.UTF_8);
}
/**
* Encrypts or decrypts a given byte array of data
*
* @param data The data to encrypt or decrypt
* @return A clear text or encrypted byte array
*/
private byte[] cipherData(byte[] data) {
byte[] result = null;
try {
final byte[] buffer = new byte[this.cipher.getOutputSize(data.length)];
final int processedBytes = this.cipher.processBytes(data, 0, data.length, buffer, 0);
final int finalBytes = this.cipher.doFinal(buffer, processedBytes);
result = new byte[processedBytes + finalBytes];
System.arraycopy(buffer, 0, result, 0, result.length);
} catch (final CryptoException e) {
LOG.error("Failed to encrypt/decrypt", e);
}
return result;
}
/**
* Creates a secret for encrypt or decryption which has a length
* of 16, 24 or 32 characters, corresponding to 128, 192 or 256 Bits
*
* @param secret A given secret to trim
* @return A secret with 16, 24 or 32 characters
*/
private String getSizedKey(String secret) {
Objects.requireNonNull(secret, "secret can not be null");
secret = secret.replaceAll("[^\\x00-\\x7F]", "");
String key = "";
if (secret.length() >= KEYLENGTH_32) {
key = secret.substring(KEYINDEX_START, KEYLENGTH_32);
} else if (secret.length() >= KEYLENGTH_24) {
key = secret.substring(KEYINDEX_START, KEYLENGTH_24);
} else if (secret.length() >= KEYLENGTH_16) {
key = secret.substring(KEYINDEX_START, KEYLENGTH_16);
}
return key;
}
}
|
package io.mangoo.core;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronExpression;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.io.Resources;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.governator.lifecycle.LifecycleManager;
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner;
import io.mangoo.admin.AdminController;
import io.mangoo.annotations.Schedule;
import io.mangoo.cache.Cache;
import io.mangoo.configuration.Config;
import io.mangoo.configuration.ConfigFactory;
import io.mangoo.core.yaml.YamlRoute;
import io.mangoo.core.yaml.YamlRouter;
import io.mangoo.enums.CacheName;
import io.mangoo.enums.Default;
import io.mangoo.enums.Jvm;
import io.mangoo.enums.Key;
import io.mangoo.enums.Mode;
import io.mangoo.enums.Required;
import io.mangoo.enums.RouteType;
import io.mangoo.exceptions.MangooSchedulerException;
import io.mangoo.interfaces.MangooLifecycle;
import io.mangoo.providers.CacheProvider;
import io.mangoo.routing.Route;
import io.mangoo.routing.Router;
import io.mangoo.routing.handlers.DispatcherHandler;
import io.mangoo.routing.handlers.ExceptionHandler;
import io.mangoo.routing.handlers.FallbackHandler;
import io.mangoo.routing.handlers.MetricsHandler;
import io.mangoo.routing.handlers.ServerSentEventHandler;
import io.mangoo.routing.handlers.WebSocketHandler;
import io.mangoo.scheduler.Scheduler;
import io.mangoo.utils.BootstrapUtils;
import io.mangoo.utils.CryptoUtils;
import io.mangoo.utils.SchedulerUtils;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.Undertow.Builder;
import io.undertow.UndertowOptions;
import io.undertow.server.HttpHandler;
import io.undertow.server.RoutingHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.resource.ClassPathResourceManager;
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
/**
* Main class that starts all components of a mangoo I/O application
*
* @author svenkubiak
*
*/
public final class Application {
private static Logger LOG; //NOSONAR
private static final int BUFFERSIZE = 255;
private static volatile String httpHost;
private static volatile String ajpHost;
private static volatile int httpPort;
private static volatile int ajpPort;
private static volatile Undertow undertow;
private static volatile Mode mode;
private static volatile Injector injector;
private static volatile LocalDateTime start = LocalDateTime.now();
private static volatile boolean started;
private static volatile boolean error;
private static volatile PathHandler pathHandler;
private static volatile ResourceHandler resourceHandler;
private Application() {
}
public static void main(String... args) {
start(Mode.PROD);
}
public static void start(Mode mode) {
Objects.requireNonNull(mode, Required.MODE.toString());
if (!started) {
prepareMode(mode);
System.setProperty("log4j.configurationFactory", ConfigFactory.class.getName());
resourceHandler = Handlers.
resource(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + '/'));
prepareLogger();
prepareInjector();
applicationInitialized();
prepareConfig();
prepareRoutes();
createRoutes();
prepareScheduler();
prepareUndertow();
if (!error) {
sanityChecks();
showLogo();
applicationStarted();
Runtime.getRuntime().addShutdownHook(getInstance(Shutdown.class));
started = true;
} else {
System.out.print("Failed to start mangoo I/O application"); //NOSONAR
System.exit(1); //NOSONAR
}
}
}
/**
* Checks if the application is running in dev mode
*
* @return True if the application is running in dev mode, false otherwise
*/
public static boolean inDevMode() {
return Mode.DEV == mode;
}
/**
* Checks if the application is running in prod mode
*
* @return True if the application is running in prod mode, false otherwise
*/
public static boolean inProdMode() {
return Mode.PROD == mode;
}
/**
* Checks if the application is running in test mode
*
* @return True if the application is running in test mode, false otherwise
*/
public static boolean inTestMode() {
return Mode.TEST == mode;
}
/**
* Returns the current mode the application is running in
*
* @return Enum Mode
*/
public static Mode getMode() {
return mode;
}
/**
* Returns the Google Guice Injector
*
* @return Google Guice injector instance
*/
public static Injector getInjector() {
return injector;
}
/**
* @return True if the application started successfully, false otherwise
*/
public static boolean isStarted() {
return started;
}
/**
* @return The LocalDateTime of the application start
*/
public static LocalDateTime getStart() {
return start;
}
/**
* @return The duration of the application uptime
*/
public static Duration getUptime() {
Objects.requireNonNull(start, Required.START.toString());
return Duration.between(start, LocalDateTime.now());
}
/**
* Short form for getting an Goolge Guice injected class by
* calling injector.getInstance(...)
*
* @param clazz The class to retrieve from the injector
* @param <T> JavaDoc requires this (just ignore it)
*
* @return An instance of the requested class
*/
public static <T> T getInstance(Class<T> clazz) {
Objects.requireNonNull(clazz, Required.CLASS.toString());
return injector.getInstance(clazz);
}
/**
* Stops the underlying undertow server
*/
public static void stopUndertow() {
undertow.stop();
}
/**
* Sets the mode the application is running in
*
* @param providedMode A given mode or null
*/
private static void prepareMode(Mode providedMode) {
final String applicationMode = System.getProperty(Jvm.APPLICATION_MODE.toString());
if (StringUtils.isNotBlank(applicationMode)) {
switch (applicationMode.toLowerCase(Locale.ENGLISH)) {
case "dev" : mode = Mode.DEV;
break;
case "test" : mode = Mode.TEST;
break;
default : mode = Mode.PROD;
break;
}
} else {
mode = providedMode;
}
}
/**
* Sets the injector wrapped through netflix Governator
*/
private static void prepareInjector() {
if (!error) {
injector = LifecycleInjector.builder()
.withModules(getModules())
.usingBasePackages(".")
.build()
.createInjector();
try {
injector.getInstance(LifecycleManager.class).start();
} catch (Exception e) {
LOG.error("Failed to start Governator LifecycleManager", e);
error = true;
}
}
}
/**
* Callback to MangooLifecycle applicationInitialized
*/
private static void applicationInitialized() {
if (!error) {
injector.getInstance(MangooLifecycle.class).applicationInitialized();
}
}
/**
* Checks for config failures that pervent the application from starting
*/
private static void prepareConfig() {
if (!error) {
Config config = injector.getInstance(Config.class);
if (!CryptoUtils.isValidSecret(config.getApplicationSecret())) {
LOG.error("Please make sure that your application.yaml has an application.secret property which has at least 32 characters");
error = true;
}
if (!config.isDecrypted()) {
LOG.error("Found encrypted config values in application.yaml but decryption was not successful!");
error = true;
}
}
}
/**
* Do sanity checks on the configuration an warn about it in the log
*/
private static void sanityChecks() {
if (!error) {
Config config = injector.getInstance(Config.class);
Cache cache = injector.getInstance(CacheProvider.class).getCache(CacheName.APPLICATION);
List<String> warnings = new ArrayList<>();
if (!config.isAuthenticationCookieSecure()) {
String warning = "Authentication cookie has secure flag set to false. It is highly recommended to set authentication.cookie.secure to true in an production environment.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getAuthenticationCookieName().equals(Default.AUTHENTICATION_COOKIE_NAME.toString())) {
String warning = "Authentication cookie name has default value. Consider changing authentication.cookie.name to an application specific value.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getAuthenticationCookieSignKey().equals(config.getApplicationSecret())) {
String warning = "Authentication cookie sign key is using application secret. It is highly recommend to set a dedicated value to authentication.cookie.signkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.isAuthenticationCookieEncrypt() && !CryptoUtils.isValidSecret(config.getAuthenticationCookieEncryptionKey())) {
String warning = "Authentication cookie encryption is enabled and encryption key is not a valid secret. A valid secret has to be at least 32 characters.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.isAuthenticationCookieEncrypt() && config.getAuthenticationCookieEncryptionKey().equals(config.getApplicationSecret())) {
String warning = "Authentication cookie encryption is enabled and encryption is using application secret. It is highly recommend to set a dedicated value to authentication.cookie.encryptionkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (!config.isSessionCookieSecure()) {
String warning = "Session cookie has secure flag set to false. It is highly recommended to set session.cookie.secure to true in an production environment.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getSessionCookieName().equals(Default.SESSION_COOKIE_NAME.toString())) {
String warning = "Session cookie name has default value. Consider changing session.cookie.name to an application specific value.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getSessionCookieSignKey().equals(config.getApplicationSecret())) {
String warning = "Session cookie sign key is using application secret. It is highly recommend to set a dedicated value to session.cookie.signkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.isSessionCookieEncrypt() && !CryptoUtils.isValidSecret(config.getSessionCookieEncryptionKey())) {
String warning = "Session cookie encryption is enabled and encryption key is not a valid secret. A valid secret has to be at least 32 characters.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.isSessionCookieEncrypt() && config.getSessionCookieEncryptionKey().equals(config.getApplicationSecret())) {
String warning = "Session cookie encryption is enabled and encryption is using application secret. It is highly recommend to set a dedicated value to session.cookie.encryptionkey.";
warnings.add(warning);
LOG.warn(warning);
}
cache.put(Key.MANGOOIO_WARNINGS.toString(), warnings);
}
}
/**
* Parse routes from routes.yaml file and set up dispatcher
*/
private static void prepareRoutes() {
if (!error) {
Config config = injector.getInstance(Config.class);
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
YamlRouter yamlRouter = null;
try {
yamlRouter = objectMapper.readValue(Resources.getResource(Default.ROUTES_FILE.toString()).openStream(), YamlRouter.class);
} catch (IOException e) {
LOG.error("Failed to load routes.yaml Please make sure that your routes.yaml exists in your application src/main/resources folder", e);
error = true;
}
if (!error && yamlRouter != null) {
for (final YamlRoute yamlRoute : yamlRouter.getRoutes()) {
RouteType routeType = BootstrapUtils.getRouteType(yamlRoute.getMethod());
final Route route = new Route(routeType)
.toUrl(yamlRoute.getUrl().trim())
.withRequest(HttpString.tryFromString(yamlRoute.getMethod()))
.withUsername(yamlRoute.getUsername())
.withPassword(yamlRoute.getPassword())
.withAuthentication(yamlRoute.isAuthentication())
.withTimer(yamlRoute.isTimer())
.withLimit(yamlRoute.getLimit())
.allowBlocking(yamlRoute.isBlocking());
try {
String mapping = yamlRoute.getMapping();
if (StringUtils.isNotBlank(mapping)) {
if (routeType == RouteType.REQUEST) {
int lastIndexOf = mapping.trim().lastIndexOf('.');
String controllerClass = BootstrapUtils.getPackageName(config.getControllerPackage()) + mapping.substring(0, lastIndexOf);
route.withClass(Class.forName(controllerClass));
String methodName = mapping.substring(lastIndexOf + 1);
if (BootstrapUtils.methodExists(methodName, route.getControllerClass())) {
route.withMethod(methodName);
} else {
error = true;
}
} else {
route.withClass(Class.forName(BootstrapUtils.getPackageName(config.getControllerPackage()) + mapping));
}
}
Router.addRoute(route);
} catch (final ClassNotFoundException e) {
LOG.error("Failed to create routes from routes.yaml");
LOG.error("Please verify that your routes.yaml mapping is correct", e);
error = true;
}
}
}
}
}
/**
* Create routes for WebSockets ServerSentEvent and Resource files
*/
private static void createRoutes() {
if (!error) {
pathHandler = new PathHandler(getRoutingHandler());
for (final Route route : Router.getRoutes()) {
if (RouteType.WEBSOCKET == route.getRouteType()) {
pathHandler.addExactPath(route.getUrl(),
Handlers.websocket(injector.getInstance(WebSocketHandler.class)
.withControllerClass(route.getControllerClass())
.withAuthentication(route.isAuthenticationRequired())));
} else if (RouteType.SERVER_SENT_EVENT == route.getRouteType()) {
pathHandler.addExactPath(route.getUrl(),
Handlers.serverSentEvents(injector.getInstance(ServerSentEventHandler.class)
.withAuthentication(route.isAuthenticationRequired())));
} else if (RouteType.RESOURCE_PATH == route.getRouteType()) {
pathHandler.addPrefixPath(route.getUrl(),
new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + route.getUrl())));
}
}
}
}
private static RoutingHandler getRoutingHandler() {
final RoutingHandler routingHandler = Handlers.routing();
routingHandler.setFallbackHandler(Application.getInstance(FallbackHandler.class));
Config config = injector.getInstance(Config.class);
if (config.isAdminEnabled()) {
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin").withRequest(Methods.GET).withClass(AdminController.class).withMethod("index").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/health").withRequest(Methods.GET).withClass(AdminController.class).withMethod("health").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/scheduler").withRequest(Methods.GET).withClass(AdminController.class).withMethod("scheduler").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/logger").withRequest(Methods.GET).withClass(AdminController.class).withMethod("logger").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/logger/ajax").withRequest(Methods.POST).withClass(AdminController.class).withMethod("loggerajax").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/routes").withRequest(Methods.GET).withClass(AdminController.class).withMethod("routes").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/metrics").withRequest(Methods.GET).withClass(AdminController.class).withMethod("metrics").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/metrics/reset").withRequest(Methods.GET).withClass(AdminController.class).withMethod("resetMetrics").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/tools").withRequest(Methods.GET).withClass(AdminController.class).withMethod("tools").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/tools/ajax").withRequest(Methods.POST).withClass(AdminController.class).withMethod("toolsajax").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/scheduler/execute/{name}").withRequest(Methods.GET).withClass(AdminController.class).withMethod("execute").useInternalTemplateEngine());
Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/scheduler/state/{name}").withRequest(Methods.GET).withClass(AdminController.class).withMethod("state").useInternalTemplateEngine());
}
Router.getRoutes().parallelStream().forEach((Route route) -> {
if (RouteType.REQUEST == route.getRouteType()) {
DispatcherHandler dispatcherHandler = Application.getInstance(DispatcherHandler.class).dispatch(route.getControllerClass(), route.getControllerMethod())
.isBlocking(route.isBlockingAllowed())
.withTimer(route.isTimerEnabled())
.withUsername(route.getUsername())
.withPassword(route.getPassword())
.withLimit(route.getLimit());
routingHandler.add(route.getRequestMethod(),route.getUrl(), dispatcherHandler);
} else if (RouteType.RESOURCE_FILE == route.getRouteType()) {
routingHandler.add(Methods.GET, route.getUrl(), resourceHandler);
}
});
return routingHandler;
}
@SuppressWarnings("all")
private static void prepareLogger() {
LOG = LogManager.getLogger(Application.class);
LOG.info(System.getProperty(Key.LOGGER_MESSAGE.toString()));
}
private static void prepareUndertow() {
if (!error) {
Config config = injector.getInstance(Config.class);
HttpHandler httpHandler;
if (config.isMetricsEnabled()) {
httpHandler = MetricsHandler.HANDLER_WRAPPER.wrap(Handlers.exceptionHandler(pathHandler)
.addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class)));
} else {
httpHandler = Handlers.exceptionHandler(pathHandler)
.addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class));
}
Builder builder = Undertow.builder()
.setServerOption(UndertowOptions.MAX_ENTITY_SIZE, config.getUndertowMaxEntitySize())
.setHandler(httpHandler);
httpHost = config.getConnectorHttpHost();
httpPort = config.getConnectorHttpPort();
ajpHost = config.getConnectorAjpHost();
ajpPort = config.getConnectorAjpPort();
boolean hasConnector = false;
if (httpPort > 0 && StringUtils.isNotBlank(httpHost)) {
builder.addHttpListener(httpPort, httpHost);
hasConnector = true;
}
if (ajpPort > 0 && StringUtils.isNotBlank(ajpHost)) {
builder.addAjpListener(ajpPort, ajpHost);
hasConnector = true;
}
if (hasConnector) {
undertow = builder.build();
undertow.start();
} else {
LOG.error("No connector found! Please configure a HTTP and/or AJP connector in your application.yaml");
error = true;
}
}
}
private static void showLogo() {
if (!error) {
final StringBuilder buffer = new StringBuilder(BUFFERSIZE);
buffer.append('\n')
.append(BootstrapUtils.getLogo())
.append("\n\nhttps://mangoo.io | @mangoo_io | ")
.append(BootstrapUtils.getVersion())
.append('\n');
LOG.info(buffer.toString()); //NOSONAR
if (httpPort > 0 && StringUtils.isNotBlank(httpHost)) {
LOG.info("HTTP connector listening @{}:{}", httpHost, httpPort);
}
if (ajpPort > 0 && StringUtils.isNotBlank(ajpHost)) {
LOG.info("AJP connector listening @{}:{}", ajpHost, ajpPort);
}
LOG.info("mangoo I/O application started in {} ms in {} mode. Enjoy.", ChronoUnit.MILLIS.between(start, LocalDateTime.now()), mode.toString());
}
}
private static List<Module> getModules() {
final List<Module> modules = new ArrayList<>();
try {
final Class<?> applicationModule = Class.forName(Default.MODULE_CLASS.toString());
modules.add(new io.mangoo.core.Module());
modules.add((AbstractModule) applicationModule.getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
LOG.error("Failed to load modules. Check that conf/Module.java exists in your application", e);
error = true;
}
return modules;
}
private static void applicationStarted() {
if (!error) {
injector.getInstance(MangooLifecycle.class).applicationStarted();
}
}
private static void prepareScheduler() {
if (!error) {
Config config = injector.getInstance(Config.class);
List<Class<?>> jobs = new ArrayList<>();
new FastClasspathScanner(config.getSchedulerPackage())
.matchClassesWithAnnotation(Schedule.class, jobs::add)
.scan();
if (!jobs.isEmpty() && config.isSchedulerAutostart()) {
final Scheduler mangooScheduler = injector.getInstance(Scheduler.class);
mangooScheduler.initialize();
for (Class<?> clazz : jobs) {
final Schedule schedule = clazz.getDeclaredAnnotation(Schedule.class);
if (CronExpression.isValidExpression(schedule.cron())) {
final JobDetail jobDetail = SchedulerUtils.createJobDetail(clazz.getName(), Default.SCHEDULER_JOB_GROUP.toString(), clazz.asSubclass(Job.class));
final Trigger trigger = SchedulerUtils.createTrigger(clazz.getName() + "-trigger", Default.SCHEDULER_TRIGGER_GROUP.toString(), schedule.description(), schedule.cron());
try {
mangooScheduler.schedule(jobDetail, trigger);
} catch (MangooSchedulerException e) {
LOG.error("Failed to add a job to the scheduler", e);
}
LOG.info("Successfully scheduled job " + clazz.getName() + " with cron " + schedule.cron());
} else {
LOG.error("Invalid or missing cron expression for job: " + clazz.getName());
error = true;
}
}
if (!error) {
try {
mangooScheduler.start();
} catch (MangooSchedulerException e) {
LOG.error("Failed to start the scheduler", e);
error = true;
}
}
}
}
}
}
|
package hudson.maven;
import hudson.CopyOnWrite;
import hudson.Util;
import hudson.Functions;
import hudson.maven.reporters.MavenMailer;
import hudson.model.AbstractProject;
import hudson.model.DependencyGraph;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.Label;
import hudson.model.Node;
import hudson.model.Resource;
import hudson.model.Saveable;
import hudson.tasks.LogRotator;
import hudson.tasks.Publisher;
import hudson.tasks.Maven.MavenInstallation;
import hudson.util.DescribableList;
import org.apache.maven.project.MavenProject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link Job} that builds projects based on Maven2.
*
* @author Kohsuke Kawaguchi
*/
public final class MavenModule extends AbstractMavenProject<MavenModule,MavenBuild> implements Saveable {
private DescribableList<MavenReporter,Descriptor<MavenReporter>> reporters =
new DescribableList<MavenReporter,Descriptor<MavenReporter>>(this);
/**
* Name taken from {@link MavenProject#getName()}.
*/
private String displayName;
/**
* Version number of this module as of fhe last build, taken from {@link MavenProject#getVersion()}.
*
* This field can be null if Hudson loaded old data
* that didn't record this information, so that situation
* needs to be handled gracefully.
*/
private String version;
private transient ModuleName moduleName;
private String relativePath;
/**
* If this module has goals specified by itself.
* Otherwise leave it null to use the default goals specified in the parent.
*/
private String goals;
/**
* List of modules that this module declares direct dependencies on.
*/
@CopyOnWrite
private volatile Set<ModuleDependency> dependencies;
/**
* List of child modules as defined by <module> POM element.
* Used to determine parent/child relationship of modules.
* <p>
* For compatibility reason, this field may be null when loading data from old hudson.
*/
@CopyOnWrite
private volatile List<ModuleName> children;
/**
* Nest level used to display this module in the module list.
* The root module and orphaned module gets 0.
*/
/*package*/ volatile transient int nestLevel;
/*package*/ MavenModule(MavenModuleSet parent, PomInfo pom, int firstBuildNumber) throws IOException {
super(parent, pom.name.toFileSystemName());
reconfigure(pom);
updateNextBuildNumber(firstBuildNumber);
}
/**
* {@link MavenModule} follows the same log rotation schedule as its parent.
*/
@Override
public LogRotator getLogRotator() {
return getParent().getLogRotator();
}
/**
* @deprecated
* Not allowed to configure log rotation per module.
*/
@Override
public void setLogRotator(LogRotator logRotator) {
throw new UnsupportedOperationException();
}
@Override
public boolean supportsLogRotator() {
return false;
}
/**
* Computes the list of {@link MavenModule}s that are 'under' this POM filesystem-wise. The list doens't include
* this module itself.
*
* <p>
* Note that this doesn't necessary has anything to do with the module inheritance structure or parent/child
* relationship of the POM.
*/
public List<MavenModule> getSubsidiaries() {
List<MavenModule> r = new ArrayList<MavenModule>();
for (MavenModule mm : getParent().getModules())
if(mm!=this && mm.getRelativePath().startsWith(getRelativePath()))
r.add(mm);
return r;
}
/**
* Called to update the module with the new POM.
* <p>
* This method is invoked on {@link MavenModule} that has the matching
* {@link ModuleName}.
*/
/*package*/ final void reconfigure(PomInfo pom) {
this.displayName = pom.displayName;
this.version = pom.version;
this.relativePath = pom.relativePath;
this.dependencies = pom.dependencies;
this.children = pom.children;
this.nestLevel = pom.getNestLevel();
disabled = false;
if (pom.mailNotifier != null) {
MavenReporter reporter = getReporters().get(MavenMailer.class);
if (reporter != null) {
MavenMailer mailer = (MavenMailer) reporter;
mailer.dontNotifyEveryUnstableBuild = !pom.mailNotifier.isSendOnFailure();
String recipients = pom.mailNotifier.getConfiguration().getProperty("recipients");
if (recipients != null) {
mailer.recipients = recipients;
}
}
}
}
@Override
protected void doSetName(String name) {
moduleName = ModuleName.fromFileSystemName(name);
super.doSetName(moduleName.toString());
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent,name);
if(reporters==null)
reporters = new DescribableList<MavenReporter, Descriptor<MavenReporter>>(this);
reporters.setOwner(this);
if(dependencies==null)
dependencies = Collections.emptySet();
else {
// Until 1.207, we used to have ModuleName in dependencies. So convert.
Set<ModuleDependency> deps = new HashSet<ModuleDependency>(dependencies.size());
for (Object d : (Set)dependencies) {
if (d instanceof ModuleDependency) {
deps.add((ModuleDependency) d);
} else {
deps.add(new ModuleDependency((ModuleName)d, ModuleDependency.UNKNOWN));
}
}
dependencies = deps;
}
}
/**
* Relative path to this module's root directory
* from the workspace of a {@link MavenModuleSet}.
*
* The path separator is normalized to '/'.
*/
public String getRelativePath() {
return relativePath;
}
/**
* Gets the version number in Maven POM as of the last build.
*
* @return
* This method can return null if Hudson loaded old data
* that didn't record this information, so that situation
* needs to be handled gracefully.
*/
public String getVersion() {
return version;
}
/**
* Gets the list of goals to execute for this module.
*/
public String getGoals() {
if(goals!=null) return goals;
return getParent().getGoals();
}
/**
* Gets the list of goals specified by the user,
* without taking inheritance and POM default goals
* into account.
*
* <p>
* This is only used to present the UI screen, and in
* all the other cases {@link #getGoals()} should be used.
*/
public String getUserConfiguredGoals() {
return goals;
}
public DescribableList<Publisher,Descriptor<Publisher>> getPublishersList() {
// TODO
return new DescribableList<Publisher,Descriptor<Publisher>>(this);
}
@Override
public JDK getJDK() {
// share one setting for the whole module set.
return getParent().getJDK();
}
@Override
protected Class<MavenBuild> getBuildClass() {
return MavenBuild.class;
}
@Override
protected MavenBuild newBuild() throws IOException {
return super.newBuild();
}
public ModuleName getModuleName() {
return moduleName;
}
/**
* Gets groupId+artifactId+version as {@link ModuleDependency}.
*/
public ModuleDependency asDependency() {
return new ModuleDependency(moduleName,Functions.defaulted(version,ModuleDependency.UNKNOWN));
}
@Override
public String getShortUrl() {
return moduleName.toFileSystemName()+'/';
}
@Exported(visibility=2)
@Override
public String getDisplayName() {
return displayName;
}
@Override
public String getPronoun() {
return Messages.MavenModule_Pronoun();
}
@Override
public boolean isNameEditable() {
return false;
}
@Override
public MavenModuleSet getParent() {
return (MavenModuleSet)super.getParent();
}
/**
* Gets all the child modules (that are listed in the <module> element in our POM.)
* <p>
* This method returns null if this information is not recorded. This happens
* for compatibility reason.
*/
public List<MavenModule> getChildren() {
List<ModuleName> l = children; // take a snapshot
if(l==null) return null;
List<MavenModule> modules = new ArrayList<MavenModule>(l.size());
for (ModuleName n : l) {
MavenModule m = getParent().modules.get(n);
if(m!=null)
modules.add(m);
}
return modules;
}
/**
* {@link MavenModule} uses the workspace of the {@link MavenModuleSet},
* so it always needs to be built on the same slave as the parent.
*/
@Override
public Label getAssignedLabel() {
Node n = getParent().getLastBuiltOn();
if(n==null) return null;
return n.getSelfLabel();
}
/**
* Workspace of a {@link MavenModule} is a part of the parent's workspace.
* <p>
* That is, {@Link MavenModuleSet} builds are incompatible with any {@link MavenModule}
* builds, whereas {@link MavenModule} builds are compatible with each other.
*
* @deprecated as of 1.319 in {@link AbstractProject}.
*/
@Override
public Resource getWorkspaceResource() {
return new Resource(getParent().getWorkspaceResource(),getDisplayName()+" workspace");
}
@Override
public boolean isFingerprintConfigured() {
return true;
}
protected void buildDependencyGraph(DependencyGraph graph) {
if(isDisabled() || getParent().ignoreUpstremChanges()) return;
Map<ModuleDependency,MavenModule> modules = new HashMap<ModuleDependency,MavenModule>();
// when we load old data that doesn't record version in dependency, we'd like
// to emulate the old behavior that it tries to identify the upstream by ignoring the version.
// do this by always putting groupId:artifactId:UNKNOWN to the modules list.
for (MavenModule m : Hudson.getInstance().getAllItems(MavenModule.class)) {
if(m.isDisabled()) continue;
modules.put(m.asDependency(),m);
modules.put(m.asDependency().withUnknownVersion(),m);
}
// in case two modules with the same name is defined, modules in the same MavenModuleSet
// takes precedence.
for (MavenModule m : getParent().getModules()) {
if(m.isDisabled()) continue;
modules.put(m.asDependency(),m);
modules.put(m.asDependency().withUnknownVersion(),m);
}
// if the build style is the aggregator build, define dependencies against project,
// not module.
AbstractProject dest = getParent().isAggregatorStyleBuild() ? getParent() : this;
for (ModuleDependency d : dependencies) {
MavenModule src = modules.get(d);
if(src!=null) {
if(src.getParent().isAggregatorStyleBuild())
graph.addDependency(new DependencyGraph.Dependency(src.getParent(),dest));
else
graph.addDependency(new DependencyGraph.Dependency(src,dest));
}
}
}
@Override
protected void addTransientActionsFromBuild(MavenBuild build, Set<Class> added) {
if(build==null) return;
List<MavenReporter> list = build.projectActionReporters;
if(list==null) return;
for (MavenReporter step : list) {
if(!added.add(step.getClass())) continue; // already added
try {
transientActions.addAll(step.getProjectActions(this));
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to getProjectAction from " + step
+ ". Report issue to plugin developers.", e);
}
}
}
public MavenInstallation inferMavenInstallation() {
return getParent().inferMavenInstallation();
}
/**
* List of active {@link MavenReporter}s configured for this module.
*/
public DescribableList<MavenReporter, Descriptor<MavenReporter>> getReporters() {
return reporters;
}
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req, rsp);
reporters.rebuild(req, req.getSubmittedForm(),MavenReporters.getConfigurableList());
goals = Util.fixEmpty(req.getParameter("goals").trim());
// dependency setting might have been changed by the user, so rebuild.
Hudson.getInstance().rebuildDependencyGraph();
}
@Override
protected void performDelete() throws IOException, InterruptedException {
super.performDelete();
getParent().onModuleDeleted(this);
}
/**
* Creates a list of {@link MavenReporter}s to be used for a build of this project.
*/
protected final List<MavenReporter> createReporters() {
List<MavenReporter> reporterList = new ArrayList<MavenReporter>();
getReporters().addAllTo(reporterList);
getParent().getReporters().addAllTo(reporterList);
for (MavenReporterDescriptor d : MavenReporterDescriptor.all()) {
if(getReporters().contains(d))
continue; // already configured
MavenReporter auto = d.newAutoInstance(this);
if(auto!=null)
reporterList.add(auto);
}
return reporterList;
}
private static final Logger LOGGER = Logger.getLogger(MavenModule.class.getName());
}
|
package com.centurylink.mdw.canvas;
import com.centurylink.mdw.draw.Impl;
import org.json.JSONObject;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
public class Implementors extends LinkedHashMap<String, Impl> {
public Implementors() {
loadImplemetors(assetLoc);
}
private void loadImplemetors(File assetLoc) {
for (File file : assetLoc.listFiles()) {
if (file.isDirectory()) {
loadImplemetors(file);
}
else if (file.exists()) {
try {
if (file.getName().endsWith("impl")) {
add(new Impl(file.getPath(), new JSONObject(new String(Files.readAllBytes(file.toPath())))));
}
else if (file.getName().endsWith(".java")) {
// TODO annotation-based implementors
}
else if (file.getName().endsWith(".kt")) {
// TODO annotation-based implementors
}
}
catch (Exception e) {
System.out.println("Problem loading implementor " + file + ": " + e);
}
}
}
}
public void add(Impl impl) {
String iconAsset = impl.getIconName();
if (iconAsset != null && !iconAsset.startsWith("shape:")) {
String iconPkg = Impl.BASE_PKG;
int slash = iconAsset.lastIndexOf('/');
if (slash > 0) {
iconPkg = iconAsset.substring(0, slash);
iconAsset = iconAsset.substring(slash + 1);
}
else {
String implClass = impl.getImplementorClassName();
String pkg = implClass.substring(0, implClass.lastIndexOf('.'));
if (new File(assetLoc + "/" + pkg.replace('.', '/') + "/" + iconAsset).isFile())
iconPkg = pkg;
}
impl.setIcon(getIcon(assetLoc + "/" + iconPkg.replace('.', '/') + "/" + iconAsset));
}
put(impl.getImplementorClassName(), impl);
}
public static File assetLoc;
private ImageIcon getIcon(String filePath) {
try {
File imgFile = new File(filePath);
return new ImageIcon(Files.readAllBytes(Paths.get(imgFile.getPath())));
}
catch (IOException e) {
System.out.println("Unable to load icon " + filePath + ": " + e);
}
return null;
}
}
|
package florian_haas.lucas.util;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.function.Consumer;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.validation.*;
import org.apache.shiro.ShiroException;
import org.primefaces.model.*;
public class WebUtils {
public static final String DEFAULT_MESSAGE_COMPONENT_ID = "defaultMessage";
public static final String GROWL_MESSAGE_COMPONENT_ID = "growlMessage";
public static final String STICKY_GROWL_MESSAGE_COMPONENT_ID = "stickyGrowlMessage";
public static void addDefaultInformationMessage(String message) {
addInformationMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedInformationMessage(String message, Object... params) {
addTranslatedInformationMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addDefaultWarningMessage(String message) {
addWarningMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedWarningMessage(String message, Object... params) {
addTranslatedWarningMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addDefaultErrorMessage(String message) {
addErrorMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedErrorMessage(String message, Object... params) {
addTranslatedErrorMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addDefaultFatalMessage(String message) {
addFatalMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedFatalMessage(String message, Object... params) {
addTranslatedFatalMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlInformationMessage(String message) {
addInformationMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedInformationMessage(String message, Object... params) {
addTranslatedInformationMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlWarningMessage(String message) {
addWarningMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedWarningMessage(String message, Object... params) {
addTranslatedWarningMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlErrorMessage(String message) {
addErrorMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedErrorMessage(String message, Object... params) {
addTranslatedErrorMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlFatalMessage(String message) {
addFatalMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedFatalMessage(String message, Object... params) {
addTranslatedFatalMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlInformationMessage(String message) {
addInformationMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedInformationMessage(String message, Object... params) {
addTranslatedInformationMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlWarningMessage(String message) {
addWarningMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedWarningMessage(String message, Object... params) {
addTranslatedWarningMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlErrorMessage(String message) {
addErrorMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedErrorMessage(String message, Object... params) {
addTranslatedErrorMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlFatalMessage(String message) {
addFatalMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedFatalMessage(String message, Object... params) {
addTranslatedFatalMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addInformationMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_INFO, message, clientComponent);
}
public static void addTranslatedInformationMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_INFO, message, clientComponent, params);
}
public static void addWarningMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_WARN, message, clientComponent);
}
public static void addTranslatedWarningMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_WARN, message, clientComponent, params);
}
public static void addErrorMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_ERROR, message, clientComponent);
}
public static void addTranslatedErrorMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_ERROR, message, clientComponent, params);
}
public static void addFatalMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_FATAL, message, clientComponent);
}
public static void addTranslatedFatalMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_FATAL, message, clientComponent, params);
}
private static void addTranslatedMessage(FacesMessage.Severity severity, String key, String clientComponent, Object... params) {
addMessage(severity, getTranslatedMessage(key, params), clientComponent);
}
private static void addMessage(FacesMessage.Severity severity, String message, String clientComponent) {
String titlePrefix = severity == FacesMessage.SEVERITY_WARN ? "warn"
: severity == FacesMessage.SEVERITY_ERROR ? "error" : severity == FacesMessage.SEVERITY_FATAL ? "fatal" : "info";
FacesContext.getCurrentInstance().addMessage(clientComponent,
new FacesMessage(severity, getTranslatedMessage("lucas.application.message." + titlePrefix), message));
}
public static String getTranslatedMessage(String key, Object... params) {
String message = getTranslatedMessage(key);
for (int i = 0; i < params.length; i++) {
if (params[i] != null) message = message.replaceAll("\\?" + i, params[i].toString());
}
return message;
}
public static String getTranslatedMessage(String key) {
return FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{msg['" + key + "']}",
String.class);
}
public static boolean executeTask(FailableTask task, String successMessageKey, String warnMessageKey, String failMessageKey,
Object... argParams) {
return executeTask(task, successMessageKey, warnMessageKey, failMessageKey, WebUtils::addDefaultInformationMessage,
WebUtils::addDefaultWarningMessage, WebUtils::addDefaultErrorMessage, WebUtils::addDefaultFatalMessage, argParams);
}
public static boolean executeTask(FailableTask task, String successMessageKey, String warnMessageKey, String failMessageKey,
Consumer<String> informationMessageConsumer, Consumer<String> warnMessageConsumer, Consumer<String> errorMessageConsumer,
Consumer<String> fatalMessageConsumer, Object... argParams) {
boolean success = false;
List<Object> paramsList = new ArrayList<>();
paramsList.addAll(Arrays.asList(argParams));
Object[] params = paramsList.toArray();
try {
success = task.executeTask(paramsList);
params = paramsList.toArray();
if (success && successMessageKey != null) {
informationMessageConsumer.accept(WebUtils.getTranslatedMessage(successMessageKey, params));
} else if (warnMessageKey != null) {
warnMessageConsumer.accept(WebUtils.getTranslatedMessage(warnMessageKey, params));
}
}
catch (ConstraintViolationException e) {
for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
errorMessageConsumer
.accept(getTranslatedMessage(failMessageKey, params) + violation.getPropertyPath() + " " + violation.getMessage());
}
}
catch (ShiroException e2) {
errorMessageConsumer
.accept(getTranslatedMessage(failMessageKey, params) + getTranslatedMessage("lucas.application.message.accessDenied"));
}
catch (Exception e3) {
fatalMessageConsumer.accept(getTranslatedMessage(failMessageKey, params) + e3.getLocalizedMessage());
}
return success;
}
public static final String JPEG_MIME = "image/jpeg";
public static final String JPEG_TYPE = "JPEG";
public static final String SVG_MIME = "image/svg+xml";
public static StreamedContent getJPEGImage(InputStream data) {
return getDataAsStreamedContent(data, JPEG_MIME);
}
public static StreamedContent getJPEGImage(byte[] data) {
return getDataAsStreamedContent(data, JPEG_MIME);
}
public static StreamedContent getSVGImage(byte[] data) {
return getDataAsStreamedContent(data, SVG_MIME);
}
public static StreamedContent getSVGImage(InputStream data) {
return getDataAsStreamedContent(data, SVG_MIME);
}
public static StreamedContent getDataAsStreamedContent(byte[] data, String mime) {
return getDataAsStreamedContent(data != null ? new ByteArrayInputStream(data) : null, mime);
}
public static StreamedContent getDataAsStreamedContent(InputStream data, String mime) {
if (data != null) return new DefaultStreamedContent(data, mime);
return null;
}
public static BufferedImage getBufferedImageFromBytes(byte[] data) throws Exception {
BufferedImage ret = null;
ByteArrayInputStream in = new ByteArrayInputStream(data);
ret = ImageIO.read(new ByteArrayInputStream(data));
in.close();
return ret;
}
public static byte[] convertBufferedImageToBytes(BufferedImage image, String type) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, type, out);
out.close();
return out.toByteArray();
}
}
|
package com.baidu.unbiz.multiengine.codec;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec;
import com.baidu.unbiz.multiengine.dto.Signal;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
public class CodecTest {
@Test
public void testProtostuffCodec(){
MsgCodec codec = new ProtostuffCodec();
List<DeviceViewItem> dataList = mockList();
Signal params = new Signal(dataList);
byte[] bytes = codec.encode(params);
System.out.println(bytes);
Signal data = codec.decode(Signal.class, bytes);
System.out.println(data);
}
private List<DeviceViewItem> mockList() {
List<DeviceViewItem> list = new ArrayList<DeviceViewItem>();
list.add(new DeviceViewItem());
list.add(new DeviceViewItem());
return list;
}
}
|
package com.conveyal.analyst.server;
import com.conveyal.analyst.server.utils.QueryResults;
import com.google.common.io.Files;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Polygon;
import junit.framework.TestCase;
import models.Shapefile;
import org.junit.Test;
import org.mapdb.Fun;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Test that aggregation works as expected.
*/
public class AggregationTest extends TestCase {
static {
// create a temporary data directory so that the datastores aren't pointing off into space.
AnalystMain.config.setProperty("application.data", Files.createTempDir().getAbsolutePath());
}
private static final GeometryFactory geometryFactory = new GeometryFactory();
/**
* Get a grid shapefile, with the given origin, resolution and size. The IntFunction will receive a single number that is
* the feature position in the file (rows first) and should return the attributes for that feature.
*/
private static Shapefile getGrid (double originX, double originY, double resolutionX, double resolutionY, int countX, int countY, IntFunction<Map<String, Object>> attributeProducer) {
List<Polygon> ret = new ArrayList<>();
for (int y = 0; y < countY; y++) {
for (int x = 0; x < countX; x++) {
Coordinate[] coords = new Coordinate[] {
// build the grid cell.
new Coordinate(originX + x * resolutionX, originY + y * resolutionY),
new Coordinate(originX + (x + 1) * resolutionX, originY + y * resolutionY),
new Coordinate(originX + (x + 1) * resolutionX, originY + (y + 1) * resolutionY),
new Coordinate(originX + x * resolutionX, originY + (y + 1) * resolutionY),
new Coordinate(originX + x * resolutionX, originY + y * resolutionY)
};
ret.add(geometryFactory.createPolygon(coords));
}
}
Iterator<Integer> idStream = IntStream.range(0, ret.size()).iterator();
// convert everything to shapefeatures
List<Fun.Tuple2<String, Shapefile.ShapeFeature>> features = ret.stream()
.map(p -> {
int id = idStream.next();
Shapefile.ShapeFeature sf = new Shapefile.ShapeFeature();
sf.geom = p;
// zero pad so they sort in order.
sf.id = "feat" + String.format("%10d", id);
sf.attributes = attributeProducer.apply(id);
return Fun.t2(sf.id, sf);
})
.collect(Collectors.toList());
Shapefile shp = new Shapefile();
// has to have an ID so it can be stored.
shp.id = UUID.randomUUID().toString();
shp.setShapeFeatureStore(features);
// make sure the attribute stats are up to date.
for (Fun.Tuple2<String, Shapefile.ShapeFeature> feature : features) {
for (Map.Entry<String, Object> attr : feature.b.attributes.entrySet()) {
shp.updateAttributeStats(attr.getKey(), attr.getValue());
}
}
return shp;
}
/** Create query results from a shapefile. The function returns the value for a particular feature. */
public QueryResults getQueryResultsForShapefile (Shapefile shp, Function<Shapefile.ShapeFeature, Double> getValue) {
QueryResults qr = new QueryResults();
qr.shapeFileId = shp.id;
qr.minValue = qr.maxPossible = Double.MAX_VALUE;
qr.maxValue = Double.MIN_VALUE;
for (Shapefile.ShapeFeature sf : shp.getShapeFeatureStore().getAll()) {
QueryResults.QueryResultItem queryResultItem = new QueryResults.QueryResultItem();
queryResultItem.feature = sf;
queryResultItem.value = getValue.apply(sf);
qr.items.put(sf.id, queryResultItem);
}
return qr;
}
/** Test that aggregation works correctly when weighting by the same shapefile */
@Test
public void testSameShapefile () {
// 45 degrees latitude; everything is squished in the x dimension by 50%
Shapefile shp = getGrid(0, 45, 2e-6, 1e-6, 100, 100, i -> {
Map<String, Object> map = new HashMap<>();
map.put("value", i % 100);
map.put("weight", 1e6 -i);
return map;
});
// get a shapefile that encompasses part of the grid: in the x dimension, 50.5 cells, and in the y dimension 50.
Shapefile contour = getGrid(0, 45, 2e-6 * 50.5, 1e-6 * 50, 1, 1, HashMap::new);
// use the precomputed value in the shapefile
QueryResults qr = getQueryResultsForShapefile(shp, sf -> sf.getAttribute("value").doubleValue());
QueryResults aggregated = qr.aggregate(contour, shp, "weight");
QueryResults.QueryResultItem aggItem = aggregated.items.values().stream().findFirst().orElse(null);
// Independently verify the calculated values.
// The aggregate shapefile overlaps the first 50.5 features of the first fifty rows.
double expected = 0;
double wsum = 0;
int i = 0;
for (Shapefile.ShapeFeature feature: shp.getShapeFeatureStore().getAll()) {
int x = i++ % 100;
// NB i has already been incremented
if (i > 50 * 100)
// this is the 51st row, no further features are overlapped
break;
if (x < 50) {
// this feature is overlapped completely
expected += feature.getAttribute("weight") * feature.getAttribute("value");
wsum += feature.getAttribute("weight");
}
if (x == 50) {
// this feature is overlapped 50%
expected += feature.getAttribute("weight") * feature.getAttribute("value") / 2D;
wsum += feature.getAttribute("weight") / 2D;
}
}
assertEquals(expected / wsum, aggItem.value, 1e-6);
}
/** Test weighting by a different shapefile */
@Test
public void testDifferentShapefile () {
Shapefile shp = getGrid(0, 45, 2e-6, 1e-6, 2, 1, i -> {
Map<String, Object> ret = new HashMap<>();
ret.put("value", i + 1);
return ret;
});
// three cells half of which overlaps above shapefile.
// So weight for first feature should be (1 / 2 + 2 / 2) = 1.5
// weight for second feature should be (2 / 2 + 3 / 2) = 2.5
// value for first feature = 1
// value for second feature = 2
// weighted value for first feature = 1.5
// weighted value for second feature = 5
// sum of weighted values = 6.5
// sum of weights = 4
// weighted average = 6.5 / 4
Shapefile weights = getGrid(-1e-6, 45, 2e-6, 1e-6, 3, 1, i -> {
Map<String, Object> ret = new HashMap<>();
ret.put("weight", i + 1);
return ret;
});
// more than includes all of above
Shapefile contour = getGrid(-2e-6, 45, 8e-6, 1e-6, 1, 1, i -> {
Map<String, Object> ret = new HashMap<>();
ret.put("value", 1);
return ret;
});
QueryResults qr = getQueryResultsForShapefile(shp, sf -> sf.getAttribute("value").doubleValue());
QueryResults aggregated = qr.aggregate(contour, weights, "weight");
QueryResults.QueryResultItem item = aggregated.items.values().stream().findFirst().orElse(null);
// see comment above for why the correct answer is 6.5 / 4.
assertEquals(6.5 / 4, item.value, 1e-6);
}
}
|
package com.slugterra.gui;
import org.lwjgl.opengl.GL11;
import com.slugterra.capabilities.ISlugInv;
import com.slugterra.capabilities.SlugInventoryProvider;
import com.slugterra.lib.Strings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class GuiSlugBeltOverlay extends Gui{
private Minecraft mc;
public static int selslot;
protected RenderItem itemRenderer;
public GuiSlugBeltOverlay(Minecraft mc){
super();
this.mc = mc;
itemRenderer = mc.getRenderItem();
}
private ISlugInv props;
@SubscribeEvent(priority = EventPriority.NORMAL)
public void onRenderExperienceBar(RenderGameOverlayEvent event){
if(event.isCancelable() || event.getType() != ElementType.HOTBAR){
return;
}
ScaledResolution scaledresolution = new ScaledResolution(this.mc);
int k = scaledresolution.getScaledWidth();
int l = scaledresolution.getScaledHeight();
GL11.glDisable(GL11.GL_LIGHTING);
//get player properties
if(props == null){
props = ((EntityPlayer)this.mc.player).getCapability(SlugInventoryProvider.INV_CAP, null);
this.selslot = props.getSlot();
}
//rendering bar
this.mc.renderEngine.bindTexture(new ResourceLocation(Strings.MODID + ":textures/gui/slughotbar2.png"));
this.drawTexturedModalRect(2, l/2-90, 0, 0, 24, 133);
for (int i1 = 0; i1 < 6; ++i1)
{
int k1 = l / 2 - 86 + i1 * 22;//change last value to push up or down
this.renderInventorySlot(i1, 6, k1);
}
GL11.glEnable(GL11.GL_BLEND);
//rendering square thing over hotbar
this.mc.renderEngine.bindTexture(new ResourceLocation(Strings.MODID + ":textures/gui/hotbarsquare.png"));
this.drawTexturedModalRect(2, (22 * selslot) + (l/2-92)+1, 0, 0, 26, 26);
}
private void renderInventorySlot(int p_73832_1_, int p_73832_2_, int p_73832_3_)
{
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_BLEND);
ItemStack itemstack = props.getInventory().getStackInSlot(p_73832_1_);
if (itemstack != null)
{
float f1 = (float)itemstack.getAnimationsToGo();
if (f1 > 0.0F)
{
GL11.glPushMatrix();
float f2 = 1.0F + f1 / 5.0F;
GL11.glTranslatef((float)(p_73832_2_ + 8), (float)(p_73832_3_ + 12), 0.0F);
GL11.glScalef(1.0F / f2, (f2 + 1.0F) / 2.0F, 1.0F);
GL11.glTranslatef((float)(-(p_73832_2_ + 8)), (float)(-(p_73832_3_ + 12)), 0.0F);
}
itemRenderer.renderItemAndEffectIntoGUI(itemstack, p_73832_2_, p_73832_3_);
if (f1 > 0.0F)
{
GL11.glPopMatrix();
}
itemRenderer.renderItemOverlayIntoGUI(this.mc.fontRendererObj, itemstack, p_73832_2_, p_73832_3_, null);
}
}
}
|
package com.github.dreamhead.moco;
import com.github.dreamhead.moco.action.MocoAsyncAction;
import com.github.dreamhead.moco.action.MocoGetRequestAction;
import com.github.dreamhead.moco.action.MocoPostRequestAction;
import com.github.dreamhead.moco.config.MocoContextConfig;
import com.github.dreamhead.moco.config.MocoFileRootConfig;
import com.github.dreamhead.moco.config.MocoRequestConfig;
import com.github.dreamhead.moco.config.MocoResponseConfig;
import com.github.dreamhead.moco.extractor.CookieRequestExtractor;
import com.github.dreamhead.moco.extractor.FormRequestExtractor;
import com.github.dreamhead.moco.extractor.HeaderRequestExtractor;
import com.github.dreamhead.moco.extractor.JsonPathRequestExtractor;
import com.github.dreamhead.moco.extractor.ParamRequestExtractor;
import com.github.dreamhead.moco.extractor.PlainExtractor;
import com.github.dreamhead.moco.extractor.XPathRequestExtractor;
import com.github.dreamhead.moco.handler.AndResponseHandler;
import com.github.dreamhead.moco.handler.HeaderResponseHandler;
import com.github.dreamhead.moco.handler.ProcedureResponseHandler;
import com.github.dreamhead.moco.handler.ProxyBatchResponseHandler;
import com.github.dreamhead.moco.handler.ProxyResponseHandler;
import com.github.dreamhead.moco.handler.StatusCodeResponseHandler;
import com.github.dreamhead.moco.handler.failover.Failover;
import com.github.dreamhead.moco.handler.failover.FailoverStrategy;
import com.github.dreamhead.moco.handler.proxy.ProxyConfig;
import com.github.dreamhead.moco.internal.ActualHttpServer;
import com.github.dreamhead.moco.internal.ActualSocketServer;
import com.github.dreamhead.moco.internal.ApiUtils;
import com.github.dreamhead.moco.matcher.AndRequestMatcher;
import com.github.dreamhead.moco.matcher.EqRequestMatcher;
import com.github.dreamhead.moco.matcher.ExistMatcher;
import com.github.dreamhead.moco.matcher.NotRequestMatcher;
import com.github.dreamhead.moco.matcher.OrRequestMatcher;
import com.github.dreamhead.moco.matcher.XmlRequestMatcher;
import com.github.dreamhead.moco.monitor.StdLogWriter;
import com.github.dreamhead.moco.procedure.LatencyProcedure;
import com.github.dreamhead.moco.resource.ContentResource;
import com.github.dreamhead.moco.resource.Resource;
import com.github.dreamhead.moco.resource.reader.ExtractorVariable;
import com.github.dreamhead.moco.util.Jsons;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.HttpHeaders;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import static com.github.dreamhead.moco.extractor.Extractors.extractor;
import static com.github.dreamhead.moco.handler.ResponseHandlers.responseHandler;
import static com.github.dreamhead.moco.handler.SequenceHandler.newSeq;
import static com.github.dreamhead.moco.internal.ApiUtils.resourceToResourceHandler;
import static com.github.dreamhead.moco.internal.ApiUtils.textToResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.classpathFileResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.cookieResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.fileResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.jsonResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.methodResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.templateResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.textResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.uriResource;
import static com.github.dreamhead.moco.resource.ResourceFactory.versionResource;
import static com.github.dreamhead.moco.util.Preconditions.checkNotNullOrEmpty;
import static com.github.dreamhead.moco.util.URLs.toUrlFunction;
import static com.google.common.base.Optional.of;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.net.HttpHeaders.SET_COOKIE;
import static java.lang.String.format;
public final class Moco {
public static HttpServer httpServer(final int port, final MocoConfig... configs) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualHttpServer.createQuietServer(of(port), configs);
}
public static HttpServer httpServer(final int port, final MocoMonitor monitor, final MocoConfig... configs) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualHttpServer.createHttpServerWithMonitor(of(port),
checkNotNull(monitor, "Monitor should not be null"),
checkNotNull(configs, "Configuration should not be null"));
}
public static HttpServer httpServer(final int port, final MocoMonitor monitor, final MocoMonitor monitor2,
final MocoMonitor... monitors) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualHttpServer.createHttpServerWithMonitor(of(port),
ApiUtils.mergeMonitor(checkNotNull(monitor, "Monitor should not be null"),
checkNotNull(monitor2, "Monitor should not be null"),
checkNotNull(monitors, "Monitors should not be null")));
}
public static HttpServer httpServer(final MocoConfig... configs) {
return ActualHttpServer.createQuietServer(Optional.<Integer>absent(),
checkNotNull(configs, "Configuration should not be null"));
}
public static HttpServer httpServer(final MocoMonitor monitor, final MocoConfig... configs) {
return ActualHttpServer.createHttpServerWithMonitor(Optional.<Integer>absent(), checkNotNull(monitor, "Monitor should not be null"), configs);
}
public static HttpsServer httpsServer(final int port, final HttpsCertificate certificate, final MocoConfig... configs) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualHttpServer.createHttpsQuietServer(of(port), checkNotNull(certificate, "Certificate should not be null"), configs);
}
public static HttpsServer httpsServer(final int port, final HttpsCertificate certificate, final MocoMonitor monitor, final MocoConfig... configs) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualHttpServer.createHttpsServerWithMonitor(of(port),
checkNotNull(certificate, "Certificate should not be null"),
checkNotNull(monitor, "Monitor should not be null"), configs);
}
public static HttpsServer httpsServer(final HttpsCertificate certificate, final MocoConfig... configs) {
return ActualHttpServer.createHttpsQuietServer(Optional.<Integer>absent(), checkNotNull(certificate, "Certificate should not be null"), configs);
}
public static HttpsServer httpsServer(final HttpsCertificate certificate, final MocoMonitor monitor, final MocoConfig... configs) {
return ActualHttpServer.createHttpsServerWithMonitor(Optional.<Integer>absent(),
checkNotNull(certificate, "Certificate should not be null"),
checkNotNull(monitor, "Monitor should not be null"), configs);
}
public static HttpServer httpsServer(final int port, final HttpsCertificate certificate, final MocoMonitor monitor, final MocoMonitor monitor2, final MocoMonitor... monitors) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualHttpServer.createHttpsServerWithMonitor(of(port), checkNotNull(certificate, "Certificate should not be null"),
ApiUtils.mergeMonitor(checkNotNull(monitor, "Monitor should not be null"),
checkNotNull(monitor2, "Monitor should not be null"), monitors));
}
public static SocketServer socketServer() {
return ActualSocketServer.createQuietServer(Optional.<Integer>absent());
}
public static SocketServer socketServer(final int port) {
return ActualSocketServer.createQuietServer(of(port));
}
public static SocketServer socketServer(final int port, final MocoMonitor monitor) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualSocketServer.createServerWithMonitor(of(port),
checkNotNull(monitor, "Monitor should not be null"));
}
public static SocketServer socketServer(final int port, final MocoMonitor monitor, final MocoMonitor monitor2, final MocoMonitor... monitors) {
checkArgument(port > 0, "Port must be greater than zero");
return ActualSocketServer.createServerWithMonitor(of(port),
ApiUtils.mergeMonitor(checkNotNull(monitor, "Monitor should not be null"),
checkNotNull(monitor2, "Monitor should not be null"), monitors));
}
public static MocoConfig context(final String context) {
return new MocoContextConfig(checkNotNullOrEmpty(context, "Context should not be null"));
}
public static MocoConfig request(final RequestMatcher matcher) {
return new MocoRequestConfig(checkNotNull(matcher, "Request matcher should not be null"));
}
public static MocoConfig response(final ResponseHandler handler) {
return new MocoResponseConfig(checkNotNull(handler, "Response handler should not be null"));
}
public static MocoConfig fileRoot(final String fileRoot) {
return new MocoFileRootConfig(checkNotNullOrEmpty(fileRoot, "File root should not be null"));
}
public static MocoMonitor log() {
return ApiUtils.log(new StdLogWriter());
}
public static MocoMonitor log(final String filename) {
return ApiUtils.log(ApiUtils.fileLogWriter(checkNotNullOrEmpty(filename, "Filename should not be null or empty"), Optional.<Charset>absent()));
}
public static MocoMonitor log(final String filename, final Charset charset) {
return ApiUtils.log(ApiUtils.fileLogWriter(checkNotNullOrEmpty(filename, "Filename should not be null or empty"), of(checkNotNull(charset, "Charset should not be null"))));
}
public static RequestMatcher by(final String content) {
return by(text(checkNotNullOrEmpty(content, "Content should not be null")));
}
public static RequestMatcher by(final Resource resource) {
checkNotNull(resource, "Resource should not be null");
return ApiUtils.by(extractor(resource.id()), resource);
}
public static <T> RequestMatcher eq(final RequestExtractor<T> extractor, final String expected) {
return eq(checkNotNull(extractor, "Extractor should not be null"), text(checkNotNull(expected, "Expected content should not be null")));
}
public static <T> RequestMatcher eq(final RequestExtractor<T> extractor, final Resource expected) {
return new EqRequestMatcher<>(checkNotNull(extractor, "Extractor should not be null"), checkNotNull(expected, "Expected content should not be null"));
}
public static RequestMatcher match(final Resource resource) {
return ApiUtils.match(extractor(resource.id()), checkNotNull(resource, "Resource should not be null"));
}
public static <T> RequestMatcher match(final RequestExtractor<T> extractor, final String expected) {
return ApiUtils.match(checkNotNull(extractor, "Extractor should not be null"), text(checkNotNullOrEmpty(expected, "Expected content should not be null")));
}
public static <T> RequestMatcher exist(final RequestExtractor<T> extractor) {
return new ExistMatcher<T>(checkNotNull(extractor, "Extractor should not be null"));
}
public static RequestMatcher startsWith(final Resource resource) {
return ApiUtils.startsWith(extractor(resource.id()), checkNotNull(resource, "Resource should not be null"));
}
public static <T> RequestMatcher startsWith(final RequestExtractor<T> extractor, final String expected) {
return ApiUtils.startsWith(checkNotNull(extractor, "Extractor should not be null"),
text(checkNotNullOrEmpty(expected, "Expected resource should not be null")));
}
public static RequestMatcher endsWith(final Resource resource) {
return ApiUtils.endsWith(extractor(resource.id()), checkNotNull(resource, "Resource should not be null"));
}
public static <T> RequestMatcher endsWith(final RequestExtractor<T> extractor, final String expected) {
return ApiUtils.endsWith(checkNotNull(extractor, "Extractor should not be null"),
text(checkNotNullOrEmpty(expected, "Expected resource should not be null")));
}
public static RequestMatcher contain(final Resource resource) {
return ApiUtils.contain(extractor(resource.id()), checkNotNull(resource, "Resource should not be null"));
}
public static <T> RequestMatcher contain(final RequestExtractor<T> extractor, final String expected) {
return ApiUtils.contain(checkNotNull(extractor, "Extractor should not be null"),
text(checkNotNullOrEmpty(expected, "Expected resource should not be null")));
}
public static RequestMatcher and(final RequestMatcher... matchers) {
return new AndRequestMatcher(copyOf(checkNotNull(matchers, "Matcher should not be null")));
}
public static RequestMatcher or(final RequestMatcher... matchers) {
return new OrRequestMatcher(copyOf(checkNotNull(matchers, "Matcher should not be null")));
}
public static RequestMatcher not(final RequestMatcher matcher) {
return new NotRequestMatcher(checkNotNull(matcher, "Expected matcher should not be null"));
}
public static ContentResource text(final String text) {
return textResource(checkNotNull(text, "Text should not be null"));
}
public static ResponseHandler with(final String text) {
return with(text(checkNotNullOrEmpty(text, "Text should not be null")));
}
public static ResponseHandler with(final Resource resource) {
return responseHandler(checkNotNull(resource, "Resource should not be null"));
}
public static ResponseHandler with(final MocoProcedure procedure) {
return new ProcedureResponseHandler(checkNotNull(procedure, "Procedure should not be null"));
}
public static Resource uri(final String uri) {
return uriResource(checkNotNullOrEmpty(uri, "URI should not be null"));
}
public static Resource method(final String httpMethod) {
return methodResource(checkNotNullOrEmpty(httpMethod, "HTTP method should not be null"));
}
public static Resource method(final HttpMethod httpMethod) {
return methodResource(checkNotNull(httpMethod, "HTTP method should not be null").toString());
}
public static RequestExtractor<String[]> header(final String header) {
return new HeaderRequestExtractor(checkNotNullOrEmpty(header, "Header name should not be null"));
}
public static ResponseHandler header(final String name, final String value) {
return header(checkNotNullOrEmpty(name, "Header name should not be null"), text(checkNotNullOrEmpty(value, "Header value should not be null")));
}
public static ResponseHandler header(final String name, final Resource value) {
return new HeaderResponseHandler(checkNotNullOrEmpty(name, "Header name should not be null"),
checkNotNull(value, "Header value should not be null"));
}
public static RequestExtractor<String> cookie(final String key) {
return new CookieRequestExtractor(checkNotNullOrEmpty(key, "Cookie key should not be null"));
}
public static ResponseHandler cookie(final String key, final String value, final CookieAttribute... attributes) {
return cookie(checkNotNullOrEmpty(key, "Cookie key should not be null"),
text(checkNotNullOrEmpty(value, "Cookie value should not be null")),
checkNotNull(attributes, "Cookie options should not be null"));
}
public static ResponseHandler cookie(final String key, final Resource resource, final CookieAttribute... attributes) {
return header(SET_COOKIE, cookieResource(
checkNotNullOrEmpty(key, "Cookie key should not be null"),
checkNotNull(resource, "Cookie value should not be null"),
checkNotNull(attributes, "Cookie options should not be null")));
}
public static RequestExtractor<String> form(final String key) {
return new FormRequestExtractor(checkNotNullOrEmpty(key, "Form key should not be null"));
}
public static LatencyProcedure latency(final long duration, final TimeUnit unit) {
checkArgument(duration > 0, "Latency must be greater than zero");
return new LatencyProcedure(duration, checkNotNull(unit, "Time unit should not be null"));
}
public static RequestExtractor<String[]> query(final String param) {
return new ParamRequestExtractor(checkNotNullOrEmpty(param, "Query parameter should not be null"));
}
public static XPathRequestExtractor xpath(final String xpath) {
return new XPathRequestExtractor(checkNotNullOrEmpty(xpath, "XPath should not be null"));
}
public static RequestMatcher xml(final String resource) {
return xml(text(checkNotNullOrEmpty(resource, "Resource should not be null")));
}
public static RequestMatcher xml(final Resource resource) {
checkNotNull(resource, "Resource should not be null");
return new XmlRequestMatcher(resource);
}
public static ContentResource json(final String jsonText) {
return json(text(checkNotNullOrEmpty(jsonText, "Json should not be null")));
}
public static ContentResource json(final Resource resource) {
return jsonResource(checkNotNull(resource, "Json should not be null"));
}
public static ContentResource json(final Object pojo) {
return jsonResource(checkNotNull(pojo, "Json object should not be null"));
}
public static JsonPathRequestExtractor jsonPath(final String jsonPath) {
return new JsonPathRequestExtractor(checkNotNullOrEmpty(jsonPath, "JsonPath should not be null"));
}
public static ResponseHandler seq(final String... contents) {
checkArgument(contents.length > 0, "Sequence contents should not be null");
return newSeq(FluentIterable.from(copyOf(contents)).transform(textToResource()));
}
public static ResponseHandler seq(final Resource... contents) {
checkArgument(contents.length > 0, "Sequence contents should not be null");
return newSeq(FluentIterable.from(copyOf(contents)).transform(resourceToResourceHandler()));
}
public static ResponseHandler seq(final ResponseHandler... handlers) {
checkArgument(handlers.length > 0, "Sequence contents should not be null");
return newSeq(copyOf(handlers));
}
public static ContentResource file(final String filename) {
return file(text(checkNotNullOrEmpty(filename, "Filename should not be null")));
}
public static ContentResource file(final Resource filename) {
return file(checkNotNull(filename, "Filename should not be null"), Optional.<Charset>absent());
}
public static ContentResource file(final String filename, final Charset charset) {
return file(text(checkNotNullOrEmpty(filename, "Filename should not be null")), of(checkNotNull(charset, "Charset should not be null")));
}
public static ContentResource file(final Resource filename, final Charset charset) {
return file(checkNotNull(filename, "Filename should not be null"), of(checkNotNull(charset, "Charset should not be null")));
}
private static ContentResource file(final Resource filename, final Optional<Charset> charset) {
return fileResource(checkNotNull(filename, "Filename should not be null"), charset, Optional.<MocoConfig>absent());
}
public static ContentResource pathResource(final String filename) {
return pathResource(text(checkNotNullOrEmpty(filename, "Filename should not be null")));
}
public static ContentResource pathResource(final Resource filename) {
return pathResource(checkNotNull(filename, "Filename should not be null"), Optional.<Charset>absent());
}
public static ContentResource pathResource(final String filename, final Charset charset) {
return pathResource(text(checkNotNullOrEmpty(filename, "Filename should not be null")), of(checkNotNull(charset, "Charset should not be null")));
}
public static ContentResource pathResource(final Resource filename, final Charset charset) {
return pathResource(checkNotNull(filename, "Filename should not be null"), of(checkNotNull(charset, "Charset should not be null")));
}
private static ContentResource pathResource(final Resource filename, final Optional<Charset> charset) {
return classpathFileResource(checkNotNull(filename, "Filename should not be null"), charset);
}
public static Resource version(final String version) {
return version(HttpProtocolVersion.versionOf(checkNotNullOrEmpty(version, "Version should not be null")));
}
public static Resource version(final Resource resource) {
return versionResource(checkNotNull(resource, "Version should not be null"));
}
public static Resource version(final HttpProtocolVersion version) {
return versionResource(checkNotNull(version, "Version should not be null"));
}
public static ResponseHandler status(final int code) {
checkArgument(code > 0, "Status code must be greater than zero");
return new StatusCodeResponseHandler(code);
}
public static ResponseHandler proxy(final String url) {
return proxy(checkNotNullOrEmpty(url, "URL should not be null"), Failover.DEFAULT_FAILOVER);
}
public static ResponseHandler proxy(final ContentResource url) {
return proxy(checkNotNull(url, "URL should not be null"), Failover.DEFAULT_FAILOVER);
}
public static ResponseHandler proxy(final String url, final Failover failover) {
return proxy(text(checkNotNullOrEmpty(url, "URL should not be null")),
checkNotNull(failover, "Failover should not be null"));
}
public static ResponseHandler proxy(final ContentResource url, final Failover failover) {
return new ProxyResponseHandler(toUrlFunction(checkNotNull(url, "URL should not be null")),
checkNotNull(failover, "Failover should not be null"));
}
public static ResponseHandler proxy(final ProxyConfig proxyConfig) {
return proxy(checkNotNull(proxyConfig), Failover.DEFAULT_FAILOVER);
}
public static ResponseHandler proxy(final ProxyConfig proxyConfig, final Failover failover) {
return new ProxyBatchResponseHandler(checkNotNull(proxyConfig), checkNotNull(failover));
}
public static ProxyConfig.Builder from(final String localBase) {
return ProxyConfig.builder(checkNotNullOrEmpty(localBase, "Local base should not be null"));
}
public static ContentResource template(final String template) {
return template(text(checkNotNullOrEmpty(template, "Template should not be null")));
}
public static ContentResource template(final String template, final String name, final String value) {
return template(text(checkNotNullOrEmpty(template, "Template should not be null")),
checkNotNullOrEmpty(name, "Template variable name should not be null"),
checkNotNullOrEmpty(value, "Template variable value should not be null"));
}
public static ContentResource template(final String template, final String name1, final String value1, final String name2, final String value2) {
return template(text(checkNotNullOrEmpty(template, "Template should not be null")),
checkNotNullOrEmpty(name1, "Template variable name should not be null"),
checkNotNullOrEmpty(value1, "Template variable value should not be null"),
checkNotNullOrEmpty(name2, "Template variable name should not be null"),
checkNotNullOrEmpty(value2, "Template variable value should not be null"));
}
public static ContentResource template(final ContentResource resource) {
return template(checkNotNull(resource, "Template should not be null"), ImmutableMap.<String, RequestExtractor<?>>of());
}
public static ContentResource template(final ContentResource template, final String name, final String value) {
return template(checkNotNull(template, "Template should not be null"),
checkNotNullOrEmpty(name, "Template variable name should not be null"),
var(checkNotNullOrEmpty(value, "Template variable value should not be null")));
}
public static ContentResource template(final ContentResource template, final String name1, final String value1, final String name2, final String value2) {
return template(checkNotNull(template, "Template should not be null"),
checkNotNullOrEmpty(name1, "Template variable name should not be null"),
var(checkNotNullOrEmpty(value1, "Template variable value should not be null")),
checkNotNullOrEmpty(name2, "Template variable name should not be null"),
var(checkNotNullOrEmpty(value2, "Template variable value should not be null")));
}
public static <T> ContentResource template(final String template, final String name, final RequestExtractor<T> extractor) {
return template(text(checkNotNullOrEmpty(template, "Template should not be null")),
checkNotNullOrEmpty(name, "Template variable name should not be null"),
checkNotNull(extractor, "Template variable extractor should not be null"));
}
public static <ExtractorType1, ExtractorType2> ContentResource template(final String template, final String name1, final RequestExtractor<ExtractorType1> extractor1,
final String name2, final RequestExtractor<ExtractorType2> extractor2) {
return template(text(checkNotNullOrEmpty(template, "Template should not be null")),
checkNotNullOrEmpty(name1, "Template variable name should not be null"),
checkNotNull(extractor1, "Template variable extractor should not be null"),
checkNotNullOrEmpty(name2, "Template variable name should not be null"),
checkNotNull(extractor2, "Template variable extractor should not be null"));
}
public static <T> ContentResource template(final ContentResource template, final String name, final RequestExtractor<T> extractor) {
return templateResource(checkNotNull(template, "Template should not be null"),
ImmutableMap.of(checkNotNullOrEmpty(name, "Template variable name should not be null"),
new ExtractorVariable<T>(checkNotNull(extractor, "Template variable extractor should not be null")))
);
}
public static <ExtractorType1, ExtractorType2> ContentResource template(final ContentResource template, final String name1, final RequestExtractor<ExtractorType1> extractor1,
final String name2, final RequestExtractor<ExtractorType2> extractor2) {
return templateResource(checkNotNull(template, "Template should not be null"),
ImmutableMap.of(checkNotNullOrEmpty(name1, "Template variable name should not be null"),
new ExtractorVariable<ExtractorType1>(checkNotNull(extractor1, "Template variable extractor should not be null")),
checkNotNullOrEmpty(name2, "Template variable name should not be null"),
new ExtractorVariable<ExtractorType2>(checkNotNull(extractor2, "Template variable extractor should not be null")))
);
}
public static ContentResource template(final String template,
final ImmutableMap<String, ? extends RequestExtractor<?>> variables) {
return template(text(checkNotNull(template, "Template should not be null")),
checkNotNull(variables, "Template variable should not be null"));
}
public static ContentResource template(final ContentResource template,
final ImmutableMap<String, ? extends RequestExtractor<?>> variables) {
return templateResource(checkNotNull(template, "Template should not be null"),
ApiUtils.toVariables(checkNotNull(variables, "Template variable should not be null")));
}
public static RequestExtractor<Object> var(final Object text) {
return new PlainExtractor<Object>(checkNotNull(text, "Template variable should not be null or empty"));
}
public static Failover failover(final String file) {
return new Failover(ApiUtils.failoverExecutor(
checkNotNullOrEmpty(file, "Filename should not be null")), FailoverStrategy.FAILOVER);
}
public static Failover playback(final String file) {
return new Failover(ApiUtils.failoverExecutor(
checkNotNullOrEmpty(file, "Filename should not be null")), FailoverStrategy.PLAYBACK);
}
public static MocoEventTrigger complete(final MocoEventAction action) {
return new MocoEventTrigger(MocoEvent.COMPLETE, checkNotNull(action, "Action should not be null"));
}
public static MocoEventAction async(final MocoEventAction action) {
return async(checkNotNull(action, "Action should not be null"),
latency(LatencyProcedure.DEFAULT_LATENCY, TimeUnit.MILLISECONDS));
}
public static MocoEventAction async(final MocoEventAction action, final LatencyProcedure procedure) {
return new MocoAsyncAction(checkNotNull(action, "Action should not be null"),
checkNotNull(procedure, "Procedure should not be null"));
}
public static MocoEventAction get(final String url) {
return get(text(checkNotNullOrEmpty(url, "URL should not be null")));
}
public static MocoEventAction get(final Resource url) {
return new MocoGetRequestAction(checkNotNull(url, "URL should not be null"));
}
public static MocoEventAction post(final Resource url, final ContentResource content) {
return new MocoPostRequestAction(checkNotNull(url, "URL should not be null"), checkNotNull(content, "Content should not be null"));
}
public static MocoEventAction post(final String url, final ContentResource content) {
return post(text(checkNotNullOrEmpty(url, "URL should not be null")), checkNotNull(content, "Content should not be null"));
}
public static MocoEventAction post(final String url, final String content) {
return post(checkNotNullOrEmpty(url, "URL should not be null"), text(checkNotNullOrEmpty(content, "Content should not be null")));
}
public static MocoEventAction post(final Resource url, final String content) {
return post(checkNotNull(url, "URL should not be null"), text(checkNotNullOrEmpty(content, "Content should not be null")));
}
public static MocoEventAction post(final Resource url, final Object object) {
return post(checkNotNull(url, "URL should not be null"),
Jsons.toJson(checkNotNull(object, "Content should not be null")));
}
public static ResponseHandler attachment(final String filename, final Resource resource) {
return AndResponseHandler.and(
header(HttpHeaders.CONTENT_DISPOSITION, format("attachment; filename=%s", checkNotNullOrEmpty(filename, "Filename should not be null or empty"))),
with(checkNotNull(resource, "Resource should not be null")));
}
private Moco() {
}
}
|
package org.minijax.data;
import java.io.Closeable;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.RollbackException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.Validate;
import org.minijax.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Dao class is the interface for all database access.
*/
public abstract class BaseDao implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(BaseDao.class);
protected EntityManagerFactory emf;
protected EntityManager em;
@Inject
protected void setEntityManagerFactory(final EntityManagerFactory emf) {
em = emf.createEntityManager();
}
/**
* Inserts a new instance in the database.
*
* @param obj The object to create.
* @return The instance with ID.
*/
public <T extends BaseEntity> T create(final T obj) {
Validate.notNull(obj);
Validate.isTrue(obj.getId() == null, "ID must not be set before create");
obj.validate();
obj.setId(IdUtils.create());
obj.setCreatedDateTime(Instant.now());
obj.setUpdatedDateTime(obj.getCreatedDateTime());
try {
em.getTransaction().begin();
em.persist(obj);
em.flush();
em.getTransaction().commit();
return obj;
} catch (final RollbackException ex) {
throw convertRollbackToConflict(ex);
}
}
/**
* Retrieves an object by ID.
*
* @param id The ID.
* @return The object if found; null otherwise.
*/
public <T extends BaseEntity> T read(final Class<T> entityClass, final UUID id) {
Validate.notNull(entityClass);
Validate.notNull(id);
return em.find(entityClass, id);
}
/**
* Finds a user by handle.
* Returns the user on success. Returns null on failure.
*
* @param handle The user's handle.
* @return The user on success; null on failure.
*/
public <T extends NamedEntity> T readByHandle(final Class<T> entityClass, final String handle) {
try {
// Unfortunately @CacheIndex does not work with CriteriaBuilder, so using string query instead.
return em.createQuery("SELECT e FROM " + entityClass.getSimpleName() + " e WHERE e.handle = :handle", entityClass)
.setParameter("handle", handle)
.getSingleResult();
} catch (final NoResultException ex) {
return null;
}
}
/**
* Returns a page of objects.
*
* @param entityClass The entity class.
* @param page The page index (zero indexed).
* @param pageSize The page size.
* @return A page of objects.
*/
public <T extends BaseEntity> List<T> readPage(
final Class<T> entityClass,
final int page,
final int pageSize) {
Validate.notNull(entityClass);
Validate.inclusiveBetween(0, 1000, page);
Validate.inclusiveBetween(1, 1000, pageSize);
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<T> cq = cb.createQuery(entityClass);
final Root<T> root = cq.from(entityClass);
cq.select(root);
cq.orderBy(cb.desc(root.get("id")));
return em.createQuery(cq)
.setFirstResult(page * pageSize)
.setMaxResults(pageSize)
.getResultList();
}
/**
* Updates an object.
*
* @param obj The object to update.
*/
public <T extends BaseEntity> T update(final T obj) {
Validate.notNull(obj);
Validate.notNull(obj.getId());
obj.validate();
obj.setUpdatedDateTime(Instant.now());
try {
em.getTransaction().begin();
em.merge(obj);
em.flush();
em.getTransaction().commit();
return obj;
} catch (final RollbackException ex) {
throw convertRollbackToConflict(ex);
}
}
/**
* Soft deletes an object.
*
* The data is still in the database, but with deleted flag.
*
* @param obj The object to delete.
*/
public <T extends BaseEntity> void delete(final T obj) {
Validate.notNull(obj);
Validate.notNull(obj.getId());
obj.setDeletedDateTime(Instant.now());
update(obj);
}
/**
* Hard deletes an object.
*
* This purges the data from the database.
*
* @param obj The object to delete.
*/
public <T extends BaseEntity> void purge(final T obj) {
Validate.notNull(obj);
Validate.notNull(obj.getId());
@SuppressWarnings("unchecked")
final T actual = (T) em.find(obj.getClass(), obj.getId());
if (actual != null) {
em.getTransaction().begin();
em.remove(actual);
em.getTransaction().commit();
}
}
/**
* Counts all rows of a type.
*
* @param entityClass The entity class.
* @return The count of rows.
*/
public <T extends BaseEntity> long countAll(final Class<T> entityClass) {
Validate.notNull(entityClass);
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<Long> cq = cb.createQuery(Long.class);
return em.createQuery(cq.select(cb.count(cq.from(entityClass)))).getSingleResult();
}
@Override
public void close() {
em.close();
}
/*
* Private helper methods.
*/
/**
* Returns null if the list is empty.
* Returns the first element otherwise.
*
* JPA getSingleResult() throws an exception if no results,
* which is an annoying design. So instead you can call
* getResultList() and wrap it with firstOrNull(), which is
* the more expected result.
*
* @param list
* @return
*/
protected static <T extends BaseEntity> T firstOrNull(final List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
/**
* Closes an EntityManager instance if not null.
*
* @param em The EntityManager.
*/
protected static void closeQuietly(final EntityManager em) {
if (em != null) {
em.close();
}
}
/**
* Converts a JPA rollback exception into a conflict exception.
*
* @param ex The database rollback exception.
* @return A structured key/value conflict exception.
*/
static ConflictException convertRollbackToConflict(final RollbackException ex) {
final List<Pattern> patterns = Arrays.asList(
Pattern.compile("Duplicate entry '(?<value>[^']+)' for key '(?<key>[^']+)'"),
Pattern.compile("CONSTRAINT_INDEX_[a-zA-Z0-9_]+ ON PUBLIC\\.[a-zA-Z]+\\((?<key>[a-zA-Z]+)\\) VALUES \\('(?<value>[^']+)'"));
for (final Pattern pattern : patterns) {
final Matcher matcher = pattern.matcher(ex.getMessage());
if (matcher.find()) {
final String key = matcher.group("key").toLowerCase();
final String value = matcher.group("value");
return new ConflictException(key, value);
}
}
LOG.warn("Unrecognized RollbackException: {}", ex.getMessage(), ex);
throw ex;
}
}
|
package org.noear.weed.cache;
import java.util.Map;
import java.util.concurrent.*;
public class LocalCache implements ICacheServiceEx {
private String _cacheKeyHead;
private int _defaultSeconds;
private Map<String, Entity> _data = new ConcurrentHashMap<>();
private static ScheduledExecutorService _exec = Executors.newSingleThreadScheduledExecutor();
public LocalCache(String keyHeader, int defSeconds) {
_cacheKeyHead = keyHeader;
_defaultSeconds = defSeconds;
}
@Override
public void store(String key, Object obj, int seconds) {
synchronized (key.intern()) {
Entity val = _data.get(key);
if (val != null) {
if (val.future != null) {
val.future.cancel(true);
val.future = null;
}
} else {
val = new Entity(obj);
_data.put(key, val);
}
if (seconds > 0) {
val.future = _exec.schedule(() -> {
_data.remove(key);
}, seconds, TimeUnit.SECONDS);
}
}
}
@Override
public Object get(String key) {
Entity val = _data.get(key);
return val == null ? null : val.value;
}
@Override
public void remove(String key) {
synchronized (key.intern()) {
Entity val = _data.remove(key);
if (val != null) {
if (val.future != null) {
val.future.cancel(true);
val.future = null;
}
}
}
}
public void clear() {
for (Entity val : _data.values()) {
if (val.future != null) {
val.future.cancel(true);
val.future = null;
}
}
_data.clear();
}
@Override
public int getDefalutSeconds() {
return _defaultSeconds;
}
@Override
public String getCacheKeyHead() {
return _cacheKeyHead;
}
private static class Entity {
public Object value;
public Future future;
public Entity(Object val) {
this.value = val;
}
}
}
|
package cgeo.geocaching.maps;
import cgeo.geocaching.R;
import cgeo.geocaching.databinding.MapSettingsDialogBinding;
import cgeo.geocaching.maps.routing.Routing;
import cgeo.geocaching.maps.routing.RoutingMode;
import cgeo.geocaching.models.IndividualRoute;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.PersistableUri;
import cgeo.geocaching.ui.ViewUtils;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.IndividualRouteUtils;
import cgeo.geocaching.utils.functions.Action1;
import android.app.Activity;
import android.app.Dialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import com.google.android.material.button.MaterialButtonToggleGroup;
public class MapSettingsUtils {
private static int colorAccent;
private static boolean isShowCircles;
private static boolean isAutotargetIndividualRoute;
private static boolean showAutotargetIndividualRoute;
private MapSettingsUtils() {
// utility class
}
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"}) // splitting up that method would not help improve readability
public static void showSettingsPopup(final Activity activity, @Nullable final IndividualRoute route, @NonNull final Action1<Boolean> onMapSettingsPopupFinished, @NonNull final Action1<RoutingMode> setRoutingValue, @NonNull final Action1<Integer> setCompactIconValue, @DrawableRes final int alternativeButtonResId) {
colorAccent = activity.getResources().getColor(R.color.colorAccent);
isShowCircles = Settings.isShowCircles();
isAutotargetIndividualRoute = Settings.isAutotargetIndividualRoute();
showAutotargetIndividualRoute = isAutotargetIndividualRoute || (route != null && route.getNumSegments() > 0);
final ArrayList<SettingsCheckboxModel> allCbs = new ArrayList<>();
final SettingsCheckboxModel foundCb = createCb(allCbs, R.string.map_showc_found, R.drawable.ic_menu_found, Settings.isExcludeFound(), Settings::setExcludeFound, true);
final SettingsCheckboxModel ownCb = createCb(allCbs, R.string.map_showc_own, R.drawable.ic_menu_myplaces, Settings.isExcludeMyCaches(), Settings::setExcludeMine, true);
final SettingsCheckboxModel disabledCb = createCb(allCbs, R.string.map_showc_disabled, R.drawable.ic_menu_disabled, Settings.isExcludeDisabledCaches(), Settings::setExcludeDisabled, true);
final SettingsCheckboxModel archivedCb = createCb(allCbs, R.string.map_showc_archived, R.drawable.ic_menu_archived, Settings.isExcludeArchivedCaches(), Settings::setExcludeArchived, true);
final SettingsCheckboxModel offlineLogCb = createCb(allCbs, R.string.map_showc_offlinelog, R.drawable.ic_menu_edit, Settings.isExcludeOfflineLog(), Settings::setExcludeOfflineLog, true);
final SettingsCheckboxModel wpOriginalCb = createCb(allCbs, R.string.map_showwp_original, R.drawable.ic_menu_waypoint, Settings.isExcludeWpOriginal(), Settings::setExcludeWpOriginal, true);
final SettingsCheckboxModel wpParkingCb = createCb(allCbs, R.string.map_showwp_parking, R.drawable.ic_menu_parking, Settings.isExcludeWpParking(), Settings::setExcludeWpParking, true);
final SettingsCheckboxModel wbVisitedCb = createCb(allCbs, R.string.map_showwp_visited, R.drawable.ic_menu_visited, Settings.isExcludeWpVisited(), Settings::setExcludeWpVisited, true);
final SettingsCheckboxModel trackCb = !PersistableUri.TRACK.hasValue() ? null : createCb(allCbs, R.string.map_show_track, R.drawable.ic_menu_hidetrack, Settings.isHideTrack(), Settings::setHideTrack, true);
final SettingsCheckboxModel circlesCb = createCb(allCbs, R.string.map_show_circles, R.drawable.ic_menu_circle, isShowCircles, Settings::setShowCircles, false);
final MapSettingsDialogBinding dialogView = MapSettingsDialogBinding.inflate(LayoutInflater.from(Dialogs.newContextThemeWrapper(activity)));
final List<LinearLayout> columns = ViewUtils.createAndAddStandardColumnView(activity, dialogView.mapSettingsColumns, null, 2, true);
final LinearLayout leftColumn = columns.get(0);
final LinearLayout rightColumn = columns.get(1);
leftColumn.addView(ViewUtils.createTextItem(activity, R.style.map_quicksettings_subtitle, R.string.map_show_caches_title));
foundCb.addToViewGroup(activity, leftColumn);
ownCb.addToViewGroup(activity, leftColumn);
disabledCb.addToViewGroup(activity, leftColumn);
archivedCb.addToViewGroup(activity, leftColumn);
offlineLogCb.addToViewGroup(activity, leftColumn);
rightColumn.addView(ViewUtils.createTextItem(activity, R.style.map_quicksettings_subtitle, R.string.map_show_waypoints_title));
wpOriginalCb.addToViewGroup(activity, rightColumn);
wpParkingCb.addToViewGroup(activity, rightColumn);
wbVisitedCb.addToViewGroup(activity, rightColumn);
rightColumn.addView(ViewUtils.createTextItem(activity, R.style.map_quicksettings_subtitle, R.string.map_show_other_title));
if (trackCb != null) {
trackCb.addToViewGroup(activity, rightColumn);
}
circlesCb.addToViewGroup(activity, rightColumn);
final ToggleButtonWrapper<Integer> compactIconWrapper = new ToggleButtonWrapper<>(Settings.getCompactIconMode(), setCompactIconValue, dialogView.compacticonTooglegroup);
compactIconWrapper.add(new ButtonChoiceModel<>(R.id.compacticon_off, Settings.COMPACTICON_OFF, activity.getString(R.string.switch_off)));
compactIconWrapper.add(new ButtonChoiceModel<>(R.id.compacticon_auto, Settings.COMPACTICON_AUTO, activity.getString(R.string.switch_auto)));
compactIconWrapper.add(new ButtonChoiceModel<>(R.id.compacticon_on, Settings.COMPACTICON_ON, activity.getString(R.string.switch_on)));
final ToggleButtonWrapper<RoutingMode> routingChoiceWrapper = new ToggleButtonWrapper<>(Routing.isAvailable() || Settings.getRoutingMode() == RoutingMode.OFF ? Settings.getRoutingMode() : RoutingMode.STRAIGHT, setRoutingValue, dialogView.routingTooglegroup);
final ArrayList<ButtonChoiceModel<RoutingMode>> routingChoices = new ArrayList<>();
for (RoutingMode mode : RoutingMode.values()) {
routingChoiceWrapper.add(new ButtonChoiceModel<>(mode.buttonResId, mode, activity.getString(mode.infoResId)));
}
if (showAutotargetIndividualRoute) {
dialogView.mapSettingsAutotargetContainer.setVisibility(View.VISIBLE);
dialogView.mapSettingsAutotarget.setChecked(isAutotargetIndividualRoute);
}
final Dialog dialog = Dialogs.bottomSheetDialogWithActionbar(activity, dialogView.getRoot(), R.string.quick_settings);
dialog.setOnDismissListener(d -> {
for (SettingsCheckboxModel item : allCbs) {
item.setValue();
}
compactIconWrapper.setValue();
routingChoiceWrapper.setValue();
onMapSettingsPopupFinished.call(isShowCircles != Settings.isShowCircles());
if (showAutotargetIndividualRoute && isAutotargetIndividualRoute != dialogView.mapSettingsAutotarget.isChecked()) {
if (route == null) {
Settings.setAutotargetIndividualRoute(dialogView.mapSettingsAutotarget.isChecked());
} else {
IndividualRouteUtils.setAutotargetIndividualRoute(activity, route, dialogView.mapSettingsAutotarget.isChecked());
}
}
});
dialog.show();
compactIconWrapper.init();
routingChoiceWrapper.init();
if (!Routing.isAvailable()) {
configureRoutingButtons(false, routingChoiceWrapper);
dialogView.routingInfo.setVisibility(View.VISIBLE);
dialogView.routingInfo.setOnClickListener(v -> Dialogs.confirm(activity, R.string.map_routing_activate_title, R.string.map_routing_activate, (dialog1, which) -> {
Settings.setUseInternalRouting(true);
Settings.setBrouterAutoTileDownloads(true);
configureRoutingButtons(true, routingChoiceWrapper);
dialogView.routingInfo.setVisibility(View.GONE);
}));
}
}
private static void configureRoutingButtons(final boolean enabled, final ToggleButtonWrapper<RoutingMode> routingChoiceWrapper) {
for (final ButtonChoiceModel<RoutingMode> button : routingChoiceWrapper.list) {
if (!(button.assignedValue == RoutingMode.OFF || button.assignedValue == RoutingMode.STRAIGHT)) {
button.button.setEnabled(enabled);
button.button.setAlpha(enabled ? 1f : .3f);
}
}
}
private static SettingsCheckboxModel createCb(final Collection<SettingsCheckboxModel> coll, @StringRes final int resTitle, @DrawableRes final int resIcon, final boolean currentValue, final Action1<Boolean> setValue, final boolean isNegated) {
final SettingsCheckboxModel result = new SettingsCheckboxModel(resTitle, resIcon, currentValue, setValue, isNegated);
coll.add(result);
return result;
}
private static class SettingsCheckboxModel {
@StringRes private final int resTitle;
@DrawableRes private final int resIcon;
private boolean currentValue;
private final Action1<Boolean> setValue;
private final boolean isNegated;
SettingsCheckboxModel(@StringRes final int resTitle, @DrawableRes final int resIcon, final boolean currentValue, final Action1<Boolean> setValue, final boolean isNegated) {
this.resTitle = resTitle;
this.resIcon = resIcon;
this.currentValue = isNegated != currentValue;
this.setValue = setValue;
this.isNegated = isNegated;
}
public void setValue() {
this.setValue.call(isNegated != currentValue);
}
public void addToViewGroup(final Activity ctx, final ViewGroup viewGroup) {
final CheckBox cb = ViewUtils.addCheckboxItem(ctx, viewGroup, resTitle, resIcon);
cb.setChecked(currentValue);
cb.setOnCheckedChangeListener((v, c) -> this.currentValue = !this.currentValue);
}
}
private static class ButtonChoiceModel<T> {
public final int resButton;
public final T assignedValue;
public final String info;
public View button = null;
ButtonChoiceModel(final int resButton, final T assignedValue, final String info) {
this.resButton = resButton;
this.assignedValue = assignedValue;
this.info = info;
}
}
private static class ToggleButtonWrapper<T> {
private final MaterialButtonToggleGroup toggleGroup;
private final ArrayList<ButtonChoiceModel<T>> list;
private final Action1<T> setValue;
private final T originalValue;
ToggleButtonWrapper(final T originalValue, final Action1<T> setValue, final MaterialButtonToggleGroup toggleGroup) {
this.originalValue = originalValue;
this.toggleGroup = toggleGroup;
this.setValue = setValue;
this.list = new ArrayList<>();
}
public void add(final ButtonChoiceModel<T> item) {
list.add(item);
}
public ButtonChoiceModel<T> getByResId(final int id) {
for (ButtonChoiceModel<T> item : list) {
if (item.resButton == id) {
return item;
}
}
return null;
}
public ButtonChoiceModel<T> getByAssignedValue(final T value) {
for (ButtonChoiceModel<T> item : list) {
if (Objects.equals(item.assignedValue, value)) {
return item;
}
}
return null;
}
public void init() {
for (final ButtonChoiceModel<T> button : list) {
button.button = toggleGroup.findViewById(button.resButton);
}
toggleGroup.check(getByAssignedValue(originalValue).resButton);
}
public void setValue() {
final T currentValue = getByResId(toggleGroup.getCheckedButtonId()).assignedValue;
if (setValue != null && !originalValue.equals(currentValue)) {
this.setValue.call(currentValue);
}
}
}
}
|
package fi.luontola.cqrshotel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import fi.luontola.cqrshotel.framework.Message;
import org.apache.commons.lang3.RandomStringUtils;
import org.javamoney.moneta.Money;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.reflections.Reflections;
import javax.money.Monetary;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@Category(SlowTests.class)
public class JsonSerializationTest {
private final ObjectMapper objectMapper = new Application().jacksonObjectMapper();
@Test
public void LocalDate_format() throws JsonProcessingException {
assertThat(objectMapper.writeValueAsString(LocalDate.of(2000, 1, 2)), is("\"2000-01-02\""));
}
@Test
public void Instant_format() throws JsonProcessingException {
assertThat(objectMapper.writeValueAsString(Instant.ofEpochSecond(0)), is("\"1970-01-01T00:00:00Z\""));
}
@Test
public void Money_format() throws JsonProcessingException {
assertThat(objectMapper.writeValueAsString(Money.of(12.34, "EUR")), is("\"EUR 12.34\""));
}
@Test
public void all_messages_are_serializable() throws Exception {
new Reflections("fi.luontola.cqrshotel")
.getSubTypesOf(Message.class).stream()
.filter(type -> !type.isInterface())
.filter(type -> Modifier.isPublic(type.getModifiers()))
.forEach(type -> assertSerializable(type, objectMapper));
}
private static void assertSerializable(Class<?> type, ObjectMapper objectMapper) {
try {
Object original = newDummy(type);
String json = objectMapper.writeValueAsString(original);
Object deserialized = objectMapper.readValue(json, type);
assertThat(deserialized, is(original));
} catch (Exception e) {
e.printStackTrace();
throw new AssertionError("Not serializable: " + type, e);
}
}
private static Object newDummy(Class<?> type) throws Exception {
Constructor<?> ctor = type.getConstructors()[0];
Class<?>[] paramTypes = ctor.getParameterTypes();
Object[] params = new Object[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
params[i] = randomValue(paramTypes[i]);
}
return ctor.newInstance(params);
}
private static Object randomValue(Class<?> type) {
ThreadLocalRandom random = ThreadLocalRandom.current();
if (type == UUID.class) {
return UUID.randomUUID();
}
if (type == LocalDate.class) {
return LocalDate.of(
random.nextInt(2000, 2100),
random.nextInt(Month.JANUARY.getValue(), Month.DECEMBER.getValue() + 1),
random.nextInt(1, Month.FEBRUARY.minLength() + 1));
}
if (type == Money.class) {
return Money.of(
random.nextDouble(0, 1000),
pickRandom(Monetary.getCurrencies()));
}
if (type == Instant.class) {
return Instant.ofEpochMilli(random.nextLong());
}
if (type == ZonedDateTime.class) {
ZoneId zoneId = ZoneId.of(pickRandom(ZoneId.getAvailableZoneIds()));
return Instant.ofEpochMilli(random.nextLong()).atZone(zoneId);
}
if (type == String.class) {
return RandomStringUtils.randomAlphanumeric(random.nextInt(10));
}
if (type == int.class) {
return random.nextInt();
}
throw new IllegalArgumentException("Unsupported type: " + type);
}
private static <T> T pickRandom(Collection<T> values) {
ThreadLocalRandom random = ThreadLocalRandom.current();
return values.stream()
.skip(random.nextInt(values.size()))
.findFirst()
.get();
}
}
|
package io.vertx.ext.apex.handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.impl.LoggerFactory;
import io.vertx.ext.apex.ApexTestBase;
import io.vertx.ext.apex.handler.sockjs.SockJSHandler;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
public class SockJSHandlerTest extends ApexTestBase {
private static final Logger log = LoggerFactory.getLogger(SockJSHandlerTest.class);
@Override
public void setUp() throws Exception {
super.setUp();
SockJSHandler.installTestApplications(router, vertx);
}
@Test
public void testGreeting() {
waitFor(2);
testGreeting("/echo/");
testGreeting("/echo");
await();
}
private void testGreeting(String uri) {
client.getNow(uri, resp -> {
assertEquals(200, resp.statusCode());
assertEquals("text/plain; charset=UTF-8", resp.getHeader("content-type"));
resp.bodyHandler(buff -> {
assertEquals("Welcome to SockJS!\n", buff.toString());
complete();
});
});
}
@Test
public void testNotFound() {
waitFor(5);
testNotFound("/echo/a");
testNotFound("/echo/a.html");
testNotFound("/echo/a/a");
testNotFound("/echo/a/a/");
testNotFound("/echo/a/");
testNotFound("/echo
testNotFound("/echo
await();
}
private void testNotFound(String uri) {
client.getNow(uri, resp -> {
assertEquals(404, resp.statusCode());
complete();
});
}
@Test
public void testProtocol() throws Exception {
String[] envp = new String[] {"SOCKJS_URL=http://localhost:8080"};
File dir = new File("src/test/sockjs-protocol");
Process p = Runtime.getRuntime().exec("./venv/bin/python sockjs-protocol-0.3.3.py", envp, dir);
try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
String line;
while ((line = input.readLine()) != null) {
log.info(line);
}
}
int res = p.waitFor();
// Make sure all tests pass
assertEquals("Protocol tests failed", 0, res);
}
}
|
package monitoring.intf;
import structure.impl.Verdict;
/*
* A monitor object takes an event consisting of a name and an array of arguments and produces a verdict
*/
public abstract class Monitor {
public abstract Verdict step(int eventName, Object[] args);
public Verdict step(int eventName, Object param1) {
return step(eventName, new Object[] { param1 });
}
public Verdict step(int eventName, Object param1, Object param2) {
return step(eventName, new Object[] { param1, param2 });
}
public Verdict step(int eventName, Object param1, Object param2,
Object param3) {
return step(eventName, new Object[] { param1, param2, param3 });
}
public Verdict step(int eventName, Object param1, Object param2,
Object param3, Object param4) {
return step(eventName, new Object[] { param1, param2, param3, param4 });
}
public Verdict step(int eventName, Object param1, Object param2,
Object param3, Object param4, Object param5) {
return step(eventName, new Object[] { param1, param2, param3, param4,
param5 });
}
public abstract Verdict end();
// TODO: The trace method received before a list of Events, now we don't
// have 'Event'
// public abstract Verdict trace(List<Event> eventList);
}
|
package net.mollywhite.mbta.client;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.mollywhite.mbta.api.Line;
import net.mollywhite.mbta.api.Station;
import net.mollywhite.mbta.api.Tweet;
import org.junit.Before;
import org.junit.Test;
import static io.dropwizard.testing.FixtureHelpers.fixture;
import static org.assertj.core.api.Assertions.assertThat;
public class TweetDetailsTest {
private ObjectMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Test
public void testGetReplyTo() throws Exception {
final Tweet tweet = mapper.readValue(fixture("fixtures/TweetWithReplyToFixture.json"), Tweet.class);
final TweetDetails tweetDetails = new TweetDetails(tweet).get();
assertThat(tweetDetails.getLines()).isEmpty();
assertThat(tweetDetails.getBranches()).isEmpty();
assertThat(tweetDetails.getStations()).isEmpty();
}
@Test
public void testRetweet() throws Exception {
final Tweet tweet = mapper.readValue(fixture("fixtures/RetweetFixture.json"), Tweet.class);
final TweetDetails tweetDetails = new TweetDetails(tweet).get();
assertThat(tweetDetails.getLines()).containsExactly(Line.ORANGE);
assertThat(tweetDetails.getBranches()).isEmpty();
assertThat(tweetDetails.getStations()).containsExactly(Station.WELLINGTON, Station.OAKGROVE);
}
}
|
package net.openhft.chronicle.queue;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.io.AbstractCloseable;
import net.openhft.chronicle.core.io.AbstractReferenceCounted;
import net.openhft.chronicle.core.onoes.ExceptionKey;
import net.openhft.chronicle.core.onoes.Slf4jExceptionHandler;
import net.openhft.chronicle.core.threads.CleaningThread;
import net.openhft.chronicle.core.threads.ThreadDump;
import net.openhft.chronicle.core.time.SystemTimeProvider;
import net.openhft.chronicle.wire.MessageHistory;
import org.junit.After;
import org.junit.Before;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Predicate;
public class QueueTestCommon {
private final Map<Predicate<ExceptionKey>, String> ignoreExceptions = new LinkedHashMap<>();
private final Map<Predicate<ExceptionKey>, String> expectedExceptions = new LinkedHashMap<>();
protected ThreadDump threadDump;
protected Map<ExceptionKey, Integer> exceptions;
protected boolean finishedNormally;
@Before
public void assumeFinishedNormally() {
finishedNormally = true;
}
@Before
public void clearMessageHistory() {
MessageHistory.get().reset();
}
@Before
public void enableReferenceTracing() {
AbstractReferenceCounted.enableReferenceTracing();
}
public void assertReferencesReleased() {
AbstractReferenceCounted.assertReferencesReleased();
}
@Before
public void threadDump() {
threadDump = new ThreadDump();
}
public void checkThreadDump() {
threadDump.assertNoNewThreads();
}
@Before
public void recordExceptions() {
exceptions = Jvm.recordExceptions();
}
public void ignoreException(String message) {
ignoreException(k -> k.message.contains(message) || (k.throwable != null && k.throwable.getMessage().contains(message)), message);
}
public void expectException(String message) {
expectException(k -> k.message.contains(message) || (k.throwable != null && k.throwable.getMessage().contains(message)), message);
}
public void ignoreException(Predicate<ExceptionKey> predicate, String description) {
ignoreExceptions.put(predicate, description);
}
public void expectException(Predicate<ExceptionKey> predicate, String description) {
expectedExceptions.put(predicate, description);
}
public void checkExceptions() {
for (Map.Entry<Predicate<ExceptionKey>, String> expectedException : expectedExceptions.entrySet()) {
if (!exceptions.keySet().removeIf(expectedException.getKey()))
throw new AssertionError("No error for " + expectedException.getValue());
}
expectedExceptions.clear();
for (Map.Entry<Predicate<ExceptionKey>, String> expectedException : ignoreExceptions.entrySet()) {
if (!exceptions.keySet().removeIf(expectedException.getKey()))
Slf4jExceptionHandler.DEBUG.on(getClass(), "No error for " + expectedException.getValue());
}
ignoreExceptions.clear();
for (String msg : "Shrinking ,Allocation of , ms to add mapping for ,jar to the classpath, ms to pollDiskSpace for , us to linearScan by position from ,File released ,Overriding roll length from existing metadata, was 3600000, overriding to 86400000 ".split(",")) {
exceptions.keySet().removeIf(e -> e.message.contains(msg));
}
if (Jvm.hasException(exceptions)) {
Jvm.dumpException(exceptions);
Jvm.resetExceptionHandlers();
throw new AssertionError(exceptions.keySet());
}
}
protected boolean hasExceptions(Map<ExceptionKey, Integer> exceptions) {
return Jvm.hasException(this.exceptions);
}
@After
public void afterChecks() {
SystemTimeProvider.CLOCK = SystemTimeProvider.INSTANCE;
preAfter();
CleaningThread.performCleanup(Thread.currentThread());
// find any discarded resources.
System.gc();
AbstractCloseable.waitForCloseablesToClose(100);
if (finishedNormally) {
assertReferencesReleased();
checkThreadDump();
checkExceptions();
}
tearDown();
}
protected void preAfter() {
}
protected void tearDown() {
}
}
|
package com.cinnamon.demo;
import com.cinnamon.gfx.ImageComponent;
import com.cinnamon.gfx.ImageFactory;
import com.cinnamon.object.GObject;
import com.cinnamon.object.GObjectFactory;
import com.cinnamon.system.Game;
import com.cinnamon.utils.Shape;
/**
* <p>Demo {@link GObjectFactory}.</p>
*
*
*/
public class DemoGObjectFactory extends GObjectFactory
{
private static final int LOAD = 100;
private static final float GROWTH = 0.15f;
public DemoGObjectFactory(Game.Resources directory)
{
super(directory, LOAD, GROWTH);
}
@Override
protected void onLoad(Game.Resources directory)
{
addConfiguration("char", new CharacterConfig());
addConfiguration("red_char", new RedCharacterConfig());
addConfiguration("green_char", new GreenCharacterConfig());
addConfiguration("blue_char", new BlueCharacterConfig());
addConfiguration(GObjectFactory.CONFIG_ROOM, new RoomConfig());
}
@Override
protected void onRequisition(GObject object)
{
}
@Override
protected void onRemove(GObject object)
{
}
@Override
protected void makeDefault(GObject object)
{
}
private class CharacterConfig implements GObjectConfig
{
@Override
public void configure(GObject object, Game.Resources resource)
{
final ImageFactory imgFact = resource.getImageFactory();
final ImageComponent img = imgFact.getComponent("character");
object.setImageComponent(img);
object.setBodyComponent(new DemoBodyComponent(new Shape
(Shape.Type.RECTANGLE, 100, 100)));
}
}
private class RedCharacterConfig implements GObjectConfig
{
@Override
public void configure(GObject object, Game.Resources resource)
{
final ImageFactory imgFact = resource.getImageFactory();
final ImageComponent img = imgFact.getComponent("character");
img.setTint(1f, 0f, 0f);
object.setImageComponent(img);
object.setBodyComponent(new DemoBodyComponent(new Shape
(Shape.Type.RECTANGLE, 100, 100)));
}
}
private class GreenCharacterConfig implements GObjectConfig
{
@Override
public void configure(GObject object, Game.Resources resource)
{
final ImageFactory imgFact = resource.getImageFactory();
final ImageComponent img = imgFact.getComponent("character");
img.setTint(0f, 1f, 0f);
object.setImageComponent(img);
object.setBodyComponent(new DemoBodyComponent(new Shape
(Shape.Type.RECTANGLE, 100, 100)));
}
}
private class BlueCharacterConfig implements GObjectConfig
{
@Override
public void configure(GObject object, Game.Resources resource)
{
final ImageFactory imgFact = resource.getImageFactory();
final ImageComponent img = imgFact.getComponent("character");
img.setTint(0f, 0f, 1f);
object.setImageComponent(img);
object.setBodyComponent(new DemoBodyComponent(new Shape
(Shape.Type.RECTANGLE, 100, 100)));
}
}
private class RoomConfig implements GObjectConfig
{
@Override
public void configure(GObject object, Game.Resources resource)
{
final ImageFactory imgFact = resource.getImageFactory();
final ImageComponent img = imgFact.getComponent(ImageFactory.CONFIG_ROOM);
object.setImageComponent(img);
}
}
}
|
package nom.bdezonia.zorbage.algorithm;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class TestIsSorted {
@Test
public void test() {
IndexedDataSource<Float64Member> nums = ArrayStorage.allocateDoubles(
new double[] {0,0,0,1,2,3,4,4,4,7,6,9});
assertFalse(IsSorted.compute(G.DBL, nums));
Sort.compute(G.DBL, nums);
assertTrue(IsSorted.compute(G.DBL, nums));
Sort.compute(G.DBL, G.DBL.isGreater(), nums);
assertFalse(IsSorted.compute(G.DBL, nums));
assertTrue(IsSorted.compute(G.DBL, G.DBL.isGreater(), nums));
}
}
|
package com.almasb.fxgl.app;
import com.almasb.fxgl.core.logging.FXGLLogger;
import com.almasb.fxgl.core.logging.Logger;
import com.almasb.fxgl.saving.DataFile;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Initializes application states.
* Manages transitions, updates of all states.
*
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
public final class AppStateMachine {
private static final Logger log = FXGLLogger.get(AppStateMachine.class);
private final AppState loading;
private final AppState play;
// These 3 states are optional
private final AppState intro;
private final AppState mainMenu;
private final AppState gameMenu;
private AppState appState;
private Deque<SubState> subStates = new ArrayDeque<>();
private GameApplication app;
AppStateMachine(GameApplication app) {
this.app = app;
log.debug("Initializing application states");
// STARTUP is default
appState = FXGL.getInstance(StartupState.class);
loading = FXGL.getInstance(LoadingState.class);
play = FXGL.getInstance(PlayState.class);
// reasonable hack to trigger dialog state init before intro and menus
DialogSubState.INSTANCE.getView();
intro = app.getSettings().isIntroEnabled() ? FXGL.getInstance(IntroState.class) : null;
mainMenu = app.getSettings().isMenuEnabled() ? FXGL.getInstance(MainMenuState.class) : null;
gameMenu = app.getSettings().isMenuEnabled() ? FXGL.getInstance(GameMenuState.class) : null;
}
/**
* Can only be called when no substates are present.
* Can only be called by internal FXGL API.
*/
void setState(AppState newState) {
if (!subStates.isEmpty()) {
log.warning("Cannot change states with active substates");
return;
}
AppState prevState = appState;
prevState.exit();
log.debug(prevState + " -> " + newState);
// new state
appState = newState;
app.getDisplay().setScene(appState.getScene());
appState.enter(prevState);
}
void onUpdate(double tpf) {
getCurrentState().update(tpf);
}
public void pushState(SubState newState) {
log.debug("Push state: " + newState);
// substate, so prevState does not exit
State prevState = getCurrentState();
prevState.getInput().clearAll();
log.debug(prevState + " -> " + newState);
// new state
subStates.push(newState);
app.getDisplay().getCurrentScene().getRoot().getChildren().add(newState.getView());
newState.enter(prevState);
}
public void popState() {
if (subStates.isEmpty()) {
log.warning("Cannot pop state: Substates are empty!");
return;
}
SubState prevState = subStates.pop();
log.debug("Pop state: " + prevState);
prevState.exit();
log.debug(getCurrentState() + " <- " + prevState);
app.getDisplay().getCurrentScene().getRoot().getChildren().remove(prevState.getView());
}
public State getCurrentState() {
return (subStates.isEmpty()) ? appState : subStates.peek();
}
public State getIntroState() {
if (intro == null)
throw new IllegalStateException("Intro is not enabled");
return intro;
}
public State getLoadingState() {
return loading;
}
public State getMainMenuState() {
if (mainMenu == null)
throw new IllegalStateException("Menu is not enabled");
return mainMenu;
}
public State getGameMenuState() {
if (gameMenu == null)
throw new IllegalStateException("Menu is not enabled");
return gameMenu;
}
public State getPlayState() {
return play;
}
public State getDialogState() {
return DialogSubState.INSTANCE;
}
void startIntro() {
setState(intro);
}
void startLoad(DataFile dataFile) {
((LoadingState) loading).setDataFile(dataFile);
setState(loading);
}
void startGameMenu() {
setState(gameMenu);
}
void startMainMenu() {
setState(mainMenu);
}
/**
* Set state to PLAYING.
*/
void startPlay() {
setState(play);
}
/**
* @return true if app is in play state
*/
public boolean isInPlay() {
return getCurrentState() == getPlayState();
}
public boolean isInGameMenu() {
return getCurrentState() == getGameMenuState();
}
/**
* @return true if can show close dialog
*/
public boolean canShowCloseDialog() {
// do not allow close dialog if
// 1. a dialog is shown
// 2. we are loading a game
// 3. we are showing intro
return getCurrentState() != DialogSubState.INSTANCE
&& getCurrentState() != getLoadingState()
&& (!FXGL.getApp().getSettings().isIntroEnabled() || getCurrentState() != getIntroState());
}
}
|
package org.dlw.ai.blackboard;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author dlwhitehurst
*
*/
public class BlackboardContextTest {
private Blackboard blackboard;
private Controller controller;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
blackboard = BlackboardContext.getInstance().getBlackboard();
controller = BlackboardContext.getInstance().getController();
}
@Test
public void testGetBlackboard() throws AssertionError {
assertNotNull(blackboard);
}
@Test
public void testGetController() throws AssertionError {
assertNotNull(controller);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
}
|
package ro.isdc.wro.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.isdc.wro.WroRuntimeException;
import ro.isdc.wro.config.jmx.WroConfiguration;
import ro.isdc.wro.http.WroFilter;
/**
* Holds the properties related to a request cycle.
*
* @author Alex Objelean
*/
public class Context
implements ReadOnlyContext {
private static final Logger LOG = LoggerFactory.getLogger(Context.class);
/**
* Maps correlationId with a Context.
*/
private static final Map<String, Context> CONTEXT_MAP = Collections.synchronizedMap(new HashMap<String, Context>());
/**
* Holds a correlationId, created in {@link WroFilter}. A correlationId will be associated with a {@link Context}
* object.
*/
private static ThreadLocal<String> CORRELATION_ID = new ThreadLocal<String>();
private WroConfiguration config;
/**
* Request.
*/
private transient HttpServletRequest request;
/**
* Response.
*/
private transient HttpServletResponse response;
/**
* ServletContext.
*/
private transient ServletContext servletContext;
/**
* FilterConfig.
*/
private transient FilterConfig filterConfig;
/**
* The path to the folder, relative to the root, used to compute rewritten image url.
*/
private String aggregatedFolderPath;
/**
* @return {@link WroConfiguration} singleton instance.
*/
public WroConfiguration getConfig() {
return config;
}
/**
* DO NOT CALL THIS METHOD UNLESS YOU ARE SURE WHAT YOU ARE DOING.
* <p/>
* sets the {@link WroConfiguration} singleton instance.
*/
public void setConfig(final WroConfiguration config) {
this.config = config;
}
/**
* A context useful for running in web context (inside a servlet container).
*/
public static Context webContext(final HttpServletRequest request, final HttpServletResponse response,
final FilterConfig filterConfig) {
return new Context(request, response, filterConfig);
}
/**
* A context useful for running in non web context (standalone applications).
*/
public static Context standaloneContext() {
return new Context();
}
/**
* @return {@link Context} associated with CURRENT request cycle.
*/
public static Context get() {
validateContext();
final String correlationId = CORRELATION_ID.get();
return CONTEXT_MAP.get(correlationId);
}
/**
* @return true if the call is done during wro4j request cycle. In other words, if the context is set.
*/
public static boolean isContextSet() {
try {
return CORRELATION_ID.get() != null && CONTEXT_MAP.get(CORRELATION_ID.get()) != null;
} catch (Exception e) {
LOG.debug("Unexpected exception during Context#isContextSet() method call", e);
return false;
}
}
/**
* Checks if the {@link Context} is accessible from current request cycle.
*/
private static void validateContext() {
if (!isContextSet()) {
throw new WroRuntimeException("No context associated with CURRENT request cycle!");
}
}
/**
* Set a context with default configuration to current thread.
*/
public static void set(final Context context) {
set(context, new WroConfiguration());
}
/**
* Associate a context with the CURRENT request cycle.
*
* @param context {@link Context} to set.
*/
public static void set(final Context context, final WroConfiguration config) {
Validate.notNull(context);
Validate.notNull(config);
context.setConfig(config);
final String correlationId = generateCorrelationId();
CORRELATION_ID.set(correlationId);
CONTEXT_MAP.put(correlationId, context);
}
/**
* @return a string representation of an unique id used to store Context in a map.
*/
private static String generateCorrelationId() {
return UUID.randomUUID().toString();
}
/**
* Remove context from the local thread.
*/
public static void unset() {
final String correlationId = CORRELATION_ID.get();
if (correlationId != null) {
CONTEXT_MAP.remove(correlationId);
}
CORRELATION_ID.remove();
}
/**
* Private constructor. Used to build {@link StandAloneContext}.
*/
private Context() {}
/**
* Constructor.
*/
private Context(final HttpServletRequest request, final HttpServletResponse response, final FilterConfig filterConfig) {
this.request = request;
this.response = response;
this.servletContext = filterConfig != null ? filterConfig.getServletContext() : null;
this.filterConfig = filterConfig;
}
/**
* @return the request
*/
public HttpServletRequest getRequest() {
return this.request;
}
/**
* @return the response
*/
public HttpServletResponse getResponse() {
return this.response;
}
/**
* @return the servletContext
*/
public ServletContext getServletContext() {
return this.servletContext;
}
/**
* @return the filterConfig
*/
public FilterConfig getFilterConfig() {
return this.filterConfig;
}
/**
* {@inheritDoc}
*/
public String getAggregatedFolderPath() {
return this.aggregatedFolderPath;
}
/**
* @param aggregatedFolderPath the aggregatedFolderPath to set
*/
public void setAggregatedFolderPath(final String aggregatedFolderPath) {
this.aggregatedFolderPath = aggregatedFolderPath;
}
/**
* Perform context clean-up.
*/
public static void destroy() {
unset();
//remove all context objects stored in map
CONTEXT_MAP.clear();
}
/**
* Set the correlationId to the current thread.
*/
public static void setCorrelationId(final String correlationId) {
Validate.notNull(correlationId);
CORRELATION_ID.set(correlationId);
}
/**
* Remove the correlationId from the current thread. This operation will not remove the {@link Context} associated
* with the correlationId. In order to remove context, call {@link Context#unset()}.
* <p/>
* Unsetting correlationId is useful when you create child threads which needs to access the correlationId from the
* parent thread. This simulates the {@link InheritableThreadLocal} functionality.
*/
public static void unsetCorrelationId() {
CORRELATION_ID.remove();
}
/**
* @return the correlationId associated with this thread.
*/
public static String getCorrelationId() {
validateContext();
return CORRELATION_ID.get();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
|
package org.synyx.sybil.brick;
import com.tinkerforge.BrickMaster;
import com.tinkerforge.IPConnection;
import com.tinkerforge.NotConnectedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.synyx.sybil.brick.database.BrickDomain;
import org.synyx.sybil.bricklet.output.ledstrip.LEDStripRegistry;
import org.synyx.sybil.bricklet.output.ledstrip.database.LEDStripRepository;
import org.synyx.sybil.config.DevSpringConfig;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
@ContextConfiguration(classes = DevSpringConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class BrickServiceIntegTest {
private static final Logger LOG = LoggerFactory.getLogger(BrickServiceIntegTest.class);
@Autowired
private LEDStripRegistry LEDStripRegistry;
@Autowired
private LEDStripRepository LEDStripRepository;
@Autowired
private BrickService brickService;
@Test
public void testReConnectAll() throws Exception {
LOG.info("START Test testConnectALL");
List<BrickDomain> bricks = new ArrayList<>();
BrickDomain test1 = new BrickDomain("localhost", "6dLj52", 14223, "one");
BrickDomain test2 = new BrickDomain("localhost", "im666", 14224, "two");
bricks.add(test1);
bricks.add(test2);
BrickDomain test3 = new BrickDomain("localhost", "123abc", 14225, "three");
int oldSize = brickService.getAllBrickDomains().size();
brickService.saveBrickDomains(bricks);
brickService.saveBrickDomain(test3);
assertThat(brickService.getAllBrickDomains().size(), is(oldSize + 3)); // assert that 3 bricks were added
IPConnection ipConnection = brickService.getIPConnection(test3);
brickService.disconnectAll();
try {
BrickMaster brickMaster = brickService.getBrickMaster("123abc", ipConnection);
brickMaster.getChipTemperature();
throw new Exception("No Exception thrown!");
} catch (NotConnectedException e) {
// This is what we want!
}
brickService.connectAll();
ipConnection = brickService.getIPConnection(test3);
BrickMaster brickMaster = brickService.getBrickMaster("123abc", ipConnection);
brickMaster.getChipTemperature();
brickService.deleteBrickDomain(brickService.getBrickDomain("one"));
brickService.deleteBrickDomain(brickService.getBrickDomain("two"));
brickService.deleteBrickDomain(brickService.getBrickDomain("three"));
brickService.disconnectAll();
LOG.info("FINISH Test testConnectALL");
}
}
|
package uk.ac.ebi.subs.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.http.utils.Base64Coder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import uk.ac.ebi.subs.data.Submission;
import uk.ac.ebi.subs.data.client.Sample;
import uk.ac.ebi.subs.data.client.Study;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.typeCompatibleWith;
import static org.junit.Assert.assertThat;
public class ApiIntegrationTestHelper {
private ObjectMapper objectMapper;
private String rootUri;
public static String DEFAULT_USER = "usi_user";
public static String DEFAULT_PASSWORD = "password";
private Map<String, String> getHeaders = new HashMap<>();
private Map<String, String> postHeaders = new HashMap<>();
public ApiIntegrationTestHelper(ObjectMapper objectMapper, String rootUri, List<MongoRepository> repositoriesToInit,
Map<String, String> getHeaders, Map<String, String> postHeaders) {
this.objectMapper = objectMapper;
this.rootUri = rootUri;
this.getHeaders = getHeaders;
this.postHeaders = postHeaders;
Unirest.setObjectMapper(new com.mashape.unirest.http.ObjectMapper() {
public <T> T readValue(String value, Class<T> valueType) {
try {
return objectMapper.readValue(value, valueType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String writeValue(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
repositoriesToInit.forEach(MongoRepository::deleteAll);
}
public HttpResponse<JsonNode> postSubmission(Map<String, String> rootRels, Submission submission) throws UnirestException {
//create a new submission
HttpResponse<JsonNode> submissionResponse = Unirest.post(rootRels.get("submissions:create"))
.headers(postHeaders)
.body(submission)
.asJson();
assertThat(submissionResponse.getStatus(), is(equalTo(HttpStatus.CREATED.value())));
assertThat(submissionResponse.getHeaders().get("Location"), notNullValue());
return submissionResponse;
}
public String submissionWithSamples(Map<String, String> rootRels) throws UnirestException, IOException {
Submission submission = Helpers.generateSubmission();
HttpResponse<JsonNode> submissionResponse = postSubmission(rootRels, submission);
String submissionLocation = submissionResponse.getHeaders().getFirst("Location");
Map<String, String> submissionRels = relsFromPayload(submissionResponse.getBody().getObject());
assertThat(submissionRels.get("samples"), notNullValue());
List<Sample> testSamples = Helpers.generateTestClientSamples(2);
//add samples to the submission
for (Sample sample : testSamples) {
sample.setSubmission(submissionLocation);
HttpResponse<JsonNode> sampleResponse = Unirest.post(rootRels.get("samples:create"))
.headers(postHeaders)
.body(sample)
.asJson();
assertThat(sampleResponse.getStatus(), is(equalTo(HttpStatus.CREATED.value())));
}
//retrieve the samples
String submissionSamplesUrl = submissionRels.get("samples");
HttpResponse<JsonNode> samplesQueryResponse = Unirest.get(submissionSamplesUrl)
.headers(getHeaders)
.asJson();
assertThat(samplesQueryResponse.getStatus(), is(equalTo(HttpStatus.OK.value())));
JSONObject payload = samplesQueryResponse.getBody().getObject();
JSONArray sampleList = payload.getJSONObject("_embedded").getJSONArray("samples");
assertThat(sampleList.length(), is(equalTo(testSamples.size())));
return submissionLocation;
}
public String submissionWithStudies(Map<String, String> rootRels) throws UnirestException, IOException {
Submission submission = Helpers.generateSubmission();
HttpResponse<JsonNode> submissionResponse = postSubmission(rootRels, submission);
String submissionLocation = submissionResponse.getHeaders().getFirst("Location");
Map<String, String> submissionRels = relsFromPayload(submissionResponse.getBody().getObject());
assertThat(submissionRels.get("studies"), notNullValue());
List<Study> testStudies = Helpers.generateTestClientStudies(2);
//add samples to the submission
for (Study study : testStudies) {
study.setSubmission(submissionLocation);
HttpResponse<JsonNode> studyResponse = Unirest.post(rootRels.get("studies:create"))
.headers(postHeaders)
.body(study)
.asJson();
assertThat(studyResponse.getStatus(), is(equalTo(HttpStatus.CREATED.value())));
}
//retrieve the samples
String submissionStudiesUrl = submissionRels.get("studies");
HttpResponse<JsonNode> studiesQueryResponse = Unirest.get(submissionStudiesUrl)
.headers(getHeaders)
.asJson();
assertThat(studiesQueryResponse.getStatus(), is(equalTo(HttpStatus.OK.value())));
JSONObject payload = studiesQueryResponse.getBody().getObject();
JSONArray studyList = payload.getJSONObject("_embedded").getJSONArray("studies");
assertThat(studyList.length(), is(equalTo(testStudies.size())));
return submissionLocation;
}
public Map<String, String> rootRels() throws UnirestException, IOException {
HttpResponse<JsonNode> response = Unirest.get(rootUri)
.headers(getHeaders)
.asJson();
assertThat(response.getStatus(), is(equalTo(HttpStatus.OK.value())));
JSONObject payload = response.getBody().getObject();
return relsFromPayload(payload);
}
public Map<String, String> relsFromPayload(JSONObject payload) throws IOException {
assertThat((Set<String>) payload.keySet(), hasItem("_links"));
JSONObject links = payload.getJSONObject("_links");
Map<String, String> rels = new HashMap<>();
for (Object key : links.keySet()) {
assertThat(key.getClass(), typeCompatibleWith(String.class));
Object linkJson = links.get(key.toString());
Link link = objectMapper.readValue(linkJson.toString(), Link.class);
rels.put((String) key, link.getHref());
}
return rels;
}
public static Map<String, String> createBasicAuthheaders () {
Map<String, String> h = new HashMap<>();
h.put("Authorization", "Basic " + Base64Coder.encodeString(DEFAULT_USER + ":" + DEFAULT_PASSWORD));
return h;
}
public static Map<String, String> createStandardGetHeader() {
Map<String, String> h = new HashMap<>();
h.put("accept", MediaTypes.HAL_JSON_VALUE);
h.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);
return h;
}
public static Map<String, String> createStandardPostHeader() {
Map<String, String> h = new HashMap<>();
h.putAll(createStandardGetHeader());
h.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);
return h;
}
public Map<String, String> getGetHeaders() {
return getHeaders;
}
public Map<String, String> getPostHeaders() {
return postHeaders;
}
}
|
package me.stefvanschie.buildinggame.timers;
import me.confuser.barapi.BarAPI;
import me.stefvanschie.buildinggame.Main;
import me.stefvanschie.buildinggame.managers.files.SettingsManager;
import me.stefvanschie.buildinggame.managers.messages.MessageManager;
import me.stefvanschie.buildinggame.managers.softdependencies.SDBarApi;
import me.stefvanschie.buildinggame.utils.Arena;
import me.stefvanschie.buildinggame.utils.GameState;
import me.stefvanschie.buildinggame.utils.plot.Plot;
import org.bukkit.GameMode;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
public class BuildTimer extends BukkitRunnable {
private int seconds;
private Arena arena;
public BuildTimer(int seconds, Arena arena) {
this.seconds = seconds;
this.arena = arena;
}
@Override
public void run() {
YamlConfiguration messages = SettingsManager.getInstance().getMessages();
if (seconds <= 0) {
//voten
for (Plot plot : arena.getPlots()) {
if (plot.getPlayerData() != null) {
Player player = plot.getPlayerData().getPlayer();
player.setGameMode(GameMode.CREATIVE);
if (SDBarApi.getInstance().isEnabled()) {
if (BarAPI.hasBar(player)) {
BarAPI.removeBar(player);
}
}
}
}
arena.getVoteTimer().runTaskTimer(Main.getInstance(), 20L, 20L);
arena.setState(GameState.VOTING);
this.cancel();
} else if (seconds % 60 == 0 || seconds == 30 || seconds == 15 || (seconds <= 10 && seconds >= 1)) {
for (Plot plot : arena.getPlots()) {
if (plot.getPlayerData() != null) {
Player player = plot.getPlayerData().getPlayer();
MessageManager.getInstance().send(player, messages.getString("buildingCountdown.message")
.replace("%seconds%", seconds + "")
.replaceAll("&", "§"));
}
}
}
seconds
}
public int getSeconds() {
return seconds;
}
}
|
package org.jkiss.utils;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
/**
* Some IO helper functions
*/
public final class IOUtils {
public static final int DEFAULT_BUFFER_SIZE = 16384;
public static void close(Closeable closeable)
{
try {
closeable.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void fastCopy(final InputStream src, final OutputStream dest) throws IOException {
}
public static void fastCopy(final InputStream src, final OutputStream dest, int bufferSize) throws IOException {
final ReadableByteChannel inputChannel = Channels.newChannel(src);
final WritableByteChannel outputChannel = Channels.newChannel(dest);
fastCopy(inputChannel, outputChannel, DEFAULT_BUFFER_SIZE);
}
public static void fastCopy(final ReadableByteChannel src, final WritableByteChannel dest, int bufferSize) throws IOException {
final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
while(src.read(buffer) != -1) {
buffer.flip();
dest.write(buffer);
buffer.compact();
}
buffer.flip();
while(buffer.hasRemaining()) {
dest.write(buffer);
}
}
public static void copyStream(
java.io.InputStream inputStream,
java.io.OutputStream outputStream)
throws IOException
{
copyStream(inputStream, outputStream, DEFAULT_BUFFER_SIZE);
}
/**
Read entire input stream and writes all data to output stream
then closes input and flushed output
*/
public static void copyStream(
java.io.InputStream inputStream,
java.io.OutputStream outputStream,
int bufferSize)
throws IOException
{
try {
byte[] writeBuffer = new byte[bufferSize];
for (int br = inputStream.read(writeBuffer); br != -1; br = inputStream.read(writeBuffer)) {
outputStream.write(writeBuffer, 0, br);
}
outputStream.flush();
}
finally {
// Close input stream
inputStream.close();
}
}
/**
Read entire input stream portion and writes it data to output stream
*/
public static void copyStreamPortion(
java.io.InputStream inputStream,
java.io.OutputStream outputStream,
int portionSize,
int bufferSize)
throws IOException
{
if (bufferSize > portionSize) {
bufferSize = portionSize;
}
byte[] writeBuffer = new byte[bufferSize];
int totalRead = 0;
while (totalRead < portionSize) {
int bytesToRead = bufferSize;
if (bytesToRead > portionSize - totalRead) {
bytesToRead = portionSize - totalRead;
}
int bytesRead = inputStream.read(writeBuffer, 0, bytesToRead);
outputStream.write(writeBuffer, 0, bytesRead);
totalRead += bytesRead;
}
// Close input stream
outputStream.flush();
}
/**
Read entire reader content and writes it to writer
then closes reader and flushed output.
*/
public static void copyText(
java.io.Reader reader,
java.io.Writer writer,
int bufferSize)
throws IOException
{
char[] writeBuffer = new char[bufferSize];
for (int br = reader.read(writeBuffer); br != -1; br = reader.read(writeBuffer)) {
writer.write(writeBuffer, 0, br);
}
// Close input stream
reader.close();
writer.flush();
}
public static int readStreamToBuffer(
java.io.InputStream inputStream,
byte[] buffer)
throws IOException
{
int totalRead = 0;
while (totalRead != buffer.length) {
int br = inputStream.read(buffer, totalRead, buffer.length - totalRead);
if (br == -1) {
break;
}
totalRead += br;
}
return totalRead;
}
public static String readLine(java.io.InputStream input)
throws IOException
{
StringBuilder linebuf = new StringBuilder();
for (int b = input.read(); b != '\n'; b = input.read()) {
if (b == -1) {
if (linebuf.length() == 0) {
return null;
} else {
break;
}
}
if (b != '\r') {
linebuf.append((char)b);
}
}
return linebuf.toString();
}
public static String readFullLine(java.io.InputStream input)
throws IOException
{
StringBuilder linebuf = new StringBuilder();
for (int b = input.read(); ; b = input.read()) {
if (b == -1) {
if (linebuf.length() == 0) {
return null;
} else {
break;
}
}
linebuf.append((char)b);
if (b == '\n') {
break;
}
}
return linebuf.toString();
}
}
|
package ol.style;
import ol.GwtOL3BaseTestCase;
import ol.OLFactory;
import ol.style.RegularShape;
import ol.style.RegularShapeOptions;
/**
*
* @author mribeiro
* @date 22/11/16.
*/
public class RegularShapeTest extends GwtOL3BaseTestCase {
public void testPoint() {
injectUrlAndTest(new TestWithInjection() {
@Override
public void test() {
RegularShapeOptions regularShapeOptions = OLFactory.createOptions();
regularShapeOptions.setAngle(Math.PI / 4);
regularShapeOptions.setRadius1(4);
regularShapeOptions.setRadius2(4);
regularShapeOptions.setRotation(Math.PI / 3);
regularShapeOptions.setRotateWithView(false);
assertNotNull(regularShapeOptions);
RegularShape regularShape = OLFactory.createRegularShape(regularShapeOptions);
assertNotNull(regularShape);
}
});
}
}
|
package net.yasme.android.entities;
import android.util.Log;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
import net.yasme.android.ui.AbstractYasmeActivity;
import net.yasme.android.encryption.MessageEncryption;
import net.yasme.android.storage.DatabaseConstants;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
@DatabaseTable(tableName = DatabaseConstants.CHAT_TABLE)
public class Chat implements Serializable {
@DatabaseField(columnName = DatabaseConstants.CHAT_ID, id = true)
private long id;
private List<User> participants;
@DatabaseField(columnName = DatabaseConstants.CHAT_STATUS)
private String status;
@DatabaseField(columnName = DatabaseConstants.CHAT_NAME)
private String name;
@DatabaseField(columnName = DatabaseConstants.OWNER, foreign = true)
private User owner;
private Timestamp lastModified;
private Timestamp created;
private String profilePicture;
@JsonIgnore
@ForeignCollectionField(columnName = DatabaseConstants.MESSAGES)
private Collection<Message> messages;
@JsonIgnore
private MessageEncryption aes;
/**
* Constructors *
*/
@JsonIgnore
public Chat(long id, User user, AbstractYasmeActivity activity) {
this.id = id;
this.participants = new ArrayList<User>();
this.messages = new ArrayList<Message>();
// setup Encryption for this chat
// TODO: DEVICE-ID statt USERID uebergeben
long creatorDevice = user.getId();
aes = new MessageEncryption(activity, this, creatorDevice, activity.getAccessToken());
//new Chat(id, participants, "", "", null, new ArrayList<Message>(), aes);
}
/**
* It is needed to set an id after calling this constructor!
*
* @param owner
* @param status
* @param name
*/
public Chat(User owner, String status, String name) {
new Chat(0, new ArrayList<User>(), status, name, owner, new ArrayList<Message>(), null);
}
public Chat(long id, List<User> participants, String status, String name,
User owner) {
new Chat(id, participants, status, name, owner, new ArrayList<Message>(), null);
}
public Chat() {
// ORMLite needs a no-arg constructor
}
public Chat(long id, List<User> participants, String status, String name, User owner,
Collection<Message> messages, MessageEncryption aes) {
this.id = id;
this.participants = participants;
this.status = status;
this.name = name;
this.owner = owner;
this.messages = messages;
if (aes != null) {
this.aes = aes;
} else {
//TODO aes = new MessageEncryption();
}
}
/**
* Getters *
*/
public long getId() {
return id;
}
public ArrayList<User> getParticipants() {
if (participants.isEmpty()) {
User dummy = new User("Dummy", 12);
participants.add(dummy);
Log.d(this.getClass().getSimpleName(), "Dummy-User hinzugefuegt");
}
return new ArrayList<User>(participants);
}
public String getStatus() {
return status;
}
public String getName() {
if (name == null) {
name = "";
}
if (name.length() <= 0) {
try {
int size = getParticipants().size();
for (int i = 0; i < size; i++) {
name += getParticipants().get(i).getName();
if(i < size - 1) {
name += ", ";
}
}
} catch (Exception e) {
}
}
return name;
}
public Timestamp getLastModified() {
return lastModified;
}
public Timestamp getCreated() {
return created;
}
public String getProfilePicture() {
return profilePicture;
}
public User getOwner() {
if (owner == null) {
owner = new User("Dummy", 12);
}
return owner;
}
public int getNumberOfParticipants() {
if (participants != null)
return participants.size();
return 0;
}
@JsonIgnore
public ArrayList<Message> getMessages() {
return new ArrayList<Message>(messages);
}
@JsonIgnore
public MessageEncryption getEncryption() {
if (aes == null)
System.out.println("[DEBUG] Chat wurde erstellt ohne gueltiges Encryption-Object --> Class: Chat.getEncryption())");
return aes;
}
/**
* Setters *
*/
public void setId(long id) {
this.id = id;
}
public void setParticipants(List<User> participants) {
this.participants = participants;
}
public void setStatus(String status) {
this.status = status;
}
public void setName(String name) {
this.name = name;
}
public void setOwner(User owner) {
this.owner = owner;
}
public void setEncryption(MessageEncryption aes) {
this.aes = aes;
}
public void setLastModified(Timestamp lastModified) {
this.lastModified = lastModified;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public void setProfilePicture(String profilePicture) {
this.profilePicture = profilePicture;
}
@JsonIgnore
public void setMessages(ArrayList<Message> messages) {
this.messages = messages;
}
/**
* Other Methods
*/
@JsonIgnore
public boolean isOwner(long userId) {
if (owner.getId() == userId) {
return true;
}
return false;
}
@JsonIgnore
public void addMessage(Message msg) {
if (messages == null) {
messages = new ArrayList<Message>();
}
messages.add(msg);
}
@Override
public String toString() {
return "Chat{" +
"id=" + id +
", participants=" + participants +
", status='" + status + '\'' +
", name='" + name + '\'' +
", owner=" + owner +
'}';
}
}
|
package org.zanata.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.util.Version;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.zanata.common.LocaleId;
import org.zanata.model.HGlossaryEntry;
import org.zanata.model.HGlossaryTerm;
import org.zanata.model.HLocale;
import org.zanata.webtrans.shared.rpc.HasSearchType.SearchType;
/**
*
* @author Alex Eng <a href="mailto:aeng@redhat.com">aeng@redhat.com</a>
*
**/
@Name("glossaryDAO")
@AutoCreate
@Scope(ScopeType.STATELESS)
public class GlossaryDAO extends AbstractDAOImpl<HGlossaryEntry, Long>
{
@In
private FullTextEntityManager entityManager;
public GlossaryDAO()
{
super(HGlossaryEntry.class);
}
public GlossaryDAO(Session session)
{
super(HGlossaryEntry.class, session);
}
public HGlossaryEntry getEntryById(Long id)
{
// TODO can't we just use Session.load() ?
Criteria cr = getSession().createCriteria(HGlossaryEntry.class);
cr.add(Restrictions.naturalId().set("id", id));
cr.setCacheable(true).setComment("GlossaryDAO.getEntryById");
return (HGlossaryEntry) cr.uniqueResult();
}
@SuppressWarnings("unchecked")
public List<HGlossaryEntry> getEntriesByLocaleId(LocaleId locale)
{
Query query = getSession().createQuery("from HGlossaryEntry as e WHERE e.id IN (SELECT t.glossaryEntry.id FROM HGlossaryTerm as t WHERE t.locale.localeId= :localeId)");
query.setParameter("localeId", locale);
query.setComment("GlossaryDAO.getEntriesByLocaleId");
return query.list();
}
@SuppressWarnings("unchecked")
public List<HGlossaryEntry> getEntries()
{
Query query = getSession().createQuery("from HGlossaryEntry");
query.setComment("GlossaryDAO.getEntries");
return query.list();
}
public HGlossaryTerm getTermByEntryAndLocale(Long glossaryEntryId, LocaleId locale)
{
Query query = getSession().createQuery("from HGlossaryTerm as t WHERE t.locale.localeId= :locale AND glossaryEntry.id= :glossaryEntryId");
query.setParameter("locale", locale);
query.setParameter("glossaryEntryId", glossaryEntryId);
query.setComment("GlossaryDAO.getTermByEntryAndLocale");
return (HGlossaryTerm) query.uniqueResult();
}
@SuppressWarnings("unchecked")
public List<HGlossaryTerm> getTermByGlossaryEntryId(Long glossaryEntryId)
{
Query query = getSession().createQuery("from HGlossaryTerm as t WHERE t.glossaryEntry.id= :glossaryEntryId");
query.setParameter("glossaryEntryId", glossaryEntryId);
query.setComment("GlossaryDAO.getTermByGlossaryEntryId");
return query.list();
}
/* @formatter:off */
public HGlossaryEntry getEntryBySrcLocaleAndContent(LocaleId localeid, String content)
{
Query query = getSession().createQuery("from HGlossaryEntry as e " +
"WHERE e.srcLocale.localeId= :localeid AND e.id IN " +
"(SELECT t.glossaryEntry.id FROM HGlossaryTerm as t " +
"WHERE t.locale.localeId=e.srcLocale.localeId " +
"AND t.content= :content)");
query.setParameter("localeid", localeid);
query.setParameter("content", content);
query.setComment("GlossaryDAO.getEntryBySrcLocaleAndContent");
return (HGlossaryEntry) query.uniqueResult();
}
/* @formatter:on */
@SuppressWarnings("unchecked")
public List<HGlossaryTerm> findByIdList(List<Long> idList)
{
if (idList == null || idList.isEmpty())
{
return new ArrayList<HGlossaryTerm>();
}
Query query = getSession().createQuery("FROM HGlossaryTerm WHERE id in (:idList)");
query.setParameterList("idList", idList);
query.setCacheable(false).setComment("GlossaryDAO.getByIdList");
return query.list();
}
public List<Object[]> getSearchResult(String searchText, SearchType searchType, LocaleId srcLocale, final int maxResult) throws ParseException
{
String queryText;
switch (searchType)
{
case RAW:
queryText = searchText;
break;
case FUZZY:
// search by N-grams
queryText = QueryParser.escape(searchText);
break;
case EXACT:
queryText = "\"" + QueryParser.escape(searchText) + "\"";
break;
default:
throw new RuntimeException("Unknown query type: " + searchType);
}
if (StringUtils.isEmpty(queryText))
{
return new ArrayList<Object[]>();
}
QueryParser parser = new QueryParser(Version.LUCENE_29, "content", new StandardAnalyzer(Version.LUCENE_29));
org.apache.lucene.search.Query textQuery = parser.parse(queryText);
FullTextQuery ftQuery = entityManager.createFullTextQuery(textQuery, HGlossaryTerm.class);
ftQuery.enableFullTextFilter("glossaryLocaleFilter").setParameter("locale", srcLocale);
ftQuery.setProjection(FullTextQuery.SCORE, FullTextQuery.THIS);
@SuppressWarnings("unchecked")
List<Object[]> matches = ftQuery.setMaxResults(maxResult).getResultList();
return matches;
}
public Map<HLocale, Integer> getGlossaryTermCountByLocale()
{
Map<HLocale, Integer> result = new HashMap<HLocale, Integer>();
Query query = getSession().createQuery("select term.locale, count(*) from HGlossaryTerm term GROUP BY term.locale.localeId");
query.setComment("GlossaryDAO.getGlossaryTermCountByLocale");
@SuppressWarnings("unchecked")
List<Object[]> list = query.list();
for (Object[] obj : list)
{
HLocale locale = (HLocale) obj[0];
Long count = (Long) obj[1];
int countInt = count == null ? 0 : count.intValue();
result.put(locale, countInt);
}
return result;
}
public int deleteAllEntries()
{
Query query = getSession().createQuery("Delete HTermComment");
query.setComment("GlossaryDAO.deleteAllEntries-comments");
query.executeUpdate();
Query query2 = getSession().createQuery("Delete HGlossaryTerm");
query2.setComment("GlossaryDAO.deleteAllEntries-terms");
int rowCount = query2.executeUpdate();
Query query3 = getSession().createQuery("Delete HGlossaryEntry");
query3.setComment("GlossaryDAO.deleteAllEntries-entries");
query3.executeUpdate();
return rowCount;
}
public int deleteAllEntries(LocaleId targetLocale)
{
Query query = getSession().createQuery("Delete HTermComment c WHERE c.glossaryTerm.id IN (SELECT t.id FROM HGlossaryTerm t WHERE t.locale.localeId= :locale)");
query.setParameter("locale", targetLocale);
query.setComment("GlossaryDAO.deleteLocaleEntries-comments");
query.executeUpdate();
Query query2 = getSession().createQuery("Delete HGlossaryTerm t WHERE t.locale IN (SELECT l FROM HLocale l WHERE localeId= :locale)");
query2.setParameter("locale", targetLocale);
query2.setComment("GlossaryDAO.deleteLocaleEntries-terms");
int rowCount = query2.executeUpdate();
Query query3 = getSession().createQuery("Delete HGlossaryEntry e WHERE size(e.glossaryTerms) = 0");
query3.setComment("GlossaryDAO.deleteLocaleEntries-entries");
query3.executeUpdate();
return rowCount;
}
}
|
package whelk.export.servlet;
import org.codehaus.jackson.map.ObjectMapper;
import whelk.Document;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.sql.*;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import io.prometheus.client.Counter;
public class GetRecord
{
private final static String IDENTIFIER_PARAM = "identifier";
private final static String FORMAT_PARAM = "metadataPrefix";
private static final Counter failedRequests = Counter.build()
.name("oaipmh_failed_getrecord_requests_total").help("Total failed GetRecord requests.")
.labelNames("error").register();
/**
* Verifies the integrity of a OAI-PMH request with the verb 'GetRecord' and sends a proper response.
*/
public static void handleGetRecordRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException, XMLStreamException, SQLException
{
// Parse and verify the parameters allowed for this request
String identifierUri = request.getParameter(IDENTIFIER_PARAM); // required
String metadataPrefix = request.getParameter(FORMAT_PARAM); // required
if (ResponseCommon.errorOnExtraParameters(request, response, IDENTIFIER_PARAM, FORMAT_PARAM))
return;
if (metadataPrefix == null)
{
failedRequests.labels(OaiPmh.OAIPMH_ERROR_BAD_ARGUMENT).inc();
ResponseCommon.sendOaiPmhError(OaiPmh.OAIPMH_ERROR_BAD_ARGUMENT,
"metadataPrefix argument required.", request, response);
return;
}
if (identifierUri == null)
{
failedRequests.labels(OaiPmh.OAIPMH_ERROR_BAD_ARGUMENT).inc();
ResponseCommon.sendOaiPmhError(OaiPmh.OAIPMH_ERROR_BAD_ARGUMENT,
"identifier argument required.", request, response);
return;
}
String id = null;
try (Connection dbconn = OaiPmh.s_postgreSqlComponent.getConnection();
PreparedStatement preparedStatement = prepareSameAsStatement(dbconn, identifierUri);
ResultSet resultSet = preparedStatement.executeQuery())
{
if (resultSet.next())
id = resultSet.getString("id");
}
try (Connection dbconn = OaiPmh.s_postgreSqlComponent.getConnection();
PreparedStatement preparedStatement = prepareMatchingDocumentStatement(dbconn, id);
ResultSet resultSet = preparedStatement.executeQuery())
{
if (!resultSet.next())
{
failedRequests.labels(OaiPmh.OAIPMH_ERROR_ID_DOES_NOT_EXIST).inc();
ResponseCommon.sendOaiPmhError(OaiPmh.OAIPMH_ERROR_ID_DOES_NOT_EXIST, "", request, response);
return;
}
ObjectMapper mapper = new ObjectMapper();
String data = resultSet.getString("data");
ZonedDateTime modified = ZonedDateTime.ofInstant(resultSet.getTimestamp("modified").toInstant(), ZoneOffset.UTC);
HashMap datamap = mapper.readValue(data, HashMap.class);
Document document = new Document(datamap);
// Expanded format requested, we need to build trees.
if (metadataPrefix.endsWith(OaiPmh.FORMAT_EXPANDED_POSTFIX))
{
List<String> nodeDatas = new LinkedList<String>();
HashSet<String> visitedIDs = new HashSet<String>();
ListRecordTrees.ModificationTimes modificationTimes = new ListRecordTrees.ModificationTimes();
modificationTimes.earliestModification = modified;
modificationTimes.latestModification = modified;
ListRecordTrees.addNodeAndSubnodesToTree(id, visitedIDs, nodeDatas, modificationTimes);
// Value of modificationTimes.latestModification will have changed during tree building.
modified = modificationTimes.latestModification;
document = ListRecordTrees.mergeDocument(id, nodeDatas);
}
// Build the xml response feed
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
xmlOutputFactory.setProperty("escapeCharacters", false); // Inline xml must be left untouched.
XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(response.getOutputStream());
ResponseCommon.writeOaiPmhHeader(writer, request, true);
writer.writeStartElement("GetRecord");
ResponseCommon.emitRecord(resultSet, document, writer, metadataPrefix, false);
writer.writeEndElement(); // GetRecord
ResponseCommon.writeOaiPmhClose(writer, request);
}
}
private static PreparedStatement prepareMatchingDocumentStatement(Connection dbconn, String id)
throws SQLException
{
String tableName = OaiPmh.configuration.getProperty("sqlMaintable");
// Construct the query
String selectSQL = "SELECT data, collection, modified, deleted, data#>>'{@graph,1,heldBy,@id}' AS sigel FROM " +
tableName + " WHERE id = ? AND collection <> 'definitions' ";
PreparedStatement preparedStatement = dbconn.prepareStatement(selectSQL);
preparedStatement.setString(1, id);
return preparedStatement;
}
private static PreparedStatement prepareSameAsStatement(Connection dbconn, String id)
throws SQLException
{
String tableName = OaiPmh.configuration.getProperty("sqlMaintable");
String sql = "SELECT id FROM " + tableName + "__identifiers WHERE iri = ?";
PreparedStatement preparedStatement = dbconn.prepareStatement(sql);
preparedStatement.setString(1, id);
return preparedStatement;
}
}
|
package pro.taskana;
/**
* This class encapsulates key - domain pairs for identification of workbaskets.
*
* @author bbr
*/
public class KeyDomain {
private String key;
private String domain;
public KeyDomain(String key, String domain) {
this.key = key;
this.domain = domain;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("KeyDomain [key=");
builder.append(key);
builder.append(", domain=");
builder.append(domain);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((domain == null) ? 0 : domain.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
KeyDomain other = (KeyDomain) obj;
if (domain == null) {
if (other.domain != null) {
return false;
}
} else if (!domain.equals(other.domain)) {
return false;
}
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
return true;
}
}
|
package com.litle.magento.selenium;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.PauseAction;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.events.WebDriverEventListener;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BaseTestCase {
private static final String WORKSPACE = System.getenv("WORKSPACE") == null ? System.getProperty("user.home") : System.getenv("WORKSPACE");
private static final String SCREENSHOT_DIR = WORKSPACE + "/test/screenshots/";
private static final String HOST = System.getenv("MAGENTO_HOST");
private static final String FIREFOX_PATH = System.getenv("FIREFOX_PATH");
private static final String MAGENTO_DB_NAME = System.getenv("MAGENTO_DB_NAME");
private static final String MAGENTO_DB_USER = System.getenv("MAGENTO_DB_USER");
private static final String MAGENTO_DB_PASS = System.getenv("MAGENTO_DB_PASS");
private static final String MAGENTO_HOME = System.getenv("MAGENTO_HOME");
private static final String CONTEXT = System.getenv("MAGENTO_CONTEXT");
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final long DEFAULT_TIMEOUT = 15;
private static String JDBC_URL;
private static Connection conn;
static Statement stmt;
static EventFiringWebDriver driver;
static WebDriverWait wait;
@BeforeClass
public static void setupSuite() throws Exception {
FileUtils.deleteDirectory(new File(MAGENTO_HOME+"/var/cache"));
FileUtils.deleteDirectory(new File(MAGENTO_HOME+"/var/log"));
FileUtils.deleteDirectory(new File(SCREENSHOT_DIR));
JDBC_URL = "jdbc:mysql://localhost:3306/" + MAGENTO_DB_NAME;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(JDBC_URL, MAGENTO_DB_USER, MAGENTO_DB_PASS);
stmt = conn.createStatement();
stmt.executeUpdate("delete from core_resource where code = 'palorus_setup'");
stmt.executeUpdate("delete from core_resource where code = 'lecheck_setup'");
stmt.executeUpdate("delete from core_resource where code = 'creditcard_setup'");
stmt.executeUpdate("delete from core_config_data where path like 'payment/CreditCard/%'");
stmt.executeUpdate("delete from core_config_data where path like 'payment/LEcheck/%'");
stmt.executeUpdate("delete from catalog_eav_attribute where attribute_id = (select attribute_id from eav_attribute where attribute_code = 'litle_subscription')");
stmt.executeUpdate("delete from `eav_entity_attribute` where attribute_id = (select attribute_id from eav_attribute where attribute_code = 'litle_subscription')");
stmt.executeUpdate("delete from eav_attribute where attribute_code = 'litle_subscription'");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/active','1')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/title','Credit Card')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/user','USER')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/password','PASSWORD')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/merchant_id','(''USD''=>''101'')')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/order_status','processing')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/payment_action','authorize')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/url','https:
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/paypage_enable','0')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/vault_enable','0')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/paypage_url',null)");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/paypage_id',null)");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/timeout',null)");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/LEcheck/active','0')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/LEcheck/title',null)");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/LEcheck/payment_action','authorize')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/LEcheck/order_status','processing')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/proxy','iwp1.lowell.litle.com:8080')");
stmt.executeUpdate("INSERT INTO core_config_data (scope,scope_id,path,value) VALUES ('default',0,'payment/CreditCard/cctypes','AE,DC,VI,MC,DI,JCB')");
}
@Before
public void before() throws Exception {
System.setProperty("webdriver.firefox.bin",FIREFOX_PATH);
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("Magento");
profile.setEnableNativeEvents(true);
driver = new EventFiringWebDriver(new FirefoxDriver(profile));
wait = new WebDriverWait(driver, DEFAULT_TIMEOUT);
WebDriverEventListener errorListener = new AbstractWebDriverEventListener() {
@Override
public void onException(Throwable throwable, WebDriver driver) {
String testClass = "";
String testMethod = "";
for(StackTraceElement stackTrace : throwable.getStackTrace()) {
String className = stackTrace.getClassName();
if(className.endsWith("Tests") && className.startsWith("com.litle.magento.selenium")) {
testClass = className;
testMethod = stackTrace.getMethodName();
}
}
Calendar c = Calendar.getInstance();
takeScreenshot(testClass + "." + testMethod + " " + sdf.format(c.getTime()) + "-" + driver.getTitle() + "-" + String.valueOf(System.currentTimeMillis()));
}
private void takeScreenshot(String screenshotName) {
File tempFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(tempFile, new File(SCREENSHOT_DIR + screenshotName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
};
driver.register(errorListener);
stmt.executeUpdate("delete from litle_failed_transactions");
stmt.executeUpdate("delete from litle_customer_insight");
}
@AfterClass
public static void tearDownSuite() throws Exception {
stmt.close();
conn.close();
}
@After
public void after() {
driver.quit();
}
static void iAmDoingCCOrEcheckTransaction() throws Exception {
stmt.executeUpdate("update core_config_data set value='https:
stmt.executeUpdate("update core_config_data set value='' where path='payment/CreditCard/proxy'");
stmt.executeUpdate("update core_config_data set value='1' where path='payment/LEcheck/active'");
stmt.executeUpdate("update core_config_data set value='1' where path='payment/CreditCard/active'");
stmt.executeUpdate("update core_config_data set value='JENKINS' where path='payment/CreditCard/user'");
stmt.executeUpdate("update core_config_data set value='PayPageTransactions' where path='payment/CreditCard/password'");
stmt.executeUpdate("update core_config_data set value='(\"USD\"=>\"101\",\"GBP\"=>\"102\")' where path='payment/CreditCard/merchant_id'");
stmt.executeUpdate("update core_config_data set value='AE,DC,VI,MC,DI,JCB' where path='payment/CreditCard/cctypes'");
stmt.executeUpdate("update core_config_data set value='Checking,Savings,Corporate,Corp Savings' where path='payment/LEcheck/accounttypes'");
stmt.executeUpdate("update core_config_data set value='Litle ECheck' where path='payment/LEcheck/title'");
stmt.executeUpdate("update core_config_data set value='Litle Credit Card' where path='payment/CreditCard/title'");
stmt.executeUpdate("update core_config_data set value='iwp1.lowell.litle.com:8080' where path='payment/CreditCard/proxy'");
stmt.executeUpdate("delete from sales_flat_order");
stmt.executeUpdate("delete from sales_flat_quote");
}
static void iAmDoingLPaypalTransaction() throws Exception {
stmt.executeUpdate("update core_config_data set value='https:
stmt.executeUpdate("update core_config_data set value='JENKINS' where path='payment/CreditCard/user'");
stmt.executeUpdate("update core_config_data set value='LPaypalTransactions' where path='payment/CreditCard/password'");
stmt.executeUpdate("update core_config_data set value='(\"USD\"=>\"101\",\"GBP\"=>\"102\")' where path='payment/CreditCard/merchant_id'");
stmt.executeUpdate("update core_config_data set value='iwp1.lowell.litle.com:8080' where path='payment/CreditCard/proxy'");
// for Paypal
stmt.executeUpdate("update core_config_data set value='1' where path='payment/paypal_express/active'");
stmt.executeUpdate("update core_config_data set value='1' where path='payment/paypal_express/skip_order_review_step'");
stmt.executeUpdate("update core_config_data set value='Order' where path='payment/paypal_express/payment_action'");
stmt.executeUpdate("update core_config_data set value='1' where path='paypal/wpp/sandbox_flag'");
stmt.executeUpdate("update core_config_data set value='1' where path='payment/LPaypal/active'");
stmt.executeUpdate("delete from sales_flat_order");
stmt.executeUpdate("delete from sales_flat_quote");
}
static void iAmDoingNonPaypageTransaction() throws Exception {
stmt.executeUpdate("update core_config_data set value='0' where path='payment/CreditCard/paypage_enable'");
}
static void iAmDoingPaypageTransaction() throws Exception {
stmt.executeUpdate("update core_config_data set value='1' where path='payment/CreditCard/paypage_enable'");
stmt.executeUpdate("update core_config_data set value='a2y4o6m8k0' where path='payment/CreditCard/paypage_id'");
stmt.executeUpdate("update core_config_data set value='https://request-prelive.np-securepaypage-litle.com' where path='payment/CreditCard/paypage_url'");
}
static void iAmDoingStoredCards() throws Exception {
stmt.executeUpdate("update core_config_data set value='1' where path='payment/CreditCard/vault_enable'");
}
void iAmDoingLitleAuth() throws Exception {
stmt.executeUpdate("update core_config_data set value='authorize' where path='payment/CreditCard/payment_action'");
stmt.executeUpdate("update core_config_data set value='authorize' where path='payment/LEcheck/payment_action'");
}
void iAmDoingLitleSale() throws Exception {
stmt.executeUpdate("update core_config_data set value='authorize_capture' where path='payment/CreditCard/payment_action'");
stmt.executeUpdate("update core_config_data set value='authorize_capture' where path='payment/LEcheck/payment_action'");
}
void iAmDoingLPaypalAuth() throws Exception {
stmt.executeUpdate("update core_config_data set value='authorize' where path='payment/LPaypal/payment_action'");
}
void iAmDoingLPaypalSale() throws Exception {
stmt.executeUpdate("update core_config_data set value='authorize_capture' where path='payment/LPaypal/payment_action'");
}
void iAmLoggedInAsWithThePassword(String username, String password) throws Exception {
driver.get("http://"+HOST+"/" + CONTEXT + "/index.php/");
// if(driver.findElements(By.linkText("Log Out")).size() != 0){
// driver.findElement(By.linkText("Log Out")).click();
waitFor(By.linkText("Log In"));
//Login
driver.findElement(By.linkText("Log In")).click();
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(password);
Thread.sleep(1000L);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(username);
Thread.sleep(1000L);
driver.findElement(By.id("send2")).click(); //click login button
waitForCssVisible("html body.customer-account-index div.wrapper div.page div.main-container div.main div.col-main div.my-account div.dashboard div.page-title h1");
}
WebElement waitForIdVisible(String id) {
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
}
WebElement waitForCssVisible(String css) {
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(css)));
}
WebElement waitForClassVisible(String className) {
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(className)));
}
WebElement waitFor(By locator) {
return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
void iHaveInMyCart(String productName) {
waitFor(By.id("search"));
//Find the item
//Enter search text
WebElement e = driver.findElement(By.id("search"));
e.clear();
e.sendKeys(productName);
//Hit the search button
e = driver.findElement(By.className("form-search"));
e = e.findElement(By.tagName("button"));
e.click();
waitForCssVisible(".btn-cart");
//Add to cart
e = driver.findElement(By.cssSelector(".btn-cart"));
e.click();
waitForCssVisible(".btn-proceed-checkout");
}
void iLogOutAsAdministrator() {
driver.findElement(By.linkText("Log Out")).click();
waitFor(By.linkText("Forgot your password?"));
}
void iClickOnTheTopRowInOrders() throws Exception {
WebElement ordersGrid = driver.findElement(By.id("sales_order_grid_table"));
WebElement topRow = ordersGrid.findElement(By.tagName("tbody")).findElement(By.tagName("tr"));
//WebElement topRow = driver.findElement(By.xpath("/html/body/div/div[3]/div/div[3]/div/div[2]/div/table/tbody/tr[1]"));
String title = topRow.getAttribute("title");
driver.get(title);
waitFor(By.className("head-billing-address"));
waitFor(By.className("head-sales-order"));
}
void iClickOnTheTopRowInCustomerInsights() {
WebElement table = driver.findElement(By.id("my_custom_tab_table"));
WebElement tbody = table.findElement(By.tagName("tbody"));
List<WebElement> rows = tbody.findElements(By.tagName("tr"));
assertTrue(rows.size() > 0);
WebElement topRow = rows.get(0);
String title = topRow.getAttribute("title");
driver.get(title);
waitFor(By.id("sales_order_view"));
}
void iAddTheTopRowInProductsToTheOrder() {
// WebElement topRow = driver.findElement(By.xpath("/html/body/div/div[3]/div/form/div[5]/div/div/table/tbody/tr/td[2]/div[2]/div/div[2]/div/div/div/table/tbody/tr"));
// topRow.click();
// waitFor(By.cssSelector("html body#html-body.adminhtml-sales-order-create-index div.wrapper div#anchor-content.middle div#page:main-container form#edit_form div#order-data div div.page-create-order table tbody tr td.main-col div#order-items div div.entry-edit div table tbody tr td.a-right button .scalable"));
WebElement productsTable = driver.findElement(By.id("sales_order_create_search_grid_table"));
productsTable.findElement(By.tagName("tbody")).findElement(By.tagName("tr")).click(); //Clicking the top row sets the qtyToAdd to 1
WebElement e = driver.findElement(By.id("order-search"));
e = e.findElement(By.className("entry-edit-head"));
e = e.findElement(By.tagName("button"));
e.click();
waitForIdVisible("order-items");
}
void iClickAddProducts() {
WebElement e = driver.findElement(By.id("order-items"));
e = e.findElement(By.tagName("button"));
e.click();
waitForClassVisible("head-catalog-product");
}
void iClickOnTheCustomerWithEmail(String email) {
if("New Order / Orders / Sales / Magento Admin".equals(driver.getTitle())) {
WebElement e = driver.findElement(By.id("sales_order_create_customer_grid_table"));
e = e.findElement(By.tagName("tbody"));
List<WebElement> rows = e.findElements(By.tagName("tr"));
WebElement rowToClick = null;
for(WebElement row : rows) {
WebElement emailCol = row.findElements(By.tagName("td")).get(2);
String colValue = emailCol.getText().trim();
if(colValue.equals(email)) {
rowToClick = row;
}
}
assertNotNull("Couldn't find customer with email " + email, rowToClick);
rowToClick.click();
waitFor(By.id("submit_order_top_button"));
}
else {
WebElement e = driver.findElement(By.id("customerGrid_table"));
e = e.findElement(By.tagName("tbody"));
List<WebElement> rows = e.findElements(By.tagName("tr"));
String url = null;
for(WebElement row : rows) {
WebElement emailCol = row.findElements(By.tagName("td")).get(3);
String colName = emailCol.getText().trim();
if(colName.equals(email)) {
url = row.getAttribute("title");
}
}
assertNotNull("Couldn't find customer with email " + email, url);
driver.get(url);
waitFor(By.id("customer_info_tabs"));
}
}
//"customer_info_tabs","Click here to view Litle & Co. Customer Insight"
void iClickOnTab(String tabsId, String linkTitleToFollow) {
WebElement e = driver.findElement(By.id(tabsId));
WebElement url = null;
List<WebElement> links = e.findElements(By.tagName("a"));
for(WebElement link : links) {
if(link.getAttribute("title").trim().equals(linkTitleToFollow)) {
url = link;
}
}
assertNotNull("Couldn't find link titled " + linkTitleToFollow + " on tab " + tabsId, url);
url.click();
}
//iShouldSeeInTheColumnInCustomerInsights("Affluent","Affluence");
void iShouldSeeInTheColumnInCustomerInsights(String expectedValue,String columnName) {
//Find the column with the correct name
WebElement e = driver.findElement(By.id("my_custom_tab_table"));
List<WebElement> headings = e.findElements(By.tagName("th"));
int correctHeadingIndex = -1;
for(int i = 0; i < headings.size(); i++) {
WebElement heading = headings.get(i);
String columnHeading = heading.getText();
if(columnName.equals(columnHeading)) {
correctHeadingIndex = i;
}
}
assertTrue("Couldn't find column named " + columnName + " on customer insights", correctHeadingIndex != -1);
List<WebElement> cols = e.findElement(By.tagName("tbody")).findElements(By.tagName("td"));
WebElement columnn = cols.get(correctHeadingIndex);
assertEquals(expectedValue, columnn.getText().trim());
}
void iView(String menu, String subMenu)
{
WebElement e = driver.findElement(By.id("nav"));
WebElement firstMenuElement = e.findElement(By.linkText(menu));
Actions mouseOver = new Actions(driver);
mouseOver.moveToElement(firstMenuElement).build().perform();
WebElement secondMenuElement = e.findElement(By.linkText(subMenu));
secondMenuElement.click();
waitFor(By.className("content-header"));
e = driver.findElement(By.className("content-header"));
e = e.findElement(By.tagName("h3"));
assertEquals(subMenu, e.getText());
if("Orders".equals(subMenu)) {
waitFor(By.id("sales_order_grid"));
} else if("Manage Customers".equals(subMenu)) {
waitFor(By.id("customerGrid"));
} else if("Transactions".equals(subMenu)) {
waitFor(By.id("order_transactions"));
}
}
void iAmLoggedInAsAnAdministrator() {
//Get to login screen
driver.get("http://"+HOST+"/" + CONTEXT + "/index.php/admin");
waitForIdVisible("username");
//Enter username
WebElement e = driver.findElement(By.id("username"));
e.clear();
e.sendKeys("admin");
//Enter password
e = driver.findElement(By.id("login"));
e.clear();
e.sendKeys("LocalMagentoAdmin1");
e.submit();
waitForClassVisible("link-logout");
}
void iAccessAReportingUrl(String lastBitOfUrl) {
driver.get("http://"+HOST+"/" + CONTEXT + "/index.php" + lastBitOfUrl);
//Enter username
WebElement e = driver.findElement(By.id("username"));
e.clear();
e.sendKeys("admin");
//Enter password
e = driver.findElement(By.id("login"));
e.clear();
e.sendKeys("LocalMagentoAdmin1");
e.submit();
}
private void goThroughBillingAndShipping(){
//And I press "Continue"
WebElement e = driver.findElement(By.id("co-billing-form"));
e = e.findElement(By.tagName("button"));
e.click();
waitForIdVisible("co-shipping-method-form");
// And I press the "3rd" continue button - Shipping Method
e = driver.findElement(By.id("co-shipping-method-form"));
e = e.findElement(By.tagName("button"));
e.click();
waitForIdVisible("co-payment-form");
}
private void baseCheckoutHelper(String ccType, String creditCardNumber, boolean saveCreditCard) {
//And I press "Proceed to Checkout"
WebElement e = driver.findElement(By.className("btn-proceed-checkout"));
e.click();
waitForIdVisible("co-billing-form");
// go through Billing and Shipping sections
goThroughBillingAndShipping();
//And I choose "CreditCard"
e = driver.findElement(By.id("p_method_creditcard"));
e.click();
waitForIdVisible("creditcard_cc_type");
if(creditCardNumber.startsWith("Stored")) {
iSelectFromSelect(creditCardNumber, "creditcard_cc_vaulted");
}
else {
//And I select "Visa" from "Credit Card Type"
iSelectFromSelect(ccType, "creditcard_cc_type");
// And I put in "Credit Card Number" with "4000162019882000"
e = driver.findElement(By.id("creditcard_cc_number"));
e.clear();
e.sendKeys(creditCardNumber);
}
// And I select "9" from "Expiration Date"
iSelectFromSelect("09 - September", "creditcard_expiration");
// And I select "2012" from "creditcard_expiration_yr"
iSelectFromSelect("2015", "creditcard_expiration_yr");
// And I put in "Card Verification Number" with "123"
e = driver.findElement(By.id("creditcard_cc_cid"));
e.clear();
e.sendKeys("123");
if(saveCreditCard) {
e = driver.findElement(By.id("creditcard_cc_should_save"));
e.click();
}
// And I press the "4th" continue button
e = driver.findElement(By.id("payment-buttons-container"));
e = e.findElement(By.tagName("button"));
e.click();
waitForIdVisible("checkout-step-review");
// And I press "Place Order"
e = driver.findElement(By.id("review-buttons-container"));
e = e.findElement(By.tagName("button"));
e.click();
}
private void loginPaypalAndConfirm(String account, String password){
// I login paypal
String cssStr = "html body.ng-scope section.login div.inputField.emailField.confidential > input";
WebElement e = driver.findElement(By.cssSelector(cssStr));
e.clear();
e.sendKeys(account);
cssStr = "html body.ng-scope section.login div.inputField.passwordField.confidential > input";
e = driver.findElement(By.cssSelector(cssStr));
e.clear();
e.sendKeys(password);
e = driver.findElement(By.cssSelector(".btn.full.loginBtn"));
e.click();
waitForIdVisible("confirmButtonTop");
// And I confirm the payment detail on Paypal website
e = driver.findElement(By.id("confirmButtonTop"));
e.click();
}
private void onepageLPaypalCheckoutHelper(String account, String password){
// select the Paypal express checkout method
WebElement e = driver.findElement(By.id("p_method_paypal_express"));
e.click();
waitForClassVisible("form-alt");
// And I press the "4th" continue button
e = driver.findElement(By.id("payment-buttons-container"));
e = e.findElement(By.tagName("button"));
e.click();
// change waitfor element due to new Paypal sandbox page
waitForIdVisible("forgot_password_link");
// login Paypal website and confirm the payment
loginPaypalAndConfirm(account, password);
}
void iFailCheckOutWith(String ccType, String creditCardNumber, String modalErrorMessage) throws InterruptedException {
baseCheckoutHelper(ccType, creditCardNumber, false);
Thread.sleep(2000);
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
assertTrue(alertText, alertText.contains(modalErrorMessage));
alert.accept();
}
void iCheckOutWith(String ccType, String creditCardNumber) {
iCheckOutWith(ccType, creditCardNumber, false);
}
void iCheckOutWith(String ccType, String creditCardNumber, boolean saveCreditCard) {
baseCheckoutHelper(ccType, creditCardNumber, saveCreditCard);
// Then I should see "Thank you for your purchase"
waitForCssVisible("html body.checkout-onepage-success div.wrapper div.page div.main-container div.main div.col-main p a");
WebElement e = driver.findElement(By.className("col-main"));
e = e.findElement(By.className("sub-title"));
assertEquals("Thank you for your purchase!",e.getText());
}
void iCheckOutWithEcheck(String routingNumber, String accountNumber, String accountType) {
//And I press "Proceed to Checkout"
WebElement e = driver.findElement(By.className("btn-proceed-checkout"));
e.click();
waitForIdVisible("co-billing-form");
//And I press "Continue"
e = driver.findElement(By.id("co-billing-form"));
e = e.findElement(By.tagName("button"));
e.click();
waitForIdVisible("co-shipping-method-form");
// And I press the "3rd" continue button - Shipping Method
e = driver.findElement(By.id("co-shipping-method-form"));
e = e.findElement(By.tagName("button"));
e.click();
waitForIdVisible("co-payment-form");
//And I choose "Echeck"
e = driver.findElement(By.id("p_method_lecheck"));
e.click();
waitForIdVisible("lecheck_echeck_routing_number");
e = driver.findElement(By.id("lecheck_echeck_routing_number"));
e.clear();
e.sendKeys(routingNumber);
e = driver.findElement(By.id("lecheck_echeck_bank_acct_num"));
e.clear();
e.sendKeys(accountNumber);
iSelectFromSelect(accountType, "lecheck_echeck_account_type");
// And I press the "4th" continue button
e = driver.findElement(By.id("payment-buttons-container"));
e = e.findElement(By.tagName("button"));
e.click();
waitForIdVisible("checkout-step-review");
// And I press "Place Order"
e = driver.findElement(By.id("review-buttons-container"));
e = e.findElement(By.tagName("button"));
e.click();
// Then I should see "Thank you for your purchase"
waitForCssVisible("html body.checkout-onepage-success div.wrapper div.page div.main-container div.main div.col-main p a");
e = driver.findElement(By.className("col-main"));
e = e.findElement(By.className("sub-title"));
assertEquals("Thank you for your purchase!",e.getText());
}
void iCheckOutWithLPaypal(String account, String password) {
//And I press "Proceed to Checkout"
WebElement e = driver.findElement(By.className("btn-proceed-checkout"));
e.click();
waitForIdVisible("co-billing-form");
// go through Billing and Shipping sections
goThroughBillingAndShipping();
// finish Paypal checkout flow
onepageLPaypalCheckoutHelper(account, password);
// Then I should see "Thank you for your purchase"
waitForCssVisible("html body.checkout-onepage-success div.wrapper div.page div.main-container div.main div.col-main p a");
e = driver.findElement(By.className("col-main"));
e = e.findElement(By.className("sub-title"));
assertEquals("Thank you for your purchase!",e.getText());
}
void iCheckOutInCartWithLPaypal(String account, String password) {
//And I press "Proceed to Checkout"
WebElement e = driver.findElement(By.className("paypal-logo"));
e = e.findElement(By.tagName("img"));
e.click();
// change waitfor element due to new Paypal sandbox page
// waitForIdVisible("login_email");
waitForIdVisible("forgotPasswordSection");
// waitForClassVisible("inputField emailField confidential");
// finish Paypal checkout flow
loginPaypalAndConfirm(account, password);
waitForIdVisible("review_button");
// And I select shipping method
// iSelectFirstOption("shipping_method");
iSelectFromSelect("Fixed - $5.00", "shipping_method");
waitForPlaceOrderButtonEnable();
// And I press "Place Order"
e = driver.findElement(By.id("review_button"));
e.click();
// Then I should see "Thank you for your purchase"
waitForCssVisible("html body.checkout-onepage-success div.wrapper div.page div.main-container div.main div.col-main p a");
e = driver.findElement(By.className("col-main"));
e = e.findElement(By.className("sub-title"));
assertEquals("Thank you for your purchase!",e.getText());
}
void waitForPlaceOrderButtonEnable(){
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.id("review_button"));
String enabled = button.getAttribute("class");
if(enabled.equals("button btn-checkout"))
return true;
else
return false;
}
});
}
void iLogOutAsUser() {
driver.findElement(By.linkText("Log Out")).click();
waitFor(By.partialLinkText("Log In"));
}
void iSelectFromSelect(String optionText, String selectId) {
WebElement select = driver.findElement(By.id(selectId));
List<WebElement> options = select.findElements(By.tagName("option"));
for(WebElement option : options){
if(option.getText().equals(optionText)) {
option.click();
break;
}
}
}
void iSelectNameFromSelect(String optionText, String selectName) {
WebElement select = driver.findElement(By.name(selectName));
List<WebElement> options = select.findElements(By.tagName("option"));
for(WebElement option : options){
if(option.getText().equals(optionText)) {
option.click();
break;
}
}
}
void iSelectFirstOption(String selectId) {
WebElement select = driver.findElement(By.id(selectId));
List<WebElement> options = select.findElements(By.tagName("option"));
options.get(1).click();
}
void iPressInvoice() {
WebElement invoiceButton = null;
List<WebElement> buttons = driver.findElement(By.id("anchor-content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Invoice".equals(button.getAttribute("title"))) {
invoiceButton = button;
}
}
assertNotNull("Couldn't find invoice button", invoiceButton);
waitFor(By.id(invoiceButton.getAttribute("id")));
invoiceButton.click();
waitFor(By.className("order-totals-bottom"));
}
void iPressCreateNewOrder() {
WebElement createOrderButton = null;
List<WebElement> buttons = driver.findElement(By.id("anchor-content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Create New Order".equals(button.getAttribute("title"))) {
createOrderButton = button;
}
}
assertNotNull("Couldn't find create new order button", createOrderButton);
waitFor(By.id(createOrderButton.getAttribute("id")));
createOrderButton.click();
waitFor(By.id("back_order_top_button"));
}
void iPressSubmitInvoice(String expectedMessage, String expectedComment) {
WebElement e = driver.findElement(By.className("order-totals-bottom"));
e = e.findElement(By.tagName("button"));
e.click();
waitFor(By.id("messages"));
if(expectedMessage != null) {
e = driver.findElement(By.id("messages"));
assertEquals(expectedMessage,e.getText());
}
if(expectedComment != null) {
List<WebElement> comments = driver.findElement(By.id("order_history_block")).findElements(By.tagName("li"));
assertTrue(String.valueOf(comments.size()), comments.size() > 0);
e = comments.get(0);
assertTrue(e.getText(), e.getText().contains(expectedComment));
}
}
void iPressVoidCapture(String expectedMessage) {
WebElement voidCaptureButton = null;
List<WebElement> buttons = driver.findElement(By.id("content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Void Capture".equals(button.getAttribute("title"))) {
voidCaptureButton = button;
}
}
assertNotNull("Couldn't find void capture button", voidCaptureButton);
waitFor(By.id(voidCaptureButton.getAttribute("id")));
voidCaptureButton.click();
Alert alert = driver.switchTo().alert();
alert.accept();
waitFor(By.id("messages"));
String actualText = driver.findElement(By.id("messages")).getText();
assertTrue(actualText, actualText.matches(expectedMessage));
}
void iPressVoidSale(String expectedMessage) {
WebElement voidSaleButton = null;
List<WebElement> buttons = driver.findElement(By.id("content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Void Sale".equals(button.getAttribute("title"))) {
voidSaleButton = button;
}
}
assertNotNull("Couldn't find void sale button", voidSaleButton);
waitFor(By.id(voidSaleButton.getAttribute("id")));
voidSaleButton.click();
Alert alert = driver.switchTo().alert();
alert.accept();
waitFor(By.id("messages"));
assertEquals(expectedMessage, driver.findElement(By.id("messages")).getText());
}
void iPressCreditMemo() {
WebElement creditMemoButton = null;
List<WebElement> buttons = driver.findElement(By.id("anchor-content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Credit Memo".equals(button.getAttribute("title"))) {
creditMemoButton = button;
}
}
assertNotNull("Couldn't find credit memo button", creditMemoButton);
waitFor(By.id(creditMemoButton.getAttribute("id")));
creditMemoButton.click();
waitFor(By.id("edit_form"));
}
void iPressRefund(String message) {
WebElement refundButton = null;
List<WebElement> buttons = driver.findElement(By.id("creditmemo_item_container")).findElement(By.className("order-totals-bottom")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Refund".equals(button.getAttribute("title"))) {
refundButton = button;
}
}
assertNotNull("Couldn't find refund button", refundButton);
waitFor(By.id(refundButton.getAttribute("id")));
refundButton.click();
waitFor(By.id("messages"));
assertEquals(message, driver.findElement(By.id("messages")).getText());
}
void iPressVoidRefund(String message) {
WebElement refundButton = null;
List<WebElement> buttons = driver.findElement(By.id("content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Void Refund".equals(button.getAttribute("title"))) {
refundButton = button;
}
}
assertNotNull("Couldn't find void refund button", refundButton);
waitFor(By.id(refundButton.getAttribute("id")));
refundButton.click();
Alert alert = driver.switchTo().alert();
alert.accept();
waitFor(By.id("messages"));
assertEquals(message, driver.findElement(By.id("messages")).getText());
}
void iPressCancel(String message) {
WebElement cancelButton = null;
List<WebElement> buttons = driver.findElement(By.id("content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Cancel".equals(button.getAttribute("title"))) {
cancelButton = button;
}
}
assertNotNull("Couldn't find cancel button", cancelButton);
waitFor(By.id(cancelButton.getAttribute("id")));
cancelButton.click();
Alert alert = driver.switchTo().alert();
alert.accept();
waitFor(By.id("messages"));
assertEquals(message, driver.findElement(By.id("messages")).getText());
}
void iPressAuthReversal(String message) {
WebElement authReversalButton = null;
List<WebElement> buttons = driver.findElement(By.id("content")).findElement(By.className("form-buttons")).findElements(By.tagName("button"));
for(WebElement button : buttons) {
if("Auth-Reversal".equals(button.getAttribute("title"))) {
authReversalButton = button;
}
}
assertNotNull("Couldn't find auth reversal button", authReversalButton);
waitFor(By.id(authReversalButton.getAttribute("id")));
authReversalButton.click();
Alert alert = driver.switchTo().alert();
alert.accept();
waitFor(By.id("messages"));
assertEquals(message, driver.findElement(By.id("messages")).getText());
}
void iClickOnInvoices() {
WebElement invoiceLink = null;
for(WebElement link : driver.findElement(By.id("sales_order_view_tabs")).findElements(By.tagName("a"))) {
if("Order Invoices".equals(link.getAttribute("title"))) {
invoiceLink = link;
}
}
assertNotNull(invoiceLink);
invoiceLink.click();
waitFor(By.id("order_invoices"));
}
void iClickOnTheTopRowInInvoices() {
String url = driver.findElement(By.xpath("/html/body/div[2]/div[3]/div/div/div[2]/div/div[3]/div[2]/div/div/div/table/tbody/tr")).getAttribute("title");
driver.get(url);
waitFor(By.id("comments_block"));
}
protected void iSelectTopOrders(int numOrdersToSelect) {
WebElement e = driver.findElement(By.id("sales_order_grid_table"));
e = e.findElement(By.tagName("tbody"));
List<WebElement> rows = e.findElements(By.tagName("tr"));
for(int i = 0; i < numOrdersToSelect; i++) {
WebElement row = rows.get(i);
WebElement checkbox = row.findElement(By.tagName("input"));
checkbox.click();
}
}
protected String getOrderNumForOrder(int orderRow) {
WebElement e = driver.findElement(By.id("sales_order_grid_table"));
e = e.findElement(By.tagName("tbody"));
List<WebElement> rows = e.findElements(By.tagName("tr"));
WebElement row = rows.get(orderRow);
List<WebElement> cols = row.findElements(By.tagName("td"));
WebElement col = cols.get(1);
return col.getText().trim();
}
protected void iPressSubmitOnOrders() {
WebElement e = driver.findElement(By.id("sales_order_grid_massaction-form"));
e = e.findElement(By.tagName("button"));
e.click();
waitFor(By.id("messages"));
}
protected void iPressSubmitOrder() {
List<WebElement> buttons = driver.findElements(By.tagName("button"));
WebElement submitOrderButton = null;
for(WebElement button : buttons) {
if("Submit Order".equals(button.getAttribute("title"))) {
submitOrderButton = button;
break;
}
}
assertNotNull("Couldn't find submit order button", submitOrderButton);
submitOrderButton.click();
waitForIdVisible("messages");
}
void iHaveMultipleProductsInMyCart(String productName,String numberOfProducts) {
waitFor(By.id("search"));
//Find the item
//Enter search text
WebElement e = driver.findElement(By.id("search"));
e.clear();
e.sendKeys(productName);
//Hit the search button
e = driver.findElement(By.className("form-search"));
e = e.findElement(By.tagName("button"));
e.click();
waitForCssVisible(".btn-cart");
//Add to cart
e = driver.findElement(By.cssSelector(".btn-cart"));
e.click();
waitForCssVisible(".btn-proceed-checkout");
e = driver.findElement(By.cssSelector(".qty"));
e.clear();
e.sendKeys(numberOfProducts);
e = driver.findElement(By.cssSelector(".btn-update"));
e.click();
}
}
|
package com.echsylon.atlantis;
import android.content.Context;
import android.os.AsyncTask;
import com.echsylon.atlantis.internal.UrlUtils;
import com.echsylon.atlantis.internal.Utils;
import com.echsylon.atlantis.internal.json.JsonParser;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import fi.iki.elonen.NanoHTTPD;
/**
* This is the local web server that will serve the template responses. This web server will only
* serve mocked responses for requests targeting "localhost". If configured so, a request can be
* delegated to a "real world" server if no corresponding configuration is found for a certain
* request.
*/
@SuppressWarnings("WeakerAccess") // Suppress Lint Warning on public method visibility
public class Atlantis {
private static final String HOSTNAME = "localhost";
private static final int PORT = 8080;
/**
* This is a converter class, representing an HTTP status as the NanoHTTPD class knows it.
* Atlantis only works with integers and strings when it comes to HTTP status code, hence the
* need for this class.
*/
private static final class NanoStatus implements NanoHTTPD.Response.IStatus {
private final int code;
private final String name;
private NanoStatus(int code, String name) {
this.code = code;
this.name = name;
}
@Override
public String getDescription() {
return String.format(Locale.ENGLISH, "%d %s", code, name);
}
@Override
public int getRequestStatus() {
return code;
}
}
/**
* This is a callback interface through which any asynchronous success states are notified.
*/
public interface OnSuccessListener {
/**
* Delivers a success notification.
*/
void onSuccess();
}
/**
* THis is a callback interface through which any asynchronous exceptions are notified.
*/
public interface OnErrorListener {
/**
* Delivers an error result.
*
* @param cause The cause of the error.
*/
void onError(Throwable cause);
}
/**
* Starts the local Atlantis server. The caller must manually set a configuration (either by
* pointing to a JSON asset or by injecting programmatically defined request templates). The
* success callback is called once the server is fully operational.
*
* @param successListener The success callback implementation.
* @param errorListener The error callback implementation.
* @return An Atlantis object instance.
*/
public static Atlantis start(OnSuccessListener successListener, OnErrorListener errorListener) {
Atlantis atlantis = new Atlantis();
try {
// Starting the nanoHTTPD server on the calling thread. This may cause a grumpy mode in
// Android (especially with Strict Mode enabled), while nanoHTTPD internally will force
// the calling thread to sleep. The sleep is for a very short amount of time, but
// nonetheless forceful. We need to keep an eye on this.
atlantis.nanoHTTPD.start();
if (successListener != null)
successListener.onSuccess();
} catch (IOException e) {
if (errorListener != null)
errorListener.onError(e);
}
return atlantis;
}
/**
* Starts the local Atlantis server and automatically loads a configuration from a JSON asset.
*
* @param context The context to use while loading any assets.
* @param configAssetName The name of the configuration asset file to load.
* @param successListener The success callback implementation.
* @param errorListener The error callback implementation.
* @return An Atlantis object instance.
*/
public static Atlantis start(Context context, String configAssetName, OnSuccessListener successListener, OnErrorListener errorListener) {
Atlantis atlantis = new Atlantis();
try {
// Starting the nanoHTTPD server on the calling thread. This may cause a grumpy mode in
// Android (especially with Strict Mode enabled), while nanoHTTPD internally will force
// the calling thread to sleep. The sleep is for a very short amount of time, but
// nonetheless forceful. We need to keep an eye on this.
atlantis.nanoHTTPD.start();
atlantis.setConfiguration(context, configAssetName, successListener, errorListener);
} catch (IOException e) {
if (errorListener != null)
errorListener.onError(e);
}
return atlantis;
}
/**
* Starts the local Atlantis server and automatically loads a configuration from a JSON file.
*
* @param context The context to use while loading any assets.
* @param configFile The file to load the configuration from.
* @param successListener The success callback implementation.
* @param errorListener The error callback implementation.
* @return An Atlantis object instance.
*/
public static Atlantis start(Context context, File configFile, OnSuccessListener successListener, OnErrorListener errorListener) {
Atlantis atlantis = new Atlantis();
try {
// Starting the nanoHTTPD server on the calling thread. This may cause a grumpy mode in
// Android (especially with Strict Mode enabled), while nanoHTTPD internally will force
// the calling thread to sleep. The sleep is for a very short amount of time, but
// nonetheless forceful. We need to keep an eye on this.
atlantis.nanoHTTPD.start();
atlantis.setConfiguration(context, configFile, successListener, errorListener);
} catch (IOException e) {
if (errorListener != null)
errorListener.onError(e);
}
return atlantis;
}
/**
* Starts the local Atlantis server and automatically sets a built configuration.
*
* @param context The context to use while loading any response assets.
* @param configuration The built configuration object.
* @param successListener The success callback implementation.
* @param errorListener The error callback implementation.
* @return An Atlantis object instance.
*/
public static Atlantis start(Context context, Configuration configuration, OnSuccessListener successListener, OnErrorListener errorListener) {
Atlantis atlantis = new Atlantis();
try {
// Starting the nanoHTTPD server on the calling thread. This may cause a grumpy mode in
// Android (especially with Strict Mode enabled), while nanoHTTPD internally will force
// the calling thread to sleep. The sleep is for a very short amount of time, but
// nonetheless forceful. We need to keep an eye on this.
atlantis.nanoHTTPD.start();
atlantis.setConfiguration(context, configuration);
if (successListener != null)
successListener.onSuccess();
} catch (IOException e) {
if (errorListener != null)
errorListener.onError(e);
}
return atlantis;
}
private Context context;
private NanoHTTPD nanoHTTPD;
private Configuration configuration;
private boolean isCapturing;
private final Object captureLock;
private volatile Stack<Request> captured;
// Intentionally hidden constructor.
private Atlantis() {
this.isCapturing = false;
this.captureLock = new Object();
this.captured = new Stack<>();
this.nanoHTTPD = new NanoHTTPD(HOSTNAME, PORT) {
@Override
public Response serve(IHTTPSession session) {
// Early bail-out.
if (configuration == null)
return super.serve(session);
// Get a response to deliver.
com.echsylon.atlantis.Response response = getMockedResponse(
session.getUri(),
session.getMethod().name(),
session.getHeaders());
// No response found, try to fall back to the real world.
if (response == null)
if (configuration.hasAlternativeRoute())
response = getRealResponse(configuration.fallbackBaseUrl(),
session.getUri(),
session.getMethod().name(),
session.getHeaders());
// Nope, the real world isn't any better. Bail out and serve default response.
if (response == null)
return super.serve(session);
// We have a response. Maybe delay before actually delivering it. Relax, this
// is a worker thread.
long delay = response.delay();
if (delay > 0L)
try {
Thread.sleep(delay);
} catch (InterruptedException ignored) {
}
// Now, finally, deliver.
try {
NanoStatus status = new NanoStatus(response.statusCode(), response.statusName());
String mime = response.mimeType();
byte[] bytes = response.hasAsset() ?
response.asset(context) :
response.content().getBytes();
return newFixedLengthResponse(status, mime, new ByteArrayInputStream(bytes), bytes.length);
} catch (Exception e) {
return newFixedLengthResponse(
Response.Status.INTERNAL_ERROR,
NanoHTTPD.MIME_PLAINTEXT,
"SERVER INTERNAL ERROR: Exception: " + e.getMessage());
}
}
};
}
/**
* Stops the local web server.
*/
public void stop() {
configuration = null;
nanoHTTPD.closeAllConnections();
nanoHTTPD.stop();
nanoHTTPD = null;
isCapturing = false;
}
/**
* Reconfigures Atlantis by setting the new set of requests to respond to.
*
* @param context The context to use when reading assets.
* @param configuration The new configuration.
*/
public void setConfiguration(Context context, Configuration configuration) {
this.context = context;
this.configuration = configuration;
}
/**
* Reconfigures Atlantis from a configuration JSON asset. The asset is read from disk on a
* worker thread. Any results are notified through the given callbacks, if given.
*
* @param context The context to use when reading assets.
* @param configAssetName The name of the configuration asset file (relative to the apps
* 'assets' folder).
* @param successListener The success callback.
* @param errorListener The error callback.
*/
public void setConfiguration(final Context context, final String configAssetName, final OnSuccessListener successListener, final OnErrorListener errorListener) {
this.context = context;
if (configAssetName == null)
this.configuration = null;
new AsyncTask<Void, Void, Throwable>() {
@Override
protected Throwable doInBackground(Void... nothings) {
try {
byte[] bytes = Utils.readAsset(context, configAssetName);
String json = new String(bytes);
JsonParser jsonParser = new JsonParser();
Atlantis.this.configuration = jsonParser.fromJson(json, Configuration.class);
return null;
} catch (Exception e) {
return e;
}
}
@Override
protected void onPostExecute(Throwable throwable) {
if (throwable == null) {
if (successListener != null)
successListener.onSuccess();
} else {
if (errorListener != null)
errorListener.onError(throwable);
}
}
}.execute();
}
/**
* Reconfigures Atlantis from a configuration JSON file. The asset is read from disk on a
* worker thread. Any results are notified through the given callbacks, if given.
*
* @param context The context to use when reading assets.
* @param file The configuration JSON file to read.
* @param successListener The success callback.
* @param errorListener The error callback.
*/
public void setConfiguration(final Context context, final File file, final OnSuccessListener successListener, final OnErrorListener errorListener) {
this.context = context;
if (file == null)
this.configuration = null;
new AsyncTask<Void, Void, Throwable>() {
@Override
protected Throwable doInBackground(Void... nothings) {
try {
//noinspection ConstantConditions
String json = Files.toString(file, Charsets.UTF_8);
JsonParser jsonParser = new JsonParser();
Atlantis.this.configuration = jsonParser.fromJson(json, Configuration.class);
return null;
} catch (Exception e) {
return e;
}
}
@Override
protected void onPostExecute(Throwable throwable) {
if (throwable == null) {
if (successListener != null)
successListener.onSuccess();
} else {
if (errorListener != null)
errorListener.onError(throwable);
}
}
}.execute();
}
/**
* Writes the current Atlantis configuration to a file on the filesystem. The configuration is
* written to disk on a worker thread. Any results are notified through the given callbacks, if
* given.
*
* @param file The file to write the configuration to.
* @param successListener The success callback.
* @param errorListener The error callback.
*/
public void writeConfigurationToFile(final File file, final OnSuccessListener successListener, final OnErrorListener errorListener) {
new AsyncTask<Void, Void, Throwable>() {
@Override
protected Throwable doInBackground(Void... nothings) {
try {
JsonParser jsonParser = new JsonParser();
String json = jsonParser.toJson(Atlantis.this.configuration, Configuration.class);
Files.write(json, file, Charsets.UTF_8);
return null;
} catch (Exception e) {
return e;
}
}
@Override
protected void onPostExecute(Throwable throwable) {
if (throwable == null) {
if (successListener != null)
successListener.onSuccess();
} else {
if (errorListener != null)
errorListener.onError(throwable);
}
}
}.execute();
}
/**
* Tells the local web server to start capturing a copy of any served requests. This method will
* start a new capture session by clearing the capture history stack.
*/
public void startCapturing() {
clearCapturedRequests();
isCapturing = true;
}
/**
* Tells the local web server to stop capturing any served requests. This method leaves the
* capture history stack intact.
*/
public void stopCapturing() {
isCapturing = false;
}
/**
* Returns a snapshot of the capture history stack as it looks right this moment. This method
* leaves the actual stack intact, but new requests may be added to it at any time and these new
* additions won't be reflected in the output of this method.
*
* @return A snapshot of the captured history stack.
*/
public Stack<Request> getCapturedRequests() {
Stack<Request> result = new Stack<>();
synchronized (captureLock) {
result.addAll(captured);
}
return result;
}
/**
* Clears any captured requests in the history stack. This method will not affect the capturing
* state.
*/
public void clearCapturedRequests() {
synchronized (captureLock) {
captured.clear();
}
}
// Tries to find a response configuration that matches the given request parameters. Also
// pushes the request to the capture stack if in such a state.
private Response getMockedResponse(String url, String method, Map<String, String> headers) {
Request request = configuration.findRequest(url, method, headers);
if (isCapturing)
synchronized (captureLock) {
captured.push(request != null ?
request :
new Request.Builder()
.withUrl(url)
.withMethod(method)
.withHeaders(headers));
}
return request != null ?
request.response() :
null;
}
// Synchronously makes a real network request and returns the response as an Atlantis response,
// or null would anything go wrong. This request is completely anonymous from the local web
// servers (currently NanoHTTPD) point of view as the internal state (cookies and what-not)
// won't be updated with these real world parameters. Would the real world request fail, then
// the local web server would serve a response suggesting the local request failed (i.e.
private Response getRealResponse(String realBaseUrl, String requestUrl, String method, Map<String, String> headers) {
HttpURLConnection connection = null;
String realUrl = String.format("%s%s%s%s", realBaseUrl,
UrlUtils.getPath(requestUrl),
UrlUtils.getQuery(requestUrl),
UrlUtils.getFragment(requestUrl));
try {
// Initiate the real world request.
URL url = new URL(realUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.getRequestProperties();
// Some headers we don't want to leak to the real world at all.
// These seem to be added by NanoHttpd.
headers.remove("host");
headers.remove("remote-addr");
headers.remove("http-client-ip");
// But the rest we might want to expose, still making sure we don't overwrite stuff.
if (!headers.isEmpty())
for (Map.Entry<String, String> entry : headers.entrySet())
if (connection.getRequestProperty(entry.getKey()) == null)
connection.setRequestProperty(entry.getKey(), entry.getValue());
// And so build an Atlantis response from the real world response.
return new com.echsylon.atlantis.Response.Builder()
.withStatus(UrlUtils.getResponseCode(connection), UrlUtils.getResponseMessage(connection))
.withMimeType(UrlUtils.getResponseMimeType(connection))
.withHeaders(UrlUtils.getResponseHeaders(connection))
.withAsset(UrlUtils.getResponseBody(connection));
} catch (IOException e) {
return null;
} finally {
UrlUtils.closeSilently(connection);
}
}
}
|
package com.just.library;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.StatFs;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.ColorInt;
import android.support.design.widget.Snackbar;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
public class AgentWebUtils {
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int dp2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static final void clearWebView(WebView m) {
if (m == null)
return;
if (Looper.myLooper() != Looper.getMainLooper())
return;
m.loadUrl("about:blank");
m.stopLoading();
if (m.getHandler() != null)
m.getHandler().removeCallbacksAndMessages(null);
m.removeAllViews();
ViewGroup mViewGroup = null;
if ((mViewGroup = ((ViewGroup) m.getParent())) != null)
mViewGroup.removeView(m);
m.setWebChromeClient(null);
m.setWebViewClient(null);
m.setTag(null);
m.clearHistory();
m.destroy();
m = null;
}
public static boolean checkWifi(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
}
NetworkInfo info = connectivity.getActiveNetworkInfo();
return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
}
public static boolean checkNetwork(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
}
NetworkInfo info = connectivity.getActiveNetworkInfo();
return info != null && info.isConnected();
}
public static int checkNetworkType(Context context) {
int netType = 0;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null)
return netType;
switch (networkInfo.getType()) {
case ConnectivityManager.TYPE_WIFI:
case ConnectivityManager.TYPE_WIMAX:
case ConnectivityManager.TYPE_ETHERNET:
return 1;
case ConnectivityManager.TYPE_MOBILE:
switch (networkInfo.getSubtype()) {
case TelephonyManager.NETWORK_TYPE_LTE:
case TelephonyManager.NETWORK_TYPE_HSPAP:
case TelephonyManager.NETWORK_TYPE_EHRPD:
return 2;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
return 3;
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
return 4;
default:
return netType;
}
default:
return netType;
}
}
public static long getAvailableStorage() {
try {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return stat.getAvailableBlocksLong() * stat.getBlockSizeLong();
} else {
return (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
} catch (RuntimeException ex) {
return 0;
}
}
public static Intent getFileIntent(File file) {
Uri uri = Uri.fromFile(file);
String type = getMIMEType(file);
Log.i("tag", "type=" + type);
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, type);
return intent;
}
private static String getMIMEType(File f) {
String type = "";
String fName = f.getName();
String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
/* MimeType */
if (end.equals("pdf")) {
type = "application/pdf";
} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
//
type = "*/*";
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*
* // stackflow
*/
public static void clearCache(final Context context, final int numDays) {
Log.i("Info", String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i("Info", String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}
public static String[] uriToPath(Activity activity, Uri[] uris) {
if (activity == null || uris == null || uris.length == 0) {
return null;
}
String[] paths = new String[uris.length];
int i = 0;
for (Uri mUri : uris) {
paths[i++] = Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2 ? getFileAbsolutePath(activity, mUri) : getRealPathBelowVersion(activity, mUri);
// Log.i("Info", "path:" + paths[i-1] + " uri:" + mUri);
}
return paths;
}
private static String getRealPathBelowVersion(Context context, Uri uri) {
String filePath = null;
String[] projection = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(context, uri, projection, null,
null, null);
Cursor cursor = loader.loadInBackground();
if (cursor != null) {
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
cursor.close();
}
return filePath;
}
public static Queue<FileParcel> convertFile(String[] paths) throws Exception {
if (paths == null || paths.length == 0)
return null;
int tmp = Runtime.getRuntime().availableProcessors() + 1;
int result = paths.length > tmp ? tmp : paths.length;
Executor mExecutor = Executors.newFixedThreadPool(result);
final Queue<FileParcel> mQueue = new LinkedBlockingQueue<>();
CountDownLatch mCountDownLatch = new CountDownLatch(paths.length);
int i = 1;
for (String path : paths) {
LogUtils.i("Info", "path : :" + path);
if (TextUtils.isEmpty(path)) {
mCountDownLatch.countDown();
continue;
}
mExecutor.execute(new EncodeFileRunnable(path, mQueue, mCountDownLatch, i++));
}
mCountDownLatch.await();
if (!((ThreadPoolExecutor) mExecutor).isShutdown())
((ThreadPoolExecutor) mExecutor).shutdownNow();
LogUtils.i("Info", "isShutDown:" + (((ThreadPoolExecutor) mExecutor).isShutdown()));
return mQueue;
}
static class EncodeFileRunnable implements Runnable {
private String filePath;
private Queue<FileParcel> mQueue;
private CountDownLatch mCountDownLatch;
private int id;
public EncodeFileRunnable(String filePath, Queue<FileParcel> queue, CountDownLatch countDownLatch, int id) {
this.filePath = filePath;
this.mQueue = queue;
this.mCountDownLatch = countDownLatch;
this.id = id;
}
@Override
public void run() {
InputStream is = null;
ByteArrayOutputStream os = null;
try {
File mFile = new File(filePath);
if (mFile.exists()) {
is = new FileInputStream(mFile);
if (is == null)
return;
os = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = is.read(b, 0, 1024)) != -1) {
os.write(b, 0, len);
}
mQueue.offer(new FileParcel(id, mFile.getAbsolutePath(), Base64.encodeToString(os.toByteArray(), Base64.DEFAULT)));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
CloseUtils.closeIO(is);
CloseUtils.closeIO(os);
mCountDownLatch.countDown();
}
}
}
@TargetApi(19)
public static String getFileAbsolutePath(Activity context, Uri fileUri) {
if (context == null || fileUri == null)
return null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, fileUri)) {
if (isExternalStorageDocument(fileUri)) {
String docId = DocumentsContract.getDocumentId(fileUri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(fileUri)) {
String id = DocumentsContract.getDocumentId(fileUri);
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(fileUri)) {
String docId = DocumentsContract.getDocumentId(fileUri);
String[] split = docId.split(":");
String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} // MediaStore (and general)
else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(fileUri))
return fileUri.getLastPathSegment();
return getDataColumn(context, fileUri, null, null);
}
// File
else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
return fileUri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
String[] projection = {MediaStore.Images.Media.DATA};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
public static Intent getIntentCompat(Context context, File file) {
Intent mIntent = null;
LogUtils.i("Info", "getIntentCompat :" + context.getApplicationInfo().targetSdkVersion);
if (context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(FileProvider.getUriForFile(context, context.getPackageName() + ".AgentWebFileProvider", file), "application/vnd.android.package-archive");
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
mIntent = AgentWebUtils.getFileIntent(file);
}
return mIntent;
}
public static boolean isJson(String target) {
if (TextUtils.isEmpty(target))
return false;
boolean tag = false;
try {
if (target.startsWith("["))
new JSONArray(target);
else
new JSONObject(target);
tag = true;
} catch (JSONException igonre) {
// igonre.printStackTrace();
tag = false;
}
return tag;
}
public static String FileParcetoJson(Collection<FileParcel> collection) {
if (collection == null || collection.size() == 0)
return null;
Iterator<FileParcel> mFileParcels = collection.iterator();
JSONArray mJSONArray = new JSONArray();
try {
while (mFileParcels.hasNext()) {
JSONObject jo = new JSONObject();
FileParcel mFileParcel = mFileParcels.next();
jo.put("contentPath", mFileParcel.getContentPath());
jo.put("fileBase64", mFileParcel.getFileBase64());
jo.put("id", mFileParcel.getId());
mJSONArray.put(jo);
}
} catch (Exception e) {
}
// Log.i("Info","json:"+mJSONArray);
return mJSONArray + "";
}
public static boolean isMainProcess(Context context) {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
boolean tag = false;
int id = android.os.Process.myPid();
String processName = "";
String packgeName = context.getPackageName();
List<ActivityManager.RunningAppProcessInfo> mInfos = mActivityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo mRunningAppProcessInfo : mInfos) {
if (mRunningAppProcessInfo.pid == id) {
processName = mRunningAppProcessInfo.processName;
break;
}
}
if (packgeName.equals(processName))
tag = true;
return tag;
}
public static boolean isUIThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
public static boolean isEmptyCollection(Collection collection) {
return collection == null || collection.isEmpty();
}
public static boolean isEmptyMap(Map map) {
return map == null || map.isEmpty();
}
private static Toast mToast = null;
public static void toastShowShort(Context context, String msg) {
if (mToast == null) {
mToast = Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_SHORT);
} else {
mToast.setText(msg);
}
mToast.show();
}
private static Handler mHandler = null;
public static void runInUiThread(Runnable runnable) {
if (mHandler == null)
mHandler = new Handler(Looper.getMainLooper());
mHandler.post(runnable);
}
}
|
package com.galois.qrstream.lib;
import android.hardware.Camera;
import android.util.Log;
import com.galois.qrstream.image.YuvImage;
import java.util.Queue;
public class Preview implements Camera.PreviewCallback {
private Queue frames;
private int height;
private int width;
public Preview(Queue frames, Camera.Size size) {
setQueue(frames);
setSize(size);
}
public void setQueue(Queue frames) {
this.frames = frames;
}
public void setSize(Camera.Size size) {
this.height = size.height;
this.width = size.width;
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
Log.v(Constants.APP_TAG, "previewFrame data "+data.length);
YuvImage frame = new YuvImage(data, height, width);
if(frames.offer(frame) == false) {
Log.v(Constants.APP_TAG, "Frame queue full!");
}
}
}
|
package org.maker_pattern;
import java.io.IOException;
import java.util.Properties;
import org.maker_pattern.animals.Animal;
import org.maker_pattern.animals.Cat;
import org.maker_pattern.animals.CatFamily;
import org.maker_pattern.animals.Dog;
import org.maker_pattern.animals.DogFamily;
import org.maker_pattern.plants.Ceiba;
import org.maker_pattern.plants.Daisy;
import org.maker_pattern.plants.Plant;
/**
* A very basic, light-weight, pragmatic programmatic alternative to DI frameworks
* Maker Pattern versions:
* 0.1 First version using an external class that included a Map storing the singleton instances and getInstance method, supporting
* singleton and prototype beans
* 0.2 Redesigned the pattern, now everything is in a single class (enum) and uses kind of factory methods for retrieving instances
* This version is also capable of wiring beans inside the same enum and cross enum wiring too, allowing us to separate the beans
* by domain or responsibility in different files and wire them if needed
* 0.3 Added init, start, shutdown, clear and clearAll life cycle methods
* 0.4 Added Properties parameter to getInstance method for supporting initialization properties
* 0.5 Removed init method as it was not really useful
* @author Ramiro.Serrato
*
*/
public enum LivingBeingMaker {
/*** Object configuration, definition, wiring ***/
// Pattern: NAME (isSingleton) { createInstance() { <object creation logic > } }
SPARKY_DOG (true) {
@Override
public Dog createInstance(Properties properties) {
Dog sparky = new Dog();
sparky.setName(properties.getProperty("sparky.name"));
return sparky;
}
},
PINKY_DOG (true) {
@Override
public Dog createInstance(Properties properties) {
Dog pinky = new Dog();
pinky.setName(properties.getProperty("pinky.name"));
return pinky;
}
},
SPARKY_FAMILY (true) { // A wired object
@Override
public DogFamily createInstance(Properties properties) {
DogFamily dogFamily = new DogFamily();
dogFamily.setParent1(getDog(SPARKY_DOG));
dogFamily.setParent2(getDog(PINKY_DOG));
return dogFamily;
}
},
SIAMESE (false) { @Override public Cat createInstance(Properties properties) { return new Cat(); } },
LABRADOR (false) { @Override public Dog createInstance(Properties properties) { return new Dog(); } },
DAISY (false) {
@Override
public Plant createInstance(Properties properties) {
Daisy daisy = new Daisy();
daisy.setKind(properties.getProperty("daisy_kind"));
return daisy;
}
},
CEIBA (false) {
@Override
public Plant createInstance(Properties properties) {
Ceiba ceiba = new Ceiba();
ceiba.setAge(new Integer(properties.getProperty("ceiba_age")));
return ceiba;
}
};
/** Here define factory methods **/
public static Dog getDog(LivingBeingMaker livingBeingMaker) {
return (Dog) livingBeingMaker.getInstance(generalProperties);
}
public static Cat getCat(LivingBeingMaker livingBeingMaker) {
return (Cat) livingBeingMaker.getInstance(generalProperties);
}
public static DogFamily getDogFamily(LivingBeingMaker livingBeingMaker) {
return (DogFamily) livingBeingMaker.getInstance(generalProperties);
}
public static CatFamily getCatFamily(LivingBeingMaker livingBeingMaker) {
return (CatFamily) livingBeingMaker.getInstance(generalProperties);
}
public static Animal getAnimal(LivingBeingMaker livingBeingMaker) {
return (Animal) livingBeingMaker.getInstance(generalProperties);
}
public static Plant getPlant(LivingBeingMaker livingBeingMaker) {
return (Plant) livingBeingMaker.getInstance(generalProperties);
}
static { // here you can define static stuff like properties or xml loaded configuration
Properties livingBeingroperties = new Properties();
try { // load plant and animal configuration from xml and properties files
livingBeingroperties.loadFromXML(LivingBeingMaker.class.getResourceAsStream("resources/plant-config.xml"));
livingBeingroperties.load(LivingBeingMaker.class.getResourceAsStream("resources/animal-config.properties"));
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e.getMessage());
}
generalProperties = livingBeingroperties;
}
protected static Properties generalProperties;
private LivingBeingMaker(Boolean singleton) {
this.singleton = singleton;
}
private Boolean singleton;
private Object instance;
public Boolean isSingleton() {
return singleton;
}
/**
* This is the method that handles the creation of instances based on the flag singleton it
* will create a singleton or a prototype instance
* @param properties A Properties object that may contain information needed for the instance creation
* @return The instance as an Object
*/
private Object getInstance(Properties properties) {
if (singleton) {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = this.createInstance(properties);
}
}
}
}
Object localInstance = (instance == null) ? this.createInstance(properties) : instance;
start(localInstance);
return localInstance;
}
/**
* Similar to {@link #init()} method, the difference is that the logic here will be executed each time an instance
* is created, for prototypes that means every time the getInstance method is called, for singletons only the first
* time the getInstance method is called
*/
protected void start(Object object) {
;
}
/**
* You can put some shutdown logic here, this method can be overriden inside the enum value definition.
* Shutdown logic can be: external resources release, clear chache, etc.
*/
public void shutdown() throws Exception {
;
}
/**
* This method will call the {@link #shutdown()} method for all the enums in the maker
* @throws Exception
*/
public void shutdownAll() throws Exception {
for (LivingBeingMaker value : LivingBeingMaker.values()) {
value.shutdown();
}
}
/**
* This method will set the instance to null, useful for reseting singleton instances
*/
public void clear() {
instance = null;
}
/**
* Will call the {@link #clear()} method for all the enums defined in the maker
*/
public void clearAll() {
for (LivingBeingMaker value : LivingBeingMaker.values()) {
value.clear();
}
}
/**
* This method contains the logic for creating the instance, it receives a Properties
* object as a parameter that my contain initial properties for creating the instances
* @param properties a Properties object
* @return The created instance as an Object
*/
public abstract Object createInstance(Properties properties);
}
|
package org.openntf.domino.xsp.tests.paul;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
import org.openntf.domino.Database;
import org.openntf.domino.DateTime;
import org.openntf.domino.Document;
import org.openntf.domino.DocumentCollection;
import org.openntf.domino.Item;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.junit.TestRunnerUtil;
import org.openntf.domino.types.AuthorsList;
import org.openntf.domino.types.NamesList;
import org.openntf.domino.types.ReadersList;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.utils.Factory.SessionType;
public class Connect17Documents implements Runnable {
public Connect17Documents() {
}
public static void main(final String[] args) {
TestRunnerUtil.runAsDominoThread(new Connect17Documents(), TestRunnerUtil.NATIVE_SESSION);
}
@Override
public void run() {
Session sess = Factory.getSession(SessionType.NATIVE);
Database extLib = sess.getDatabase("odademo/oda_1.nsf");
View contacts = extLib.getView("AllContacts");
View threads = extLib.getView("AllThreadsByAuthor");
Document doc = contacts.getFirstDocument();
resetDoc(doc); // Clears changes this function already made
Document newDoc = extLib.createDocument();
doc.copyAllItems(newDoc, true);
String prevDocAsJson = doc.toJson(true);
doc.appendItemValue("State", "AZ");
doc.replaceItemValue("DateTimeField", new Date());
doc.replaceItemValue("DateOnlyField", new java.sql.Date(System.currentTimeMillis()));
System.out.println(doc.getFirstItem("DateOnlyField").getValues());
doc.replaceItemValue("TimeOnlyField", new java.sql.Time(System.currentTimeMillis()));
System.out.println(doc.getFirstItem("TimeOnlyField").getValues());
doc.replaceItemValue("EmptyDate", "");
Date blankDate = doc.getItemValue("EmptyDate", Date.class);
System.out.println(blankDate);
ArrayList<String> list = new ArrayList<String>();
list.add("Value 1");
list.add("Value 2");
doc.replaceItemValue("MVField", list);
doc.replaceItemValue("DocAsJson", prevDocAsJson);
HashMap<String, String> mapField = new HashMap<String, String>();
DocumentCollection dc = threads.getAllDocumentsByKey(doc.getItemValueString("FullName"));
for (Document tmp : dc) {
mapField.put(tmp.getUniversalID(), tmp.getItemValueString("Title"));
}
doc.put("MapField", mapField);
BigDecimal decimal = new BigDecimal("2.5");
doc.replaceItemValue("BigDecimalField", decimal);
doc.save();
HashMap tmp = doc.getItemValue("MapField", HashMap.class);
System.out.println(tmp.size());
System.out.println(doc.getMetaversalID());
NamesList<String> names = new NamesList<String>();
names.add("CN=Paul Withers/O=Intec");
names.add("CN=Admin/O=Intec=PW");
newDoc.replaceItemValue("Names", names);
AuthorsList<String> authors = new AuthorsList<String>();
authors.addAll(names);
newDoc.replaceItemValue("Authors", authors);
ReadersList<String> readers = new ReadersList<String>();
readers.addAll(names);
newDoc.replaceItemValue("Readers", readers);
Item dt = newDoc.replaceItemValue("TestDate", "");
Vector<DateTime> dates = new Vector();
DateTime dt1 = sess.createDateTime("01/01/2017");
DateTime dt2 = sess.createDateTime("02/01/2017");
dates.add(dt1);
dates.add(dt2);
dt.setValues(dates);
newDoc.save();
}
public void resetDoc(final Document doc) {
doc.replaceItemValue("State", doc.getItemValue("State").get(0));
doc.replaceItemValue("DateTimeField", null);
doc.removeItem("MVField");
doc.removeItem("DocAsJson");
doc.removeItem("MapField");
doc.removeItem("DateTimeField");
doc.removeItem("DateOnlyField");
doc.removeItem("TimeOnlyField");
doc.removeItem("BigDecimalField");
doc.save();
}
}
|
package org.eclipse.jgit.lib;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.util.MutableInteger;
/** Misc. constants used throughout JGit. */
public final class Constants {
/** Hash function used natively by Git for all objects. */
private static final String HASH_FUNCTION = "SHA-1";
/** Length of an object hash. */
public static final int OBJECT_ID_LENGTH = 20;
/** Special name for the "HEAD" symbolic-ref. */
public static final String HEAD = "HEAD";
/**
* Text string that identifies an object as a commit.
* <p>
* Commits connect trees into a string of project histories, where each
* commit is an assertion that the best way to continue is to use this other
* tree (set of files).
*/
public static final String TYPE_COMMIT = "commit";
/**
* Text string that identifies an object as a blob.
* <p>
* Blobs store whole file revisions. They are used for any user file, as
* well as for symlinks. Blobs form the bulk of any project's storage space.
*/
public static final String TYPE_BLOB = "blob";
/**
* Text string that identifies an object as a tree.
* <p>
* Trees attach object ids (hashes) to names and file modes. The normal use
* for a tree is to store a version of a directory and its contents.
*/
public static final String TYPE_TREE = "tree";
/**
* Text string that identifies an object as an annotated tag.
* <p>
* Annotated tags store a pointer to any other object, and an additional
* message. It is most commonly used to record a stable release of the
* project.
*/
public static final String TYPE_TAG = "tag";
private static final byte[] ENCODED_TYPE_COMMIT = encodeASCII(TYPE_COMMIT);
private static final byte[] ENCODED_TYPE_BLOB = encodeASCII(TYPE_BLOB);
private static final byte[] ENCODED_TYPE_TREE = encodeASCII(TYPE_TREE);
private static final byte[] ENCODED_TYPE_TAG = encodeASCII(TYPE_TAG);
/** An unknown or invalid object type code. */
public static final int OBJ_BAD = -1;
/**
* In-pack object type: extended types.
* <p>
* This header code is reserved for future expansion. It is currently
* undefined/unsupported.
*/
public static final int OBJ_EXT = 0;
/**
* In-pack object type: commit.
* <p>
* Indicates the associated object is a commit.
* <p>
* <b>This constant is fixed and is defined by the Git packfile format.</b>
*
* @see #TYPE_COMMIT
*/
public static final int OBJ_COMMIT = 1;
/**
* In-pack object type: tree.
* <p>
* Indicates the associated object is a tree.
* <p>
* <b>This constant is fixed and is defined by the Git packfile format.</b>
*
* @see #TYPE_BLOB
*/
public static final int OBJ_TREE = 2;
/**
* In-pack object type: blob.
* <p>
* Indicates the associated object is a blob.
* <p>
* <b>This constant is fixed and is defined by the Git packfile format.</b>
*
* @see #TYPE_BLOB
*/
public static final int OBJ_BLOB = 3;
/**
* In-pack object type: annotated tag.
* <p>
* Indicates the associated object is an annotated tag.
* <p>
* <b>This constant is fixed and is defined by the Git packfile format.</b>
*
* @see #TYPE_TAG
*/
public static final int OBJ_TAG = 4;
/** In-pack object type: reserved for future use. */
public static final int OBJ_TYPE_5 = 5;
/**
* In-pack object type: offset delta
* <p>
* Objects stored with this type actually have a different type which must
* be obtained from their delta base object. Delta objects store only the
* changes needed to apply to the base object in order to recover the
* original object.
* <p>
* An offset delta uses a negative offset from the start of this object to
* refer to its delta base. The base object must exist in this packfile
* (even in the case of a thin pack).
* <p>
* <b>This constant is fixed and is defined by the Git packfile format.</b>
*/
public static final int OBJ_OFS_DELTA = 6;
/**
* In-pack object type: reference delta
* <p>
* Objects stored with this type actually have a different type which must
* be obtained from their delta base object. Delta objects store only the
* changes needed to apply to the base object in order to recover the
* original object.
* <p>
* A reference delta uses a full object id (hash) to reference the delta
* base. The base object is allowed to be omitted from the packfile, but
* only in the case of a thin pack being transferred over the network.
* <p>
* <b>This constant is fixed and is defined by the Git packfile format.</b>
*/
public static final int OBJ_REF_DELTA = 7;
/**
* Pack file signature that occurs at file header - identifies file as Git
* packfile formatted.
* <p>
* <b>This constant is fixed and is defined by the Git packfile format.</b>
*/
public static final byte[] PACK_SIGNATURE = { 'P', 'A', 'C', 'K' };
/** Native character encoding for commit messages, file names... */
public static final String CHARACTER_ENCODING = "UTF-8";
/** Native character encoding for commit messages, file names... */
public static final Charset CHARSET;
/** Default main branch name */
public static final String MASTER = "master";
/** Prefix for branch refs */
public static final String R_HEADS = "refs/heads/";
/** Prefix for remotes refs */
public static final String R_REMOTES = "refs/remotes/";
/** Prefix for tag refs */
public static final String R_TAGS = "refs/tags/";
/** Prefix for any ref */
public static final String R_REFS = "refs/";
/** Logs folder name */
public static final String LOGS = "logs";
/** Info refs folder */
public static final String INFO_REFS = "info/refs";
/** Packed refs file */
public static final String PACKED_REFS = "packed-refs";
/** The environment variable that contains the system user name */
public static final String OS_USER_NAME_KEY = "user.name";
/** The environment variable that contains the author's name */
public static final String GIT_AUTHOR_NAME_KEY = "GIT_AUTHOR_NAME";
/** The environment variable that contains the author's email */
public static final String GIT_AUTHOR_EMAIL_KEY = "GIT_AUTHOR_EMAIL";
/** The environment variable that contains the commiter's name */
public static final String GIT_COMMITTER_NAME_KEY = "GIT_COMMITTER_NAME";
/** The environment variable that contains the commiter's email */
public static final String GIT_COMMITTER_EMAIL_KEY = "GIT_COMMITTER_EMAIL";
/** Default value for the user name if no other information is available */
public static final String UNKNOWN_USER_DEFAULT = "unknown-user";
/** Beginning of the common "Signed-off-by: " commit message line */
public static final String SIGNED_OFF_BY_TAG = "Signed-off-by: ";
/** A gitignore file name */
public static final String GITIGNORE_FILENAME = ".gitignore";
/**
* Create a new digest function for objects.
*
* @return a new digest object.
* @throws RuntimeException
* this Java virtual machine does not support the required hash
* function. Very unlikely given that JGit uses a hash function
* that is in the Java reference specification.
*/
public static MessageDigest newMessageDigest() {
try {
return MessageDigest.getInstance(HASH_FUNCTION);
} catch (NoSuchAlgorithmException nsae) {
throw new RuntimeException("Required hash function "
+ HASH_FUNCTION + " not available.", nsae);
}
}
/**
* Convert an OBJ_* type constant to a TYPE_* type constant.
*
* @param typeCode the type code, from a pack representation.
* @return the canonical string name of this type.
*/
public static String typeString(final int typeCode) {
switch (typeCode) {
case OBJ_COMMIT:
return TYPE_COMMIT;
case OBJ_TREE:
return TYPE_TREE;
case OBJ_BLOB:
return TYPE_BLOB;
case OBJ_TAG:
return TYPE_TAG;
default:
throw new IllegalArgumentException("Bad object type: " + typeCode);
}
}
/**
* Convert an OBJ_* type constant to an ASCII encoded string constant.
* <p>
* The ASCII encoded string is often the canonical representation of
* the type within a loose object header, or within a tag header.
*
* @param typeCode the type code, from a pack representation.
* @return the canonical ASCII encoded name of this type.
*/
public static byte[] encodedTypeString(final int typeCode) {
switch (typeCode) {
case OBJ_COMMIT:
return ENCODED_TYPE_COMMIT;
case OBJ_TREE:
return ENCODED_TYPE_TREE;
case OBJ_BLOB:
return ENCODED_TYPE_BLOB;
case OBJ_TAG:
return ENCODED_TYPE_TAG;
default:
throw new IllegalArgumentException("Bad object type: " + typeCode);
}
}
/**
* Parse an encoded type string into a type constant.
*
* @param id
* object id this type string came from; may be null if that is
* not known at the time the parse is occurring.
* @param typeString
* string version of the type code.
* @param endMark
* character immediately following the type string. Usually ' '
* (space) or '\n' (line feed).
* @param offset
* position within <code>typeString</code> where the parse
* should start. Updated with the new position (just past
* <code>endMark</code> when the parse is successful.
* @return a type code constant (one of {@link #OBJ_BLOB},
* {@link #OBJ_COMMIT}, {@link #OBJ_TAG}, {@link #OBJ_TREE}.
* @throws CorruptObjectException
* there is no valid type identified by <code>typeString</code>.
*/
public static int decodeTypeString(final AnyObjectId id,
final byte[] typeString, final byte endMark,
final MutableInteger offset) throws CorruptObjectException {
try {
int position = offset.value;
switch (typeString[position]) {
case 'b':
if (typeString[position + 1] != 'l'
|| typeString[position + 2] != 'o'
|| typeString[position + 3] != 'b'
|| typeString[position + 4] != endMark)
throw new CorruptObjectException(id, "invalid type");
offset.value = position + 5;
return Constants.OBJ_BLOB;
case 'c':
if (typeString[position + 1] != 'o'
|| typeString[position + 2] != 'm'
|| typeString[position + 3] != 'm'
|| typeString[position + 4] != 'i'
|| typeString[position + 5] != 't'
|| typeString[position + 6] != endMark)
throw new CorruptObjectException(id, "invalid type");
offset.value = position + 7;
return Constants.OBJ_COMMIT;
case 't':
switch (typeString[position + 1]) {
case 'a':
if (typeString[position + 2] != 'g'
|| typeString[position + 3] != endMark)
throw new CorruptObjectException(id, "invalid type");
offset.value = position + 4;
return Constants.OBJ_TAG;
case 'r':
if (typeString[position + 2] != 'e'
|| typeString[position + 3] != 'e'
|| typeString[position + 4] != endMark)
throw new CorruptObjectException(id, "invalid type");
offset.value = position + 5;
return Constants.OBJ_TREE;
default:
throw new CorruptObjectException(id, "invalid type");
}
default:
throw new CorruptObjectException(id, "invalid type");
}
} catch (ArrayIndexOutOfBoundsException bad) {
throw new CorruptObjectException(id, "invalid type");
}
}
/**
* Convert an integer into its decimal representation.
*
* @param s
* the integer to convert.
* @return a decimal representation of the input integer. The returned array
* is the smallest array that will hold the value.
*/
public static byte[] encodeASCII(final long s) {
return encodeASCII(Long.toString(s));
}
public static byte[] encodeASCII(final String s) {
final byte[] r = new byte[s.length()];
for (int k = r.length - 1; k >= 0; k
final char c = s.charAt(k);
if (c > 127)
throw new IllegalArgumentException("Not ASCII string: " + s);
r[k] = (byte) c;
}
return r;
}
/**
* Convert a string to a byte array in the standard character encoding.
*
* @param str
* the string to convert. May contain any Unicode characters.
* @return a byte array representing the requested string, encoded using the
* default character encoding (UTF-8).
* @see #CHARACTER_ENCODING
*/
public static byte[] encode(final String str) {
final ByteBuffer bb = Constants.CHARSET.encode(str);
final int len = bb.limit();
if (bb.hasArray() && bb.arrayOffset() == 0) {
final byte[] arr = bb.array();
if (arr.length == len)
return arr;
}
final byte[] arr = new byte[len];
bb.get(arr);
return arr;
}
static {
if (OBJECT_ID_LENGTH != newMessageDigest().getDigestLength())
throw new LinkageError("Incorrect OBJECT_ID_LENGTH.");
CHARSET = Charset.forName(CHARACTER_ENCODING);
}
private Constants() {
// Hide the default constructor
}
}
|
/* This class is part of the XP framework's EAS connectivity
*
* $Id$
*/
package net.xp_framework.easc.unittest;
import org.junit.Test;
import static org.junit.Assert.*;
import static net.xp_framework.easc.protocol.standard.Serializer.*;
public class SerializerTest {
@Test public void serializeString() {
assertEquals("s:11:\"Hello World\";", serialize("Hello World"));
}
@Test public void serializeCharPrimitive() {
assertEquals("s:1:\"X\";", serialize('X'));
}
@Test public void serializeUmlautCharPrimitive() {
assertEquals("s:1:\"\";", serialize(''));
}
@Test public void serializeBytePrimitive() {
assertEquals("i:16;", serialize((byte)16));
assertEquals("i:-16;", serialize((byte)-16));
}
@Test public void serializeShortPrimitive() {
assertEquals("i:1214;", serialize((short)1214));
assertEquals("i:-1214;", serialize((short)-1214));
}
@Test public void serializeIntPrimitive() {
assertEquals("i:6100;", serialize(6100));
assertEquals("i:-6100;", serialize(-6100));
}
@Test public void serializeLongPrimitive() {
assertEquals("i:6100;", serialize(6100L));
assertEquals("i:-6100;", serialize(-6100L));
}
@Test public void serializeDoublePrimitive() {
assertEquals("d:0.1;", serialize(0.1));
assertEquals("d:-0.1;", serialize(-0.1));
}
@Test public void serializeFloatPrimitive() {
assertEquals("d:0.1;", serialize(0.1f));
assertEquals("d:-0.1;", serialize(-0.1f));
}
@Test public void serializeBooleanPrimitive() {
assertEquals("b:1;", serialize(true));
assertEquals("b:0;", serialize(false));
}
}
|
package org.modmine.web;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.actions.TilesAction;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.query.PathQueryExecutor;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.api.results.ResultElement;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.session.SessionMethods;
import org.json.JSONObject;
import org.modmine.web.logic.ModMineUtil;
/**
* Class that generates heatMap data for a list of genes or exons.
*
* @author Sergio
* @author Fengyuan Hu
*
*/
public class HeatMapController extends TilesAction
{
protected static final Logger LOG = Logger.getLogger(HeatMapController.class);
// TO be visualised in the CellLine heatmap
private static final String[] EXPRESSION_ORDERED_CONDITION_CELLLINE = {"CME L1", "Sg4",
"ML-DmD11", "ML-DmD20-c2", "ML-DmD20-c5", "Kc167", "GM2", "S2-DRSC", "S2R+", "S1",
"1182-4H", "ML-DmD16-c3", "ML-DmD32", "ML-DmD17-c3", "ML-DmD8", "CME W1 Cl.8+", "ML-DmD9",
"ML-DmBG1-c1", "ML-DmD21", "ML-DmD4-c1", "ML-DmBG3-c2", "S3", "CME W2", "mbn2",
"ML-DmBG2-c2"};
// TO be visualised in the DevelopmentalStage heatmap
private static final String[] EXPRESSION_ORDERED_CONDITION_DEVELOPMENTALSTAGE = {"Embryo 0-2 h",
"Embryo 2-4 h", "Embryo 4-6 h", "Embryo 6-8 h", "emb 8-10h",
"emb 10-12h", "emb 12-14h", "emb 14-16h", "emb 16-18h", "emb 18-20h", "emb 20-22h",
"emb 22-24h", "L1 stage larvae", "L2 stage larvae", "L3 stage larvae 12hr",
"L3 stage larvae dark blue", "L3 stage larvae light blue", "L3 stage larvae clear",
"White prepupae (WPP)", "White prepupae (WPP) 12 h", "White prepupae (WPP) 24 h",
"White prepupae (WPP) 2days", "White prepupae (WPP) 3days", "White prepupae (WPP) 4days",
"Adult F Ecl 1day", "Adult M Ecl 1day", "Adult F Ecl 5day", "Adult M Ecl 5day",
"Adult F Ecl 30day", "Adult M Ecl 30day"};
// Separate two sets of conditions
private static final List<String> EXPRESSION_CONDITION_LIST_CELLLINE = Arrays
.asList(EXPRESSION_ORDERED_CONDITION_CELLLINE);
private static final List<String> EXPRESSION_CONDITION_LIST_DEVELOPMENTALSTAGE = Arrays
.asList(EXPRESSION_ORDERED_CONDITION_DEVELOPMENTALSTAGE);
private static final String CELLLINE = "cellLine";
private static final String DEVSTAGE = "developmentalStage";
private static final String GENE = "gene";
private static final String EXON = "exon";
/**
* {@inheritDoc}
*/
@Override
public ActionForward execute(ComponentContext context,
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ObjectStore os = im.getObjectStore();
InterMineBag bag = (InterMineBag) request.getAttribute("bag");
Model model = im.getModel();
Profile profile = SessionMethods.getProfile(session);
PathQueryExecutor executor = im.getPathQueryExecutor(profile);
try {
findExpression(request, model, bag, executor, os);
} catch (ObjectStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void findExpression(HttpServletRequest request, Model model,
InterMineBag bag, PathQueryExecutor executor,
ObjectStore os) throws ObjectStoreException {
DecimalFormat df = new DecimalFormat("
String expressionType = bag.getType().toLowerCase();
// get the 2 JSON strings
String expressionScoreJSONCellLine =
getJSONString(model, bag, executor, expressionType, CELLLINE);
String expressionScoreJSONDevelopmentalStage =
getJSONString(model, bag, executor, expressionType, DEVSTAGE);
// set the attributes
request.setAttribute("expressionScoreJSONCellLine",
expressionScoreJSONCellLine);
request.setAttribute("expressionScoreJSONDevelopmentalStage",
expressionScoreJSONDevelopmentalStage);
// To make a legend for the heat map
Double logExpressionScoreMin = 0.0;
Double logExpressionScoreMax = 0.0;
if (expressionType.equals(GENE)) {
logExpressionScoreMin =
Math.log(ModMineUtil.getMinGeneExpressionScore(os) + 1) / Math.log(2);
logExpressionScoreMax =
Math.log(ModMineUtil.getMaxGeneExpressionScore(os) + 1) / Math.log(2);
}
if (expressionType.equals(EXON)) {
logExpressionScoreMin =
Math.log(ModMineUtil.getMinExonExpressionScore(os) + 1) / Math.log(2);
logExpressionScoreMax =
Math.log(ModMineUtil.getMaxExonExpressionScore(os) + 1) / Math.log(2);
}
request.setAttribute("minExpressionScore", df.format(logExpressionScoreMin));
request.setAttribute("maxExpressionScore", df.format(logExpressionScoreMax));
request.setAttribute("maxExpressionScoreCeiling", Math.ceil(logExpressionScoreMax));
request.setAttribute("ExpressionType", expressionType);
request.setAttribute("FeatureCount", bag.getSize());
// request.setAttribute("FeatureCount", geneExpressionScoreMapDevelopmentalStage.size());
}
private List<String> getConditionsList(String conditionType) {
if (conditionType.equalsIgnoreCase(CELLLINE)) {
return EXPRESSION_CONDITION_LIST_CELLLINE;
}
if (conditionType.equalsIgnoreCase(DEVSTAGE)) {
return EXPRESSION_CONDITION_LIST_DEVELOPMENTALSTAGE;
}
return null;
}
private String getJSONString (Model model,
InterMineBag bag, PathQueryExecutor executor,
String expressionType, String conditionType) {
String expressionScoreJSON = null;
// Key: gene symbol or PID - Value: list of ExpressionScore objs
Map<String, List<ExpressionScore>> expressionScoreMap =
new LinkedHashMap<String, List<ExpressionScore>>();
PathQuery query = new PathQuery(model);
query = queryExpressionScore(bag, conditionType, query);
ExportResultsIterator result = executor.execute(query);
LOG.info("GGS QUERY: -->" + query + "<--");
List<String> conditions = getConditionsList(conditionType);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String id = (String) row.get(0).getField();
String symbol = (String) row.get(1).getField();
Double score = (Double) row.get(2).getField();
String condition = (String) row.get(3).getField();
// String dCCid = (String) row.get(4).getField();
if (symbol == null) {
symbol = id;
}
symbol = fixParenthesis(symbol);
if (!expressionScoreMap.containsKey(symbol)) {
// Create a list with space for n (size of conditions) ExpressionScore
List<ExpressionScore> expressionScoreList = new ArrayList<ExpressionScore>(
Collections.nCopies(conditions.size(),
new ExpressionScore()));
ExpressionScore aScore = new ExpressionScore(condition,
score, id, symbol);
expressionScoreList.set(conditions.indexOf(condition), aScore);
expressionScoreMap.put(symbol, expressionScoreList);
} else {
ExpressionScore aScore = new ExpressionScore(
condition, score, id, symbol);
expressionScoreMap
.get(symbol).set(conditions.indexOf(condition), aScore);
}
}
expressionScoreJSON = parseToJSON(StringUtils.capitalize(conditionType),
expressionScoreMap);
LOG.info("GGS JSON: " + expressionScoreJSON);
return expressionScoreJSON;
}
/**
* To encode '(' and ')', which canvasExpress uses as separator in the cluster tree building
* @param symbol
* @return a fixed symbol
*/
private String fixParenthesis(String symbol) {
if (symbol.contains("(")) {
symbol = symbol.replace("(", "%28");
}
if (symbol.contains(")")) {
symbol = symbol.replace(")", "%29");
}
return symbol;
}
private PathQuery queryExpressionScore(InterMineBag bag, String conditionType, PathQuery query) {
String bagType = bag.getType();
String type = bagType.toLowerCase();
// Add views
query.addViews(
bagType + "ExpressionScore." + type + ".primaryIdentifier",
bagType + "ExpressionScore." + type + ".symbol",
bagType + "ExpressionScore.score",
bagType + "ExpressionScore." + conditionType + ".name"
// ,bagType + "ExpressionScore.submission.DCCid"
);
// Add orderby
query.addOrderBy(bagType + "ExpressionScore." + type
+ ".primaryIdentifier", OrderDirection.ASC);
// Add constraints and you can edit the constraint values below
query.addConstraint(Constraints.in(bagType + "ExpressionScore." + type,
bag.getName()));
return query;
}
// /**
// * Create a path query to retrieve gene expression score.
// *
// * @param bagName the bag includes the query genes
// * @param query a pathquery
// * @return the pathquery
// */
// private PathQuery queryGeneExpressionScore(String bagName, PathQuery query) {
// // Add views
// query.addViews(
// "GeneExpressionScore.gene.primaryIdentifier",
// "GeneExpressionScore.gene.symbol",
// "GeneExpressionScore.score",
// "GeneExpressionScore.cellLine.name",
// "GeneExpressionScore.developmentalStage.name",
// "GeneExpressionScore.submission.DCCid"
// // Add orderby
// query.addOrderBy("GeneExpressionScore.gene.primaryIdentifier", OrderDirection.ASC);
// // Add constraints and you can edit the constraint values below
// query.addConstraint(Constraints.in("GeneExpressionScore.gene", bagName));
// // Add join status
// query.setOuterJoinStatus("GeneExpressionScore.cellLine", OuterJoinStatus.OUTER);
// query.setOuterJoinStatus("GeneExpressionScore.developmentalStage", OuterJoinStatus.OUTER);
// return query;
/**
* Parse expressionScoreMap to JSON string
*
* @param conditionType CellLine or DevelopmentalStage
* @param geneExpressionScoreMap
* @return json string
*/
private String parseToJSON(String conditionType,
Map<String, List<ExpressionScore>> expressionScoreMap) {
// vars - conditions
// smps - genes/exons
List<String> vars = new ArrayList<String>();
if ("CellLine".equals(conditionType)) {
vars = EXPRESSION_CONDITION_LIST_CELLLINE;
} else if ("DevelopmentalStage".equals(conditionType)) {
vars = EXPRESSION_CONDITION_LIST_DEVELOPMENTALSTAGE;
} else {
String msg = "Wrong argument: " + conditionType
+ ". Should be 'CellLine' or 'DevelopmentalStage'";
throw new RuntimeException(msg);
}
Map<String, Object> heatmapData = new LinkedHashMap<String, Object>();
Map<String, Object> yInHeatmapData = new LinkedHashMap<String, Object>();
List<String> smps = new ArrayList<String>(expressionScoreMap.keySet());
List<String> desc = new ArrayList<String>();
desc.add("Intensity");
// List<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
// for (String seqenceFeature : expressionScoreMap.keySet()) {
// ArrayList<Double> dataLine = new ArrayList<Double>();
// for (ExpressionScore es : expressionScoreMap.get(seqenceFeature)) {
// dataLine.add(es.getLogScore());
// data.add(dataLine);
double[][] data = new double[smps.size()][vars.size()];
for (int i = 0; i < smps.size(); i++) {
String seqenceFeature = smps.get(i);
for (int j = 0; j < vars.size(); j++) {
data[i][j] = expressionScoreMap.get(seqenceFeature).get(j).getLogScore();
}
}
// Rotate data
double[][] rotatedData = new double[vars.size()][smps.size()];
int ii = 0;
for (int i = 0; i < vars.size(); i++) {
int jj = 0;
for (int j = 0; j < smps.size(); j++) {
rotatedData[ii][jj] = data[j][i];
jj++;
}
ii++;
}
yInHeatmapData.put("vars", vars);
yInHeatmapData.put("smps", smps);
yInHeatmapData.put("desc", desc);
yInHeatmapData.put("data", rotatedData);
heatmapData.put("y", yInHeatmapData);
JSONObject jo = new JSONObject(heatmapData);
return jo.toString();
}
}
|
package org.openlca.app.editors;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Stack;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
import org.openlca.app.M;
import org.openlca.app.editors.comments.CommentControl;
import org.openlca.app.navigation.Navigator;
import org.openlca.app.rcp.images.Icon;
import org.openlca.app.rcp.images.Images;
import org.openlca.app.util.Colors;
import org.openlca.app.util.Controls;
import org.openlca.app.util.UI;
import org.openlca.core.model.CategorizedEntity;
import org.openlca.core.model.Category;
import org.openlca.core.model.Version;
/**
* This is the general info section that each editor has: name, description,
* etc.
*/
public class InfoSection {
private CategorizedEntity entity;
private final ModelEditor<?> editor;
private Composite container;
private Label versionLabel;
public InfoSection(ModelEditor<?> editor) {
this.entity = editor.getModel();
this.editor = editor;
}
public void render(Composite body, FormToolkit tk) {
container = UI.formSection(body, tk, M.GeneralInformation, 3);
Widgets.text(container, M.Name, "name", editor, tk);
Widgets.multiText(container, M.Description, "description", editor, tk);
if (entity.category != null) {
new Label(container, SWT.NONE).setText(M.Category);
createBreadcrumb(container);
new CommentControl(container, tk, "category", editor.getComments());
} else if (editor.hasComment("category")) {
new Label(container, SWT.NONE).setText(M.Category);
UI.filler(container);
new CommentControl(container, tk, "category", editor.getComments());
}
createVersionText(tk);
Text uuidText = UI.formText(container, tk, "UUID");
uuidText.setEditable(false);
if (entity.refId != null)
uuidText.setText(entity.refId);
UI.filler(container, tk);
createDateText(tk);
createTags(tk);
}
private void createVersionText(FormToolkit tk) {
UI.formLabel(container, tk, M.Version);
var comp = tk.createComposite(container);
var layout = UI.gridLayout(comp, 3);
layout.marginWidth = 0;
layout.marginHeight = 0;
versionLabel = tk.createLabel(comp,
Version.asString(entity.version));
editor.onSaved(() -> {
entity = editor.getModel();
versionLabel.setText(Version.asString(entity.version));
});
new VersionLink(comp, tk, VersionLink.MAJOR);
new VersionLink(comp, tk, VersionLink.MINOR);
UI.filler(container, tk);
}
private void createDateText(FormToolkit tk) {
var format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
UI.formLabel(container, tk, M.LastChange);
Label text = UI.formLabel(container, tk, "");
if (entity.lastChange != 0) {
text.setText(format.format(new Date(entity.lastChange)));
}
editor.onSaved(() -> {
entity = editor.getModel();
text.setText(format.format(new Date(entity.lastChange)));
});
UI.filler(container, tk);
}
private void createBreadcrumb(Composite parent) {
Stack<Category> stack = new Stack<>();
Category current = entity.category;
while (current != null) {
stack.push(current);
current = current.category;
}
Composite breadcrumb = new Composite(parent, SWT.NONE);
UI.gridLayout(breadcrumb, stack.size() * 2 - 1, 0, 0);
while (!stack.isEmpty()) {
current = stack.pop();
Hyperlink link;
if (current.category == null) {
link = new ImageHyperlink(breadcrumb, SWT.NONE);
((ImageHyperlink) link).setImage(Images.get(current));
} else {
new Label(breadcrumb, SWT.NONE).setText(" > ");
link = new Hyperlink(breadcrumb, SWT.NONE);
}
link.setText(current.name);
link.addHyperlinkListener(new CategoryLinkClick(current));
link.setForeground(Colors.linkBlue());
}
}
private void createTags(FormToolkit tk) {
UI.formLabel(container, tk, "Tags");
var comp = tk.createComposite(container);
UI.gridData(comp, true, false);
UI.gridLayout(comp, 2, 10, 0);
var btn = tk.createButton(comp, "Add a tag", SWT.NONE);
var tagComp = tk.createComposite(comp);
UI.gridLayout(tagComp, 1);
UI.gridData(tagComp, true, false);
var innerComp = new AtomicReference<Composite>();
// render function for the tag list
Runnable render = () -> {
var inner = innerComp.get();
if (inner != null) {
inner.dispose();
}
inner = tk.createComposite(tagComp);
UI.gridData(inner, true, false);
innerComp.set(inner);
var tags = Tags.of(editor.getModel());
UI.gridLayout(inner, tags.length, 5, 0);
for (var tag : tags) {
new Tag(tag, inner, tk);
}
List.of(inner, tagComp, comp, container)
.forEach(it -> it.layout());
};
render.run();
Controls.onSelect(btn, _e -> {
Tags.add(editor.getModel(), UUID.randomUUID().toString().substring(0, 8));
render.run();
editor.setDirty(true);
});
UI.filler(container, tk);
}
public Composite getContainer() {
return container;
}
private static class CategoryLinkClick extends HyperlinkAdapter {
private final Category category;
private CategoryLinkClick(Category category) {
this.category = category;
}
@Override
public void linkActivated(HyperlinkEvent e) {
Navigator.select(category);
}
}
private class VersionLink extends HyperlinkAdapter {
static final int MAJOR = 1;
static final int MINOR = 2;
private final int type;
private final ImageHyperlink link;
private Image hoverIcon = null;
private Image icon = null;
public VersionLink(Composite parent, FormToolkit toolkit, int type) {
this.type = type;
link = toolkit.createImageHyperlink(parent, SWT.TOP);
link.addHyperlinkListener(this);
configureLink();
}
private void configureLink() {
String tooltip;
if (type == MAJOR) {
tooltip = M.UpdateMajorVersion;
hoverIcon = Icon.UP.get();
icon = Icon.UP_DISABLED.get();
} else {
tooltip = M.UpdateMinorVersion;
hoverIcon = Icon.UP_DOUBLE.get();
icon = Icon.UP_DOUBLE_DISABLED.get();
}
link.setToolTipText(tooltip);
link.setActiveImage(hoverIcon);
link.setImage(icon);
}
@Override
public void linkActivated(HyperlinkEvent e) {
if (entity == null || versionLabel == null)
return;
Version version = new Version(entity.version);
if (type == MAJOR)
version.incMajor();
else
version.incMinor();
entity.version = version.getValue();
versionLabel.setText(version.toString());
editor.setDirty(true);
}
@Override
public void linkEntered(HyperlinkEvent e) {
link.setImage(hoverIcon);
}
@Override
public void linkExited(HyperlinkEvent e) {
link.setImage(icon);
}
}
private static class Tag {
private final ImageHyperlink link;
Tag(String text, Composite comp, FormToolkit tk) {
link = tk.createImageHyperlink(comp, SWT.NONE);
link.setText(text);
link.setImage(Icon.DELETE_DISABLED.get());
link.setBackground(Colors.fromHex("#e8eaf6"));
link.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseEnter(MouseEvent e) {
link.setImage(Icon.DELETE.get());
}
@Override
public void mouseExit(MouseEvent e) {
link.setImage(Icon.DELETE_DISABLED.get());
}
});
}
void dispose() {
if (link.isDisposed())
return;
link.dispose();
}
}
}
|
package cx2x.xcodeml.helper;
import cx2x.xcodeml.exception.*;
import cx2x.xcodeml.xelement.*;
import cx2x.xcodeml.xnode.Xattr;
import cx2x.xcodeml.xnode.Xcode;
import cx2x.xcodeml.xnode.Xnode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* The class XelementHelper contains only static method to help manipulating the
* raw Elements in the XcodeML representation by using the abstracted Xelements.
*
* @author clementval
*/
public class XelementHelper {
/**
* Get a text attribute value from an element.
* @param el The element in which the attribute is searched.
* @param attrName The name of the attribute to be found.
* @return The attribute's value if the attribute is found. Null otherwise.
*/
public static String getAttributeValue(XbaseElement el, String attrName){
if(el == null || el.getBaseElement() == null){
return null;
}
NamedNodeMap attributes = el.getBaseElement().getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
if(attributes.item(j).getNodeName().equals(attrName)){
return attributes.item(j).getNodeValue();
}
}
return null;
}
/**
* Get a boolean attribute value from an element.
* @param el The element in which the attribute is searched.
* @param attrName The name of the attribute to be found.
* @return The attribute's value if the attribute is found. Null otherwise.
*/
public static boolean getBooleanAttributeValue(XbaseElement el,
String attrName) {
if (el == null || el.getBaseElement() == null) {
return false;
}
String value = XelementHelper.getAttributeValue(el, attrName);
return value != null && value.equals(XelementName.TRUE);
}
/**
* Find a function definition according to a function call.
* @param xcodeml The XcodeML program to search in.
* @param fctCall The function call used to find the function definition.
* @return A function definition element if found. Null otherwise.
*/
public static XfunctionDefinition findFunctionDefinition(XcodeProgram xcodeml,
Xnode fctCall)
{
if(xcodeml.getBaseElement() == null){
return null;
}
String name = fctCall.findNode(Xcode.NAME).getValue();
NodeList nList = xcodeml.getBaseElement().getElementsByTagName(XelementName.FCT_DEFINITION);
for (int i = 0; i < nList.getLength(); i++) {
Node fctDefNode = nList.item(i);
if (fctDefNode.getNodeType() == Node.ELEMENT_NODE) {
XbaseElement dummyFctDef = new XbaseElement((Element)fctDefNode);
Xname fctDefName = findName(dummyFctDef, false);
if(name != null && fctDefName.isIdentical(name)){
return new XfunctionDefinition(dummyFctDef.getBaseElement());
}
}
}
return null;
}
/**
* Find a function definition in a module definition.
* @param module Module definition in which we search for the function
* definition.
* @param name Name of the function to be found.
* @return A function definition element if found. Null otherwise.
*/
public static XfunctionDefinition findFunctionDefinitionInModule(
XmoduleDefinition module, String name)
{
if(module.getElement() == null){
return null;
}
NodeList nList = module.getElement().
getElementsByTagName(XelementName.FCT_DEFINITION);
for (int i = 0; i < nList.getLength(); i++) {
Node n = nList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
XfunctionDefinition fctDef = new XfunctionDefinition((Element)n);
if(fctDef.getName().getValue().equals(name)){
return fctDef;
}
}
}
return null;
}
/**
* Find all array references elements in a given body and give var name.
* @param parent The body element to search for the array references.
* @param arrayName Name of the array for the array reference to be found.
* @return A list of all array references found.
*/
public static List<Xnode> getAllArrayReferences(Xnode parent,
String arrayName)
{
List<Xnode> references = new ArrayList<>();
NodeList nList = parent.getElement().
getElementsByTagName(XelementName.F_ARRAY_REF);
for (int i = 0; i < nList.getLength(); i++) {
Node n = nList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Xnode ref = new Xnode((Element) n);
if(ref.find(Xcode.VARREF, Xcode.VAR).getValue().toLowerCase().
equals(arrayName.toLowerCase()))
{
references.add(ref);
}
}
}
return references;
}
/**
* Demote an array reference to a var reference.
* @param ref The array reference to be modified.
*/
public static void demoteToScalar(Xnode ref){
Xnode var = ref.find(Xcode.VARREF, Xcode.VAR).cloneObject();
insertAfter(ref, var);
ref.delete();
}
/**
* Demote an array reference to a reference with fewer dimensions.
* @param ref The array reference to be modified.
* @param keptDimensions List of dimensions to be kept. Dimension index starts
* at 1.
*/
public static void demote(Xnode ref, List<Integer> keptDimensions){
for(int i = 1; i < ref.getChildren().size(); ++i){
if(!keptDimensions.contains(i)){
ref.getChild(i).delete();
}
}
}
/**
* Retrieve the index ranges of an array notation.
* @param arrayRef The array reference statements to extract the ranges from.
* @return A list if indexRanges elements.
*/
public static List<Xnode> getIdxRangesFromArrayRef(Xnode arrayRef){
List<Xnode> ranges = new ArrayList<>();
if(arrayRef.Opcode() != Xcode.FARRAYREF){
return ranges;
}
for(Xnode el : arrayRef.getChildren()){
if(el.Opcode() == Xcode.INDEXRANGE){
ranges.add(el);
}
}
return ranges;
}
/**
* Compare two list of indexRange.
* @param list1 First list of indexRange.
* @param list2 Second list of indexRange.
* @return True if the indexRange at the same position in the two list are all
* identical. False otherwise.
*/
public static boolean compareIndexRanges(List<Xnode> list1,
List<Xnode> list2){
if(list1.size() != list2.size()){
return false;
}
for(int i = 0; i < list1.size(); ++i){
if(!isIndexRangeIdentical(list1.get(i), list2.get(i))){
return false;
}
}
return true;
}
/**
* <pre>
* Intersect two sets of elements in XPath 1.0
*
* This method use Xpath to select the correct nodes. Xpath 1.0 does not have
* the intersect operator but only union. By using the Kaysian Method, we can
* it is possible to express the intersection of two node sets.
*
* $set1[count(.|$set2)=count($set2)]
*
* </pre>
* @param s1 First set of element.
* @param s2 Second set of element.
* @return Xpath query that performs the intersect operator between s1 and s2.
*/
private static String xPathIntersect(String s1, String s2){
return String.format("%s[count(.|%s)=count(%s)]", s1, s2, s2);
}
/**
* <pre>
* Find all assignment statement from a node until the end pragma.
*
* We intersect all assign statments which are next siblings of
* the "from" element with all the assign statements which are previous
* siblings of the ending pragma.
* </pre>
*
* @param from The element from which the search is initiated.
* @param endPragma Value of the end pragma. Search will be performed until
* there.
* @return A list of all assign statements found. List is empty if no
* statements are found.
*/
public static List<Xnode> getArrayAssignInBlock(Xnode from, String endPragma){
/* Define all the assign element with array refs which are next siblings of
* the "from" element */
String s1 = String.format(
"following-sibling::%s[%s]",
XelementName.F_ASSIGN_STMT,
XelementName.F_ARRAY_REF
);
/* Define all the assign element with array refs which are previous siblings
* of the end pragma element */
String s2 = String.format(
"following-sibling::%s[text()=\"%s\"]/preceding-sibling::%s[%s]",
XelementName.PRAGMA_STMT,
endPragma,
XelementName.F_ASSIGN_STMT,
XelementName.F_ARRAY_REF
);
// Use the Kaysian method to express the intersect operator
String intersect = XelementHelper.xPathIntersect(s1, s2);
return getFromXpath(from, intersect);
}
/**
* Get all array references in the siblings of the given element.
* @param from Element to start from.
* @param identifier Array name value.
* @return List of all array references found. List is empty if nothing is
* found.
*/
public static List<Xnode> getAllArrayReferencesInSiblings(Xnode from,
String identifier)
{
String s1 = String.format("following-sibling::*//%s[%s[%s[text()=\"%s\"]]]",
XelementName.F_ARRAY_REF,
XelementName.VAR_REF,
XelementName.VAR,
identifier
);
return getFromXpath(from, s1);
}
/**
* Get the first assignment statement for an array reference.
* @param from Statement to look from.
* @param arrayName Identifier of the array.
* @return The assignement statement if found. Null otherwise.
*/
public static Xnode getFirstArrayAssign(Xnode from, String arrayName){
String s1 = String.format(
"following::%s[%s[%s[%s[text()=\"%s\"]] and position()=1]]",
XelementName.F_ASSIGN_STMT,
XelementName.F_ARRAY_REF,
XelementName.VAR_REF,
XelementName.VAR,
arrayName
);
try {
NodeList output = evaluateXpath(from.getElement(), s1);
if(output.getLength() == 0){
return null;
}
Element assign = (Element) output.item(0);
return new Xnode(assign);
} catch (XPathExpressionException ignored) {
return null;
}
}
/**
* Find all the nested do statement groups following the inductions iterations
* define in inductionVars and being located between the "from" element and
* the end pragma.
* @param from Element from which the search is started.
* @param endPragma End pragma that terminates the search block.
* @param inductionVars Induction variables that define the nested group to
* locates.
* @return List of do statements elements (outter most loops for each nested
* group) found between the "from" element and the end pragma.
*/
public static List<Xnode> findDoStatement(Xnode from, Xnode endPragma,
List<String> inductionVars)
{
/* s1 is selecting all the nested do statement groups that meet the criteria
* from the "from" element down to the end of the block. */
String s1 = "following::";
String dynamic_part_s1 = "";
for(int i = inductionVars.size() - 1; i >= 0; --i){
/*
* Here is example of there xpath query format for 1,2 and 3 nested loops
*
* FdoStatement[Var[text()="induction_var"]]
*
* FdoStatement[Var[text()="induction_var"] and
* body[FdoStatement[Var[text()="induction_var"]]]
*
* FdoStatement[Var[text()="induction_var"] and
* body[FdoStatement[Var[text()="induction_var"] and
* body[FdoStatement[Var[text()="induction_var"]]]]
*/
String tempQuery;
if(i == inductionVars.size() - 1) { // first iteration
tempQuery = String.format("%s[%s[text()=\"%s\"]]",
XelementName.DO_STMT,
XelementName.VAR,
inductionVars.get(i));
} else {
tempQuery = String.format("%s[%s[text()=\"%s\"] and %s[%s]]",
XelementName.DO_STMT,
XelementName.VAR,
inductionVars.get(i),
XelementName.BODY,
dynamic_part_s1); // Including previsouly formed xpath query
}
dynamic_part_s1 = tempQuery;
}
s1 = s1 + dynamic_part_s1;
List<Xnode> doStatements = new ArrayList<>();
try {
NodeList output = evaluateXpath(from.getElement(), s1);
for (int i = 0; i < output.getLength(); i++) {
Element el = (Element) output.item(i);
Xnode doStmt = new Xnode(el);
if(doStmt.getLineNo() != 0 &&
doStmt.getLineNo() < endPragma.getLineNo())
{
doStatements.add(doStmt);
}
}
} catch (XPathExpressionException ignored) {
}
return doStatements;
}
/**
* Evaluates an Xpath expression and return its result as a NodeList.
* @param from Element to start the evaluation.
* @param xpath Xpath expression.
* @return Result of evaluation as a NodeList.
* @throws XPathExpressionException if evaluation fails.
*/
private static NodeList evaluateXpath(Element from, String xpath)
throws XPathExpressionException
{
XPathExpression ex = XPathFactory.newInstance().newXPath().compile(xpath);
return (NodeList)ex.evaluate(from, XPathConstants.NODESET);
}
/**
* Find all array references in the next children that match the given
* criteria.
*
* This methods use powerful Xpath expression to locate the correct nodes in
* the AST
*
* Here is an example of such a query that return all node that are array
* references for the array "array6" with an offset of 0 -1
*
* //FarrayRef[varRef[Var[text()="array6"]] and arrayIndex and
* arrayIndex[minusExpr[Var and FintConstant[text()="1"]]]]
*
* @param from The element from which the search is initiated.
* @param identifier Identifier of the array.
* @param offsets List of offsets to be search for.
* @return A list of all array references found.
*/
public static List<Xnode> getAllArrayReferencesByOffsets(Xnode from,
String identifier, List<Integer> offsets)
{
String offsetXpath = "";
for (int i = 0; i < offsets.size(); ++i){
if(offsets.get(i) == 0){
offsetXpath +=
String.format("%s[position()=%s and %s]",
XelementName.ARRAY_INDEX,
i+1,
XelementName.VAR
);
} else if(offsets.get(i) > 0) {
offsetXpath +=
String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]",
XelementName.ARRAY_INDEX,
i+1,
XelementName.MINUS_EXPR,
XelementName.VAR,
XelementName.F_INT_CONST,
offsets.get(i));
} else {
offsetXpath +=
String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]",
XelementName.ARRAY_INDEX,
i+1,
XelementName.MINUS_EXPR,
XelementName.VAR,
XelementName.F_INT_CONST,
Math.abs(offsets.get(i)));
}
if(i != offsets.size()-1){
offsetXpath += " and ";
}
}
// Start of the Xpath query
String xpathQuery = String.format(".//%s[%s[%s[text()=\"%s\"]] and %s]",
XelementName.F_ARRAY_REF,
XelementName.VAR_REF,
XelementName.VAR,
identifier,
offsetXpath
);
return getFromXpath(from, xpathQuery);
}
/**
* Find all real constants in the direct children of the given parent.
* @param parent Root element to search from.
* @return A list of all found real constants.
*/
public static List<XrealConstant> getRealConstants(XbaseElement parent){
List<XrealConstant> elements = new ArrayList<>();
Node n = parent.getBaseElement().getFirstChild();
while(n != null){
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
if(el.getTagName().equals(XelementName.F_REAL_CONST)) {
XrealConstant ref = new XrealConstant(el);
elements.add(ref);
}
}
n = n.getNextSibling();
}
return elements;
}
/**
* Find a pragma element in the previous nodes containing a given keyword.
* @param from Element to start from.
* @param keyword Keyword to be found in the pragma.
* @return The pragma if found. Null otherwise.
*/
public static Xnode findPreviousPragma(Xnode from, String keyword){
if(from == null || from.getElement() == null){
return null;
}
Node prev = from.getElement().getPreviousSibling();
Node parent = from.getElement();
do {
while (prev != null) {
if (prev.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) prev;
if (element.getTagName().equals(Xcode.FPRAGMASTATEMENT.code())
&& element.getTextContent().toLowerCase().
contains(keyword.toLowerCase()))
{
return new Xnode(element);
}
}
prev = prev.getPreviousSibling();
}
parent = parent.getParentNode();
prev = parent;
} while(parent != null);
return null;
}
/**
* Find var element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xvar object if found. Null otherwise.
*/
public static Xvar findVar(XbaseElement parent, boolean any){
return findXelement(parent, any, Xvar.class);
}
/**
* Find varRef element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A XvarRef object if found. Null otherwise.
*/
public static XvarRef findVarRef(XbaseElement parent, boolean any){
return findXelement(parent, any, XvarRef.class);
}
/**
* Find indexRange element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A XindexRange object if found. Null otherwise.
*/
public static XindexRange findIndexRange(XbaseElement parent, boolean any){
return findXelement(parent, any, XindexRange.class);
}
/**
* Find name element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xname object if found. Null otherwise.
*/
public static Xname findName(XbaseElement parent, boolean any){
return findXelement(parent, any, Xname.class);
}
/**
* Find value element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xvalue object if found. Null otherwise.
*/
public static Xvalue findValue(XbaseElement parent, boolean any){
return findXelement(parent, any, Xvalue.class);
}
/**
* Find lValueModel element at given position.
* @param parent Root element to search from.
* @param position Position of the element to be found in the parent children
* list.
* @return A XLValueModel object if found. Null otherwise.
*/
public static XLValueModel findLValueModel(XbaseElement parent, int position){
Element element = getXthChildElement(parent.getBaseElement(), position);
if(element == null){
return null;
}
switch (element.getTagName()) {
case XelementName.VAR:
return new XLValueModel(new Xvar(element));
case XelementName.F_ARRAY_REF:
return new XLValueModel(new XarrayRef(element));
case XelementName.F_CHAR_REF:
case XelementName.F_MEMBER_REF:
case XelementName.F_COARRAY_REF:
return null; // TODO when classes are available
default:
return null;
}
}
/**
* Find exprModel element at given position.
* @param parent Root element to search from.
* @param position Position of the element to be found in the parent children
* list.
* @return A XexprModel object if found. Null otherwise.
*/
public static XexprModel findExprModel(XbaseElement parent, int position){
/** An exprModel can be of the following type
* - FintConstant, FrealConstant, FcomplexConstant, FcharacterConstant,
* FlogicalConstant
* TODO FarrayConstructor, FstructConstructor
* - FarrayConstructor, FstructConstructor
* - Var
* TODO FcharacterRef, FmemberRef, FcoArrayRef
* - FarrayRef, FcharacterRef, FmemberRef, FcoArrayRef, varRef
* - functionCall
* - plusExpr, minusExpr, mulExpr, divExpr, FpowerExpr, FconcatExpr
* logEQExpr, logNEQExpr, logGEExpr, logGTExpr, logLEExpr, logLTExpr,
* logAndExpr, logOrExpr, logEQVExpr, logNEQVExpr, logNotExpr,
* unaryMinusExpr, userBinaryExpr, userUnaryExpr
* TODO FdoLoop
* - FdoLoop
*/
Element element = getXthChildElement(parent.getBaseElement(), position);
if(element == null){
return null;
}
switch (element.getTagName()){
case XelementName.F_INT_CONST:
return new XexprModel(new XintConstant(element));
case XelementName.F_REAL_CONST:
return new XexprModel(new XrealConstant(element));
case XelementName.F_LOGICAL_CONST:
return new XexprModel(new XlogicalConstant(element));
case XelementName.F_COMPLEX_CONST:
return new XexprModel(new XcomplexConstant(element));
case XelementName.F_CHAR_CONST:
return new XexprModel(new XcharacterConstant(element));
case XelementName.VAR:
return new XexprModel(new Xvar(element));
case XelementName.FCT_CALL:
return new XexprModel(new XfunctionCall(element));
case XelementName.F_ARRAY_REF:
return new XexprModel(new XarrayRef(element));
case XelementName.VAR_REF:
return new XexprModel(new XvarRef(element));
// binary expression
case XelementName.DIV_EXPR:
case XelementName.F_CONCAT_EXPR:
case XelementName.F_POWER_EXPR:
case XelementName.LOG_AND_EXPR:
case XelementName.LOG_EQ_EXPR:
case XelementName.LOG_EQV_EXPR:
case XelementName.LOG_GE_EXPR:
case XelementName.LOG_GT_EXPR:
case XelementName.LOG_LE_EXPR:
case XelementName.LOG_LT_EXPR:
case XelementName.LOG_NEQ_EXPR:
case XelementName.LOG_NEWV_EXPR:
case XelementName.LOG_OR_EXPR:
case XelementName.MINUS_EXPR:
case XelementName.MUL_EXPR:
case XelementName.PLUS_EXPR:
case XelementName.USER_BINARY_EXPR:
return new XexprModel(new XbinaryExpr(element));
// unary expression
case XelementName.LOG_NOT_EXPR:
case XelementName.UNARY_MINUS_EXPR:
case XelementName.USER_UNARY_EXPR:
return new XexprModel(new XunaryExpr(element));
default:
return null;
}
}
/**
* The inner element of a varRef is one of the following:
* - Var
* - FmemberRef
* - FarrayRef
* - FcharacterRef
* - FcoArrayRef
* @param parent The root element to search form.
* @return The varRef inner element as a XbaseElement derived type.
*/
public static XbaseElement findVarRefInnerElement(XbaseElement parent){
Element element = getFirstChildElement(parent.getBaseElement());
if(element == null){
return null;
}
switch (element.getTagName()) {
case XelementName.VAR:
return new Xvar(element);
case XelementName.F_MEMBER_REF:
return null; // TODO move to XmemberRef
case XelementName.F_ARRAY_REF:
return new XarrayRef(element);
case XelementName.F_CHAR_REF:
return null; // TODO move to XcharacterRef
case XelementName.F_COARRAY_REF:
return null; // TODO move to XcoArrayRef
default:
return null;
}
}
/**
* Find condition element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xcondition object if found. Null otherwise.
*/
public static Xcondition findCondition(XbaseElement parent, boolean any){
return findXelement(parent, any, Xcondition.class);
}
/**
* Find then element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xthen object if found. Null otherwise.
*/
public static Xthen findThen(XbaseElement parent, boolean any){
return findXelement(parent, any, Xthen.class);
}
/**
* Find else element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xelse object if found. Null otherwise.
*/
public static Xelse findElse(XbaseElement parent, boolean any){
return findXelement(parent, any, Xelse.class);
}
/**
* Find arguments element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A XargumentsTable object if found. Null otherwise.
*/
public static XargumentsTable findArgumentsTable(XbaseElement parent, boolean any){
return findXelement(parent, any, XargumentsTable.class);
}
/**
* Find lowerBound element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A XlowerBound object if found. Null otherwise.
*/
public static XlowerBound findLowerBound(XbaseElement parent, boolean any){
return findXelement(parent, any, XlowerBound.class);
}
/**
* Find upperBound element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A XupperBound object if found. Null otherwise.
*/
public static XupperBound findUpperBound(XbaseElement parent, boolean any){
return findXelement(parent, any, XupperBound.class);
}
/**
* Find step element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xstep object if found. Null otherwise.
*/
public static Xstep findStep(XbaseElement parent, boolean any){
return findXelement(parent, any, Xstep.class);
}
/**
* Find body element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xbody object if found. Null otherwise.
*/
public static Xbody findBody(XbaseElement parent, boolean any){
return findXelement(parent, any, Xbody.class);
}
/**
* Find params in the XcodeML representation.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xparams object if found. Null otherwise.
*/
public static Xparams findParams(XbaseElement parent, boolean any){
return findXelement(parent, any, Xparams.class);
}
/**
* Find all the index elements (arrayIndex and indexRange) in an element.
* @param parent Root element to search from.
* @return A list of all index ranges found.
*/
public static List<Xnode> findIndexes(XbaseElement parent){
List<Xnode> indexRanges = new ArrayList<>();
if(parent == null || parent.getBaseElement() == null){
return indexRanges;
}
Node node = parent.getBaseElement().getFirstChild();
while (node != null){
if(node.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element)node;
switch (element.getTagName()){
case XelementName.ARRAY_INDEX:
case XelementName.INDEX_RANGE:
indexRanges.add(new Xnode(element));
break;
}
}
node = node.getNextSibling();
}
return indexRanges;
}
/**
* Find all the name elements in an element.
* @param parent Root element to search from.
* @return A list of all name elements found.
*/
public static List<Xname> findAllNames(XbaseElement parent){
return findAll(parent, Xname.class);
}
/**
* Find all the var elements that are real references to a variable. Var
* element nested in an arrayIndex element are excluded.
* @param parent Root element to search from.
* @return A list of all var elements found.
*/
public static List<Xnode> findAllReferences(Xnode parent){
List<Xnode> vars = findAll(Xcode.VAR, parent);
List<Xnode> realReferences = new ArrayList<>();
for(Xnode var : vars){
if(!((Element)var.getElement().getParentNode()).getTagName().
equals(Xcode.ARRAYINDEX.code()))
{
realReferences.add(var);
}
}
return realReferences;
}
/**
* Find all the var elements that are real references to a variable. Var
* element nested in an arrayIndex element are excluded.
* @param parent Root element to search from.
* @param id Identifier of the var to be found.
* @return A list of all var elements found.
*/
public static List<Xnode> findAllReferences(Xnode parent, String id){
List<Xnode> vars = findAll(Xcode.VAR, parent);
List<Xnode> realReferences = new ArrayList<>();
for(Xnode var : vars){
if(!((Element)var.getElement().getParentNode()).getTagName().
equals(Xcode.ARRAYINDEX.code())
&& var.getValue().toLowerCase().equals(id.toLowerCase()))
{
realReferences.add(var);
}
}
return realReferences;
}
/**
* Find len element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xlength object if found. Null otherwise.
*/
public static Xlength findLen(XbaseElement parent, boolean any){
return findXelement(parent, any, Xlength.class);
}
/**
* Find kind element.
* @param parent Root element to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return A Xkind object if found. Null otherwise.
*/
public static Xkind findKind(XbaseElement parent, boolean any){
return findXelement(parent, any, Xkind.class);
}
/**
* Find all the pragma element in an XcodeML tree.
* @param xcodeml The XcodeML program to search in.
* @return A list of all pragmas found in the XcodeML program.
*/
public static List<Xnode> findAllPragmas(XcodeProgram xcodeml){
NodeList pragmaList = xcodeml.getDocument()
.getElementsByTagName(Xcode.FPRAGMASTATEMENT.code());
List<Xnode> pragmas = new ArrayList<>();
for (int i = 0; i < pragmaList.getLength(); i++) {
Node pragmaNode = pragmaList.item(i);
if (pragmaNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) pragmaNode;
pragmas.add(new Xnode(element));
}
}
return pragmas;
}
public static void appendBody(Xbody originalBody, Xbody extraBody)
throws IllegalTransformationException
{
if(originalBody == null || originalBody.getBaseElement() == null
|| extraBody == null || extraBody.getBaseElement() == null)
{
throw new IllegalTransformationException("One of the body is null.");
}
// Append content of loop-body (loop) to this loop-body
Node childNode = extraBody.getBaseElement().getFirstChild();
while(childNode != null){
Node nextChild = childNode.getNextSibling();
// Do something with childNode, including move or delete...
if(childNode.getNodeType() == Node.ELEMENT_NODE){
originalBody.getBaseElement().appendChild(childNode);
}
childNode = nextChild;
}
}
/**
* Extract the body of a do statement and place it directly after it.
* @param loop The do statement containing the body to be extracted.
*/
public static void extractBody(Xnode loop){
Element loopElement = loop.getElement();
Element body = XelementHelper.findFirstElement(loopElement,
XelementName.BODY);
Node refNode = loopElement;
if(body == null){
return;
}
for(Node childNode = body.getFirstChild(); childNode!=null;){
Node nextChild = childNode.getNextSibling();
// Do something with childNode, including move or delete...
if(childNode.getNodeType() == Node.ELEMENT_NODE){
XelementHelper.insertAfter(refNode, childNode);
refNode = childNode;
}
childNode = nextChild;
}
}
/**
* Delete an element for the tree.
* @param element Element to be deleted.
*/
public static void delete(Element element){
if(element == null || element.getParentNode() == null){
return;
}
element.getParentNode().removeChild(element);
}
/**
* Write the XcodeML to file or std out
* @param xcodeml The XcodeML to write in the output
* @param outputFile Path of the output file or null to output on std out
* @param indent Number of spaces used for the indentation
* @return true if the output could be write without problems.
*/
public static boolean writeXcodeML(XcodeProgram xcodeml, String outputFile, int indent) {
try {
XelementHelper.cleanEmptyTextNodes(xcodeml.getDocument());
Transformer transformer
= TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount",
Integer.toString(indent));
DOMSource source = new DOMSource(xcodeml.getDocument());
if(outputFile == null){
// Output to console
StreamResult console = new StreamResult(System.out);
transformer.transform(source, console);
} else {
// Output to file
StreamResult console = new StreamResult(new File(outputFile));
transformer.transform(source, console);
}
} catch (TransformerConfigurationException ex){
xcodeml.addError("Cannot output file: " + ex.getMessage(), 0);
return false;
} catch (TransformerException ex){
xcodeml.addError("Cannot output file: " + ex.getMessage(), 0);
return false;
}
return true;
}
/**
* Removes text nodes that only contains whitespace. The conditions for
* removing text nodes, besides only containing whitespace, are: If the
* parent node has at least one child of any of the following types, all
* whitespace-only text-node children will be removed: - ELEMENT child -
* CDATA child - COMMENT child.
* @param parentNode Root node to start the cleaning.
*/
private static void cleanEmptyTextNodes(Node parentNode) {
boolean removeEmptyTextNodes = false;
Node childNode = parentNode.getFirstChild();
while (childNode != null) {
removeEmptyTextNodes |= checkNodeTypes(childNode);
childNode = childNode.getNextSibling();
}
if (removeEmptyTextNodes) {
removeEmptyTextNodes(parentNode);
}
}
/**
* Validate a string attribute.
* @param doc Document in which the attribute must be validated.
* @param attrValue Attribute value expected.
* @param query Xpath query to locate the attribute value.
* @return True if the attribute validates. False otherwise.
* @throws Exception if xpathQuery cannot be executed.
*/
public static boolean validateStringAttribute(Document doc, String attrValue,
String query) throws Exception
{
XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query);
String outputValue = (String) ex.evaluate(doc, XPathConstants.STRING);
return outputValue.equals(attrValue);
}
/**
* Insert an element just before a reference element.
* @param ref The reference element.
* @param insert The element to be inserted.
*/
public static void insertBefore(XbaseElement ref, XbaseElement insert){
ref.getBaseElement().getParentNode().insertBefore(insert.getBaseElement(),
ref.getBaseElement());
}
/**
* Insert an element just after a reference element.
* @param refElement The reference element.
* @param element The element to be inserted.
*/
public static void insertAfter(XbaseElement refElement, XbaseElement element){
XelementHelper.insertAfter(refElement.getBaseElement(),
element.getBaseElement());
}
/*
* PRIVATE SECTION
*/
/**
* Remove all empty text nodes in the subtree.
* @param parentNode Root node to start the search.
*/
private static void removeEmptyTextNodes(Node parentNode) {
Node childNode = parentNode.getFirstChild();
while (childNode != null) {
// grab the "nextSibling" before the child node is removed
Node nextChild = childNode.getNextSibling();
short nodeType = childNode.getNodeType();
if (nodeType == Node.TEXT_NODE) {
boolean containsOnlyWhitespace = childNode.getNodeValue()
.trim().isEmpty();
if (containsOnlyWhitespace) {
parentNode.removeChild(childNode);
}
}
childNode = nextChild;
}
}
/**
* Check the type of the given node.
* @param childNode Node to be checked.
* @return True if the node contains data. False otherwise.
*/
private static boolean checkNodeTypes(Node childNode) {
short nodeType = childNode.getNodeType();
if (nodeType == Node.ELEMENT_NODE) {
cleanEmptyTextNodes(childNode); // recurse into subtree
}
return nodeType == Node.ELEMENT_NODE || nodeType == Node.CDATA_SECTION_NODE
|| nodeType == Node.COMMENT_NODE;
}
/**
* Insert a node directly after a reference node.
* @param refNode The reference node. New node will be inserted after this
* one.
* @param newNode The new node to be inserted.
*/
private static void insertAfter(Node refNode, Node newNode){
refNode.getParentNode().insertBefore(newNode, refNode.getNextSibling());
}
/**
* Find an element of Class T in the nested elements under parent.
* @param parent XbaseElement to search from.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @param xElementClass Element's class to be found.
* @param <T> Derived class of XbaseElement.
* @return An instance of T class if an element is found. Null if no element
* is found.
*/
private static <T extends XbaseElement> T findXelement(XbaseElement parent,
boolean any, Class<T> xElementClass)
{
String elementName = XelementName.getElementNameFromClass(xElementClass);
if(elementName == null || parent == null
|| parent.getBaseElement() == null)
{
return null;
}
Element element = findElement(parent, elementName, any);
if (element != null){
try{
return xElementClass.
getDeclaredConstructor(Element.class).newInstance(element);
} catch(Exception ex){
return null;
}
}
return null;
}
/**
* Find element of the the given Class that is directly after the given from
* element.
* @param from XbaseElement to search from.
* @param xElementClass Element's class to be found.
* @param <T> Derived class of XbaseElement.
* @return Instance of the xElementClass. Null if no element is found.
*/
private static <T extends XbaseElement> T findDirectNextElement(
XbaseElement from, Class<T> xElementClass)
{
String elementName = XelementName.getElementNameFromClass(xElementClass);
if(elementName == null || from == null || from.getBaseElement() == null){
return null;
}
Node nextNode = from.getBaseElement().getNextSibling();
while (nextNode != null){
if(nextNode.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) nextNode;
if(element.getTagName().equals(elementName)){
return construct(xElementClass, element);
}
return null;
}
nextNode = nextNode.getNextSibling();
}
return null;
}
/**
* Find a parent element from a child in the ancestors.
* @param from The child element to search from.
* @return A XbaseElement object if found. Null otherwise.
*/
private static <T extends XbaseElement> T findParentOfType(
XbaseElement from, Class<T> xElementClass)
{
return findOfType(from, xElementClass, true);
}
/**
* Find any element of the the given Class in the direct children of from
* element. Only first level children are search for.
* @param from XbaseElement to search from.
* @param xElementClass Element's class to be found.
* @param <T> Derived class of XbaseElement.
* @return The first element found under from element. Null if no element is
* found.
*/
private static <T extends XbaseElement> T findNextElementOfType(
XbaseElement from, Class<T> xElementClass)
{
return findOfType(from, xElementClass, false);
}
/**
* Find any element of the given Class in the direct children or the ancestors
* of the from element. In the case if children, only first level children are
* search for.
* @param from XbaseElement to search from.
* @param xElementClass Element's class to be found.
* @param ancestor if true, search in the ancestor. If false, search in
* the children.
* @param <T> Derived class of XbaseElement.
* @return The first element found under or in the ancestors of the from
* element. Null if no element is found.
*/
private static <T extends XbaseElement> T findOfType(XbaseElement from,
Class<T> xElementClass,
boolean ancestor)
{
String elementName = XelementName.getElementNameFromClass(xElementClass);
if(elementName == null || from == null || from.getBaseElement() == null){
return null;
}
Node nextNode = ancestor ? from.getBaseElement().getParentNode() :
from.getBaseElement().getNextSibling();
while(nextNode != null){
if (nextNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nextNode;
if(element.getTagName().equals(elementName)){
return construct(xElementClass, element);
}
}
nextNode = ancestor ? nextNode.getParentNode() : nextNode.getNextSibling();
}
return null;
}
/**
* Constructs an object with the base constrcutor for XbaseElement.
* @param xElementClass Type of the object.
* @param element Element to pass to the constructor.
* @param <T> Derived class of XbaseElement.
* @return A new XbaseElement dervied object or null if the construction
* fails.
*/
private static <T extends XbaseElement> T construct(Class<T> xElementClass,
Element element){
try{
return xElementClass.
getDeclaredConstructor(Element.class).newInstance(element);
} catch(Exception ex){
return null;
}
}
/**
* Get a list of T elements from an xpath query executed from the
* given element.
* @param from Element to start from.
* @param query XPath query to be executed.
* @param xElementClass Type of element to retrieve.
* @return List of all array references found. List is empty if nothing is
* found.
*/
private static <T extends XbaseElement> List<T> getFromXpath(
XbaseElement from, String query, Class<T> xElementClass)
{
List<T> elements = new ArrayList<>();
try {
XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query);
NodeList output = (NodeList) ex.evaluate(from.getBaseElement(),
XPathConstants.NODESET);
for (int i = 0; i < output.getLength(); i++) {
Element element = (Element) output.item(i);
try{
T el = xElementClass.
getDeclaredConstructor(Element.class).newInstance(element);
elements.add(el);
} catch(Exception ignored){ }
}
} catch (XPathExpressionException ignored) {
}
return elements;
}
/**
* Get a list of all inner values from a list of base elements.
* @param elements List of base elements.
* @return A list of inner values.
*/
public static <T extends XbaseElement> List<String> getAllValues(
List<T> elements)
{
List<String> values = new ArrayList<>();
for(XbaseElement b : elements){
values.add(b.getValue());
}
return values;
}
/**
* Find all elements of the given type in the subtree from the given parent
* element.
* @param parent The element to search from.
* @param xElementClass Type of element to be searched.
* @param <T> Type of the XbaseElement to be searched.
* @return A list of found elements.
*/
private static <T extends XbaseElement> List<T> findAll(XbaseElement parent,
Class<T> xElementClass)
{
List<T> elements = new ArrayList<>();
String elementName = XelementName.getElementNameFromClass(xElementClass);
if(elementName == null || parent == null) {
return elements;
}
NodeList nodes = parent.getBaseElement().getElementsByTagName(elementName);
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
try {
elements.add(xElementClass.
getDeclaredConstructor(Element.class).newInstance(el));
} catch(Exception ex){
return null;
}
}
}
return elements;
}
public static <T extends XbaseElement> T createEmpty(Class<T> xElementClass,
XcodeProgram xcodeml)
throws IllegalTransformationException
{
String elementName = XelementName.getElementNameFromClass(xElementClass);
if(elementName != null){
Element element = xcodeml.getDocument().createElement(elementName);
try {
return xElementClass.
getDeclaredConstructor(Element.class).newInstance(element);
} catch(Exception ex){
throw new IllegalTransformationException("Cannot create new element: "
+ elementName);
}
}
throw new IllegalTransformationException("Undefined statement for classe:" +
xElementClass.toString());
}
/**
* Find the first element with tag corresponding to elementName.
* @param parent The root element to search from.
* @param elementName The tag of the element to search for.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return first element found. Null if no element is found.
*/
private static Element findElement(XbaseElement parent, String elementName, boolean any){
return findElement(parent.getBaseElement(), elementName, any);
}
/**
* Find the first element with tag corresponding to elementName.
* @param parent The root element to search from.
* @param elementName The tag of the element to search for.
* @param any If true, find in any nested element under parent. If
* false, only direct children are search for.
* @return first element found. Null if no element is found.
*/
private static Element findElement(Element parent, String elementName, boolean any){
if(any){
return findFirstElement(parent, elementName);
} else {
return findFirstChildElement(parent, elementName);
}
}
/**
* Find the first element with tag corresponding to elementName nested under
* the parent element.
* @param parent The root element to search from.
* @param elementName The tag of the element to search for.
* @return The first element found under parent with the corresponding tag.
* Null if no element is found.
*/
private static Element findFirstElement(Element parent, String elementName){
NodeList elements = parent.getElementsByTagName(elementName);
if(elements.getLength() == 0){
return null;
}
return (Element) elements.item(0);
}
/**
* Find the first element with tag corresponding to elementName in the direct
* children of the parent element.
* @param parent The root element to search from.
* @param elementName The tag of the element to search for.
* @return The first element found in the direct children of the element
* parent with the corresponding tag. Null if no element is found.
*/
private static Element findFirstChildElement(Element parent, String elementName){
NodeList nodeList = parent.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node nextNode = nodeList.item(i);
if(nextNode.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) nextNode;
if(element.getTagName().equals(elementName)){
return element;
}
}
}
return null;
}
/**
* Get the first child element.
* @param parent Root element to search form.
* @return First found element.
*/
private static Element getFirstChildElement(Element parent){
NodeList nodeList = parent.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node nextNode = nodeList.item(i);
if (nextNode.getNodeType() == Node.ELEMENT_NODE) {
return (Element) nextNode;
}
}
return null;
}
/**
* Get the xth child element.
* @param parent Root element to search form.
* @param position Position of the element to be found. Start at 0.
* @return Element found at position.
*/
private static Element getXthChildElement(Element parent, int position){
int crtIndex = 0;
NodeList nodeList = parent.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node nextNode = nodeList.item(i);
if (nextNode.getNodeType() == Node.ELEMENT_NODE && crtIndex == position) {
return (Element) nextNode;
} else if (nextNode.getNodeType() == Node.ELEMENT_NODE){
++crtIndex;
}
}
return null;
}
public static XbinaryExpr createEmpty(String exprTag, XcodeProgram xcodeml)
throws IllegalTransformationException
{
if(XelementName.isBinaryExprTag(exprTag)){
Element element = xcodeml.getDocument().createElement(exprTag);
return new XbinaryExpr(element);
}
throw new IllegalTransformationException("No binary expression with tag:" +
exprTag);
}
/**
* Get the depth of an element in the AST.
* @param element The element for which the depth is computed.
* @return A depth value greater or equal to 0.
*/
public static int getDepth(XbaseElement element) {
if(element == null || element.getBaseElement() == null){
return -1;
}
return getDepth(element.getBaseElement());
}
/**
* Get the depth of an element in the AST.
* @param element XML element for which the depth is computed.
* @return A depth value greater or equal to 0.
*/
private static int getDepth(Element element){
Node parent = element.getParentNode();
int depth = 0;
while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
++depth;
parent = parent.getParentNode();
}
return depth;
}
/**
* Shift all statements from the first siblings of the "from" element until
* the "until" element (not included).
* @param from Start element for the swifting.
* @param until End element for the swifting.
* @param targetBody Body element in which statements are inserted.
*/
public static void shiftStatementsInBody(Xnode from,
Xnode until, Xnode targetBody)
{
Node currentSibling = from.getElement().getNextSibling();
Node firstStatementInBody = targetBody.getElement().getFirstChild();
while(currentSibling != null && currentSibling != until.getElement()){
Node nextSibling = currentSibling.getNextSibling();
targetBody.getElement().insertBefore(currentSibling,
firstStatementInBody);
currentSibling = nextSibling;
}
}
/**
* Copy the enhanced information from an element to a target element.
* Enhanced information include line number and original file name.
* @param base Base element to copy information from.
* @param target Target element to copy information to.
*/
public static void copyEnhancedInfo(XenhancedElement base,
XenhancedElement target)
{
target.setLine(base.getLineNo());
target.setFile(base.getFile());
}
/**
* Copy the whole body element into the destination one. Destination is
* overwritten.
* @param from The body to be copied.
* @param to The desination of the copied body.
*/
public static void copyBody(Xnode from, Xnode to){
Node copiedBody = from.cloneNode();
if(to.getBody() != null){
to.getBody().delete();
}
to.getElement().appendChild(copiedBody);
}
/**
* Check whether the given type is a built-in type or is a type defined in the
* type table.
* @param type Type to check.
* @return True if the type is built-in. False otherwise.
*/
public static boolean isBuiltInType(String type){
switch (type){
case XelementName.TYPE_F_CHAR:
case XelementName.TYPE_F_COMPLEX:
case XelementName.TYPE_F_INT:
case XelementName.TYPE_F_LOGICAL:
case XelementName.TYPE_F_REAL:
case XelementName.TYPE_F_VOID:
return true;
default:
return false;
}
}
/* XNODE SECTION */
/**
* Find module definition element in which the child is included if any.
* @param from The child element to search from.
* @return A XmoduleDefinition object if found. Null otherwise.
*/
public static XmoduleDefinition findParentModule(Xnode from) {
Xnode moduleDef = findParent(Xcode.FMODULEDEFINITION, from);
if(moduleDef == null){
return null;
}
return new XmoduleDefinition(moduleDef.getElement());
}
/**
* TODO javadoc
* @param from
* @return
*/
public static XfunctionDefinition findParentFunction(Xnode from){
Xnode fctDef = findParent(Xcode.FFUNCTIONDEFINITION, from);
if(fctDef == null){
return null;
}
return new XfunctionDefinition(fctDef.getElement());
}
/**
* Find an element in the ancestor of the given element.
* @param opcode Code of the element to be found.
* @param from Element to start the search from.
* @return The element found. Null if no element is found.
*/
public static Xnode findParent(Xcode opcode, Xnode from){
if(from == null){
return null;
}
Node nextNode = from.getElement().getParentNode();
while(nextNode != null){
if (nextNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nextNode;
if(element.getTagName().equals(opcode.code())){
return new Xnode(element);
}
}
nextNode = nextNode.getParentNode();
}
return null;
}
/**
* Find element of the the given type that is directly after the given from
* element.
* @param opcode Code of the element to be found.
* @param from Element to start the search from.
* @return The element found. Null if no element is found.
*/
public static Xnode findDirectNext(Xcode opcode, Xnode from) {
if(from == null){
return null;
}
Node nextNode = from.getElement().getNextSibling();
while (nextNode != null){
if(nextNode.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) nextNode;
if(element.getTagName().equals(opcode.code())){
return new Xnode(element);
}
return null;
}
nextNode = nextNode.getNextSibling();
}
return null;
}
/**
* Delete all the elements between the two given elements.
* @param start The start element. Deletion start from next element.
* @param end The end element. Deletion end just before this element.
*/
public static void deleteBetween(Xnode start, Xnode end){
List<Element> toDelete = new ArrayList<>();
Node node = start.getElement().getNextSibling();
while (node != null && node != end.getElement()){
if(node.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element)node;
toDelete.add(element);
}
node = node.getNextSibling();
}
for(Element e : toDelete){
delete(e);
}
}
/**
* Insert an element just after a reference element.
* @param refElement The reference element.
* @param element The element to be inserted.
*/
public static void insertAfter(Xnode refElement, Xnode element){
XelementHelper.insertAfter(refElement.getElement(), element.getElement());
}
/**
* Find the first element with tag corresponding to elementName.
* @param opcode The XcodeML code of the element to search for.
* @param parent The root element to search from.
* @param any If true, find in any nested element under parent. If false,
* only direct children are search for.
* @return first element found. Null if no element is found.
*/
public static Xnode find(Xcode opcode, Xnode parent, boolean any){
Element el;
if(any){
el = findFirstElement(parent.getElement(), opcode.code());
} else {
el = findFirstChildElement(parent.getElement(), opcode.code());
}
return (el == null) ? null : new Xnode(el);
}
/**
* Find element of the the given type that is directly after the given from
* element.
* @param opcode Code of the element to be found.
* @param from Element to start the search from.
* @return The element found. Null if no element is found.
*/
public static Xnode findNext(Xcode opcode, Xnode from) {
if(from == null){
return null;
}
Node nextNode = from.getElement().getNextSibling();
while (nextNode != null){
if(nextNode.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) nextNode;
if(element.getTagName().equals(opcode.code())){
return new Xnode(element);
}
}
nextNode = nextNode.getNextSibling();
}
return null;
}
public static void appendBody(Xnode originalBody, Xnode extraBody)
throws IllegalTransformationException
{
if(originalBody == null || originalBody.getElement() == null
|| extraBody == null || extraBody.getElement() == null
|| originalBody.Opcode() != Xcode.BODY
|| extraBody.Opcode() != Xcode.BODY)
{
throw new IllegalTransformationException("One of the body is null.");
}
// Append content of loop-body (loop) to this loop-body
Node childNode = extraBody.getElement().getFirstChild();
while(childNode != null){
Node nextChild = childNode.getNextSibling();
// Do something with childNode, including move or delete...
if(childNode.getNodeType() == Node.ELEMENT_NODE){
originalBody.getElement().appendChild(childNode);
}
childNode = nextChild;
}
}
/**
* Check if the two element are direct children of the same parent element.
* @param e1 First element.
* @param e2 Second element.
* @return True if the two element are direct children of the same parent.
* False otherwise.
*/
public static boolean hasSameParentBlock(Xnode e1, Xnode e2) {
return !(e1 == null || e2 == null || e1.getElement() == null
|| e2.getElement() == null)
&& e1.getElement().getParentNode() ==
e2.getElement().getParentNode();
}
/**
* Compare the iteration range of two do statements.
* @param e1 First do statement.
* @param e2 Second do statement.
* @return True if the iteration range are identical.
*/
public static boolean hasSameIndexRange(Xnode e1, Xnode e2){
// The two nodes must be do statement
if(e1.Opcode() != Xcode.FDOSTATEMENT || e2.Opcode() != Xcode.FDOSTATEMENT){
return false;
}
// TODO XNODE refactoring (have method to get bounds)
Xnode inductionVar1 = XelementHelper.find(Xcode.VAR, e1, false);
Xnode inductionVar2 = XelementHelper.find(Xcode.VAR, e2, false);
Xnode indexRange1 = XelementHelper.find(Xcode.INDEXRANGE, e1, false);
Xnode indexRange2 = XelementHelper.find(Xcode.INDEXRANGE, e2, false);
if(!inductionVar1.getValue().toLowerCase().
equals(inductionVar2.getValue().toLowerCase()))
{
return false;
}
return isIndexRangeIdentical(indexRange1, indexRange2);
}
private static boolean isIndexRangeIdentical(Xnode idx1, Xnode idx2){
if(idx1.Opcode() != Xcode.INDEXRANGE ||idx2.Opcode() != Xcode.INDEXRANGE){
return false;
}
if(idx1.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE) &&
idx2.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)){
return true;
}
Xnode low1 = idx1.find(Xcode.LOWERBOUND).getChild(0);
Xnode up1 = idx1.find(Xcode.UPPERBOUND).getChild(0);
Xnode low2 = idx2.find(Xcode.LOWERBOUND);
Xnode up2 = idx2.find(Xcode.UPPERBOUND).getChild(0);
Xnode s1 = idx1.find(Xcode.STEP);
Xnode s2 = idx2.find(Xcode.STEP);
if(s1 != null){
s1 = s1.getChild(0);
}
if(s2 != null){
s2 = s2.getChild(0);
}
if (!low1.getValue().toLowerCase().equals(low2.getValue().toLowerCase())) {
return false;
}
if (!up1.getValue().toLowerCase().equals(up2.getValue().toLowerCase())) {
return false;
}
// step is optional
return s1 == null && s2 == null ||
s1.getValue().toLowerCase().equals(s2.getValue().toLowerCase());
}
/**
* Compare the iteration range of two do statements.
* @param e1 First do statement.
* @param e2 Second do statement.
* @return True if the iteration range are identical besides the lower bound.
*/
public static boolean hasSameIndexRangeBesidesLower(Xnode e1, Xnode e2){
// The two nodes must be do statement
if(e1.Opcode() != Xcode.FDOSTATEMENT || e2.Opcode() != Xcode.FDOSTATEMENT){
return false;
}
Xnode inductionVar1 = XelementHelper.find(Xcode.VAR, e1, false);
Xnode inductionVar2 = XelementHelper.find(Xcode.VAR, e2, false);
Xnode indexRange1 = XelementHelper.find(Xcode.INDEXRANGE, e1, false);
Xnode indexRange2 = XelementHelper.find(Xcode.INDEXRANGE, e2, false);
Xnode up1 = XelementHelper.find(Xcode.UPPERBOUND, indexRange1, false).getChild(0);
Xnode s1 = XelementHelper.find(Xcode.STEP, indexRange1, false).getChild(0);
Xnode up2 = XelementHelper.find(Xcode.UPPERBOUND, indexRange2, false).getChild(0);
Xnode s2 = XelementHelper.find(Xcode.STEP, indexRange2, false).getChild(0);
if(!inductionVar1.getValue().toLowerCase().
equals(inductionVar2.getValue().toLowerCase()))
{
return false;
}
if(indexRange1.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE) &&
indexRange2.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)){
return true;
}
if (!up1.getValue().toLowerCase().equals(up2.getValue().toLowerCase())) {
return false;
}
// step is optional
return s1 == null && s2 == null ||
s1.getValue().toLowerCase().equals(s2.getValue().toLowerCase());
}
public static void swapIterationRange(Xnode e1, Xnode e2){
// The two nodes must be do statement
if(e1.Opcode() != Xcode.FDOSTATEMENT || e2.Opcode() != Xcode.FDOSTATEMENT){
return;
}
Xnode inductionVar1 = XelementHelper.find(Xcode.VAR, e1, false);
Xnode inductionVar2 = XelementHelper.find(Xcode.VAR, e2, false);
Xnode indexRange1 = XelementHelper.find(Xcode.INDEXRANGE, e1, false);
Xnode indexRange2 = XelementHelper.find(Xcode.INDEXRANGE, e2, false);
Xnode low1 = XelementHelper.find(Xcode.LOWERBOUND, indexRange1, false).getChild(0);
Xnode up1 = XelementHelper.find(Xcode.UPPERBOUND, indexRange1, false).getChild(0);
Xnode s1 = XelementHelper.find(Xcode.STEP, indexRange1, false).getChild(0);
Xnode low2 = XelementHelper.find(Xcode.LOWERBOUND, indexRange2, false).getChild(0);
Xnode up2 = XelementHelper.find(Xcode.UPPERBOUND, indexRange2, false).getChild(0);
Xnode s2 = XelementHelper.find(Xcode.STEP, indexRange2, false).getChild(0);
String tmpInduction = inductionVar2.getValue();
String tmpLower = low2.getValue();
String tmpUpper = up2.getValue();
String tmpStep = s2.getValue();
// Set the range of loop2 to loop1
inductionVar2.setValue(inductionVar1.getValue());
low2.setValue(low1.getValue());
up2.setValue(up1.getValue());
s2.setValue(s1.getValue());
inductionVar1.setValue(tmpInduction);
low1.setValue(tmpLower);
up1.setValue(tmpUpper);
s1.setValue(tmpStep);
}
/**
* Get the depth of an element in the AST.
* @param element The element for which the depth is computed.
* @return A depth value greater or equal to 0.
*/
public static int getDepth(Xnode element) {
if(element == null || element.getElement() == null){
return -1;
}
return getDepth(element.getElement());
}
/**
* Copy the enhanced information from an element to a target element.
* Enhanced information include line number and original file name.
* @param base Base element to copy information from.
* @param target Target element to copy information to.
*/
public static void copyEnhancedInfo(Xnode base, Xnode target) {
target.setLine(base.getLineNo());
target.setFile(base.getFile());
}
/**
* Insert an element just before a reference element.
* @param ref The reference element.
* @param insert The element to be inserted.
*/
public static void insertBefore(Xnode ref, Xnode insert){
ref.getElement().getParentNode().insertBefore(insert.getElement(),
ref.getElement());
}
public static Xnode createVar(String type, String value, Xscope scope,
XcodeProgram xcodeml)
{
Xnode var = new Xnode(Xcode.VAR, xcodeml);
var.setAttribute(Xattr.TYPE, type);
var.setAttribute(Xattr.SCOPE, scope.toString());
var.setValue(value);
return var;
}
/**
* Get a list of T elements from an xpath query executed from the
* given element.
* @param from Element to start from.
* @param query XPath query to be executed.
* @return List of all array references found. List is empty if nothing is
* found.
*/
private static List<Xnode> getFromXpath(Xnode from, String query)
{
List<Xnode> elements = new ArrayList<>();
try {
XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query);
NodeList output = (NodeList) ex.evaluate(from.getElement(),
XPathConstants.NODESET);
for (int i = 0; i < output.getLength(); i++) {
Element element = (Element) output.item(i);
elements.add(new Xnode(element));
}
} catch (XPathExpressionException ignored) {
}
return elements;
}
/**
* TODO javadoc
* @param xcodeml
* @return
*/
public static Xnode createIfThen(XcodeProgram xcodeml){
Xnode root = new Xnode(Xcode.FIFSTATEMENT, xcodeml);
Xnode cond = new Xnode(Xcode.CONDITION, xcodeml);
Xnode thenBlock = new Xnode(Xcode.THEN, xcodeml);
Xnode thenBody = new Xnode(Xcode.BODY, xcodeml);
thenBlock.appendToChildren(thenBody, false);
root.appendToChildren(cond, false);
root.appendToChildren(thenBlock, false);
return root;
}
/**
* TODO javadoc
* @param inductionVar
* @param indexRange
* @param xcodeml
* @return
*/
public static Xnode createDoStmt(Xnode inductionVar,
Xnode indexRange,
XcodeProgram xcodeml)
{
Xnode root = new Xnode(Xcode.FDOSTATEMENT, xcodeml);
root.appendToChildren(inductionVar, false);
root.appendToChildren(indexRange, false);
Xnode body = new Xnode(Xcode.BODY, xcodeml);
root.appendToChildren(body, false);
return root;
}
/**
* TODO javadoc
* @param value
* @param fctCall
* @return
*/
public static Xnode findArg(String value, Xnode fctCall){
if(fctCall.Opcode() != Xcode.FUNCTIONCALL) {
return null;
}
Xnode args = fctCall.find(Xcode.ARGUMENTS);
if(args == null){
return null;
}
for(Xnode arg : args.getChildren()){
if(value.toLowerCase().equals(arg.getValue().toLowerCase())){
return arg;
}
}
return null;
}
/**
* TODO javadoc
* @param xcodeml
* @param arrayVar
* @param startIndex
* @param dimension
* @return
*/
public static Xnode createAssumedShapeRange(XcodeProgram xcodeml,
Xnode arrayVar, int startIndex,
int dimension)
{
// Base structure
Xnode indexRange = new Xnode(Xcode.INDEXRANGE, xcodeml);
Xnode lower = new Xnode(Xcode.LOWERBOUND, xcodeml);
Xnode upper = new Xnode(Xcode.UPPERBOUND, xcodeml);
indexRange.appendToChildren(lower, false);
indexRange.appendToChildren(upper, false);
// Lower bound
Xnode lowerBound = new Xnode(Xcode.FINTCONSTANT, xcodeml);
lowerBound.setValue(String.valueOf(startIndex));
lower.appendToChildren(lowerBound, false);
// Upper bound
Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml);
upper.appendToChildren(fctCall, false);
fctCall.setAttribute(Xattr.IS_INTRINSIC, XelementName.TRUE);
fctCall.setAttribute(Xattr.TYPE, XelementName.TYPE_F_INT);
Xnode name = new Xnode(Xcode.NAME, xcodeml);
name.setValue(XelementName.INTRINSIC_SIZE);
fctCall.appendToChildren(name, false);
Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml);
fctCall.appendToChildren(args, false);
args.appendToChildren(arrayVar, true);
Xnode dim = new Xnode(Xcode.FINTCONSTANT, xcodeml);
dim.setValue(String.valueOf(dimension));
args.appendToChildren(dim, false);
return indexRange;
}
/**
* TODO javadoc
* @param xcodeml
* @return
*/
public static Xnode createEmptyAssumedShaped(XcodeProgram xcodeml) {
Xnode range = new Xnode(Xcode.INDEXRANGE, xcodeml);
range.setAttribute(Xattr.IS_ASSUMED_SHAPE, XelementName.TRUE);
return range;
}
/**
* TODO javadoc
* @param opcode
* @param parent
* @return
*/
public static List<Xnode> findAll(Xcode opcode, Xnode parent) {
List<Xnode> elements = new ArrayList<>();
if(parent == null) {
return elements;
}
NodeList nodes = parent.getElement().getElementsByTagName(opcode.code());
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
elements.add(new Xnode((Element)n));
}
}
return elements;
}
/**
* TODO javadoc
* @param xcodeml
* @param returnType
* @param name
* @param nameType
* @return
*/
public static Xnode createFctCall(XcodeProgram xcodeml, String returnType,
String name, String nameType){
Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml);
fctCall.setAttribute(Xattr.TYPE, returnType);
Xnode fctName = new Xnode(Xcode.NAME, xcodeml);
fctName.setValue(name);
fctName.setAttribute(Xattr.TYPE, nameType);
Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml);
fctCall.appendToChildren(fctName, false);
fctCall.appendToChildren(args, false);
return fctCall;
}
/**
* TODO javadoc
* @param type
* @param var
* @param xcodeml
* @return
*/
public static Xnode createArrayRef(XbasicType type, Xnode var,
XcodeProgram xcodeml)
{
Xnode ref = new Xnode(Xcode.FARRAYREF, xcodeml);
ref.setAttribute(Xattr.TYPE, type.getRef());
Xnode varRef = new Xnode(Xcode.VARREF, xcodeml);
varRef.setAttribute(Xattr.TYPE, type.getType());
varRef.appendToChildren(var, false);
ref.appendToChildren(varRef, false);
return ref;
}
/**
* Create a new Id element with all the underlying needed elements.
* @param type Value for the attribute type.
* @param sclass Value for the attribute sclass.
* @param nameValue Value of the name inner element.
* @param xcodeml XcodeML program.
* @return A newly constructs Xid element with all the information loaded.
*/
public static Xid createId(String type, String sclass, String nameValue,
XcodeProgram xcodeml)
{
Xnode id = new Xnode(Xcode.ID, xcodeml);
Xnode internalName = new Xnode(Xcode.NAME, xcodeml);
internalName.setValue(nameValue);
id.appendToChildren(internalName, false);
id.setAttribute(Xattr.TYPE, type);
id.setAttribute(Xattr.SCLASS, sclass);
return new Xid(id.getElement());
}
}
|
package edu.uci.python.nodes.attribute;
import com.oracle.truffle.api.*;
import com.oracle.truffle.api.frame.*;
import com.oracle.truffle.api.nodes.*;
import edu.uci.python.runtime.*;
import edu.uci.python.runtime.object.*;
public abstract class SetDispatchNode extends Node {
protected final String attributeId;
public SetDispatchNode(String attributeId) {
this.attributeId = attributeId;
}
public abstract void setValue(VirtualFrame frame, PythonObject primary, Object value);
public void setIntValue(VirtualFrame frame, PythonObject primary, int value) {
setValue(frame, primary, value);
}
public void setDoubleValue(VirtualFrame frame, PythonObject primary, double value) {
setValue(frame, primary, value);
}
public void setBooleanValue(VirtualFrame frame, PythonObject primary, boolean value) {
setValue(frame, primary, value);
}
protected SetDispatchNode rewrite(SetDispatchNode next) {
CompilerAsserts.neverPartOfCompilation();
assert this != next;
return replace(next);
}
@NodeInfo(cost = NodeCost.UNINITIALIZED)
public static final class UninitializedSetDispatchNode extends SetDispatchNode {
public UninitializedSetDispatchNode(String attributeId) {
super(attributeId);
}
@Override
public void setValue(VirtualFrame frame, PythonObject primary, Object value) {
CompilerDirectives.transferToInterpreterAndInvalidate();
Node current = this;
int depth = 0;
while (current.getParent() instanceof SetDispatchNode) {
current = current.getParent();
depth++;
}
if (depth < PythonOptions.AttributeAccessInlineCacheMaxDepth) {
primary.setAttribute(attributeId, value);
StorageLocation location = primary.getOwnValidLocation(attributeId);
replace(new LinkedSetDispatchNode(attributeId, AttributeWriteNode.create(location), primary, this));
} else {
replace(new GenericSetDispatchNode(attributeId)).setValue(frame, primary, value);
}
}
}
public static final class GenericSetDispatchNode extends SetDispatchNode {
public GenericSetDispatchNode(String attributeId) {
super(attributeId);
}
@Override
public void setValue(VirtualFrame frame, PythonObject primary, Object value) {
primary.setAttribute(attributeId, value);
}
}
public static final class LinkedSetDispatchNode extends SetDispatchNode {
@Child protected ShapeCheckNode check;
@Child protected AttributeWriteNode write;
@Child protected SetDispatchNode next;
public LinkedSetDispatchNode(String attributeId, AttributeWriteNode write, PythonObject primary, SetDispatchNode next) {
super(attributeId);
this.check = ShapeCheckNode.create(primary, 0);
this.write = write;
this.next = next;
}
@Override
public void setValue(VirtualFrame frame, PythonObject primary, Object value) {
try {
if (check.accept(primary)) {
write.setValueUnsafe(primary, value);
} else {
next.setValue(frame, primary, value);
}
} catch (InvalidAssumptionException | GeneralizeStorageLocationException e) {
rewrite(next).setValue(frame, primary, value);
}
}
@Override
public void setIntValue(VirtualFrame frame, PythonObject primary, int value) {
try {
if (check.accept(primary)) {
write.setIntValueUnsafe(primary, value);
} else {
next.setIntValue(frame, primary, value);
}
} catch (InvalidAssumptionException | GeneralizeStorageLocationException e) {
rewrite(next).setValue(frame, primary, value);
}
}
@Override
public void setDoubleValue(VirtualFrame frame, PythonObject primary, double value) {
try {
if (check.accept(primary)) {
write.setDoubleValueUnsafe(primary, value);
} else {
next.setDoubleValue(frame, primary, value);
}
} catch (InvalidAssumptionException | GeneralizeStorageLocationException e) {
rewrite(next).setValue(frame, primary, value);
}
}
@Override
public void setBooleanValue(VirtualFrame frame, PythonObject primary, boolean value) {
try {
if (check.accept(primary)) {
write.setBooleanValueUnsafe(primary, value);
} else {
next.setBooleanValue(frame, primary, value);
}
} catch (InvalidAssumptionException | GeneralizeStorageLocationException e) {
rewrite(next).setValue(frame, primary, value);
}
}
}
}
|
package org.jnosql.artemis.graph;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.jnosql.artemis.AttributeConverter;
import org.jnosql.artemis.Converters;
import org.jnosql.artemis.EntityNotFoundException;
import org.jnosql.artemis.reflection.ClassRepresentation;
import org.jnosql.artemis.reflection.ClassRepresentations;
import org.jnosql.artemis.reflection.FieldRepresentation;
import org.jnosql.artemis.reflection.Reflections;
import org.jnosql.diana.api.Value;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.jnosql.artemis.reflection.FieldType.EMBEDDED;
abstract class AbstractGraphConverter implements GraphConverter {
protected abstract ClassRepresentations getClassRepresentations();
protected abstract Reflections getReflections();
protected abstract Converters getConverters();
protected abstract Graph getGraph();
@Override
public <T> Vertex toVertex(T entity) {
requireNonNull(entity, "entity is required");
ClassRepresentation representation = getClassRepresentations().get(entity.getClass());
String label = representation.getName();
List<FieldGraph> fields = representation.getFields().stream()
.map(f -> to(f, entity))
.filter(FieldGraph::isNotEmpty).collect(toList());
Optional<FieldGraph> id = fields.stream().filter(FieldGraph::isId).findFirst();
final Function<Property, Vertex> findVertexOrCreateWithId = p -> {
Iterator<Vertex> vertices = getGraph().vertices(p.value());
return vertices.hasNext() ? vertices.next() :
getGraph().addVertex(org.apache.tinkerpop.gremlin.structure.T.label, label,
org.apache.tinkerpop.gremlin.structure.T.id, p.value());
};
Vertex vertex = id.map(i -> i.toElement(getConverters()))
.map(findVertexOrCreateWithId)
.orElseGet(() -> getGraph().addVertex(label));
fields.stream().filter(FieldGraph::isNotId)
.flatMap(f -> f.toElements(this, getConverters()).stream())
.forEach(p -> vertex.property(p.key(), p.value()));
return vertex;
}
public <T> List<Property<?>> getProperties(T entity) {
Objects.requireNonNull(entity, "entity is required");
ClassRepresentation representation = getClassRepresentations().get(entity.getClass());
List<FieldGraph> fields = representation.getFields().stream()
.map(f -> to(f, entity))
.filter(FieldGraph::isNotEmpty).collect(toList());
return fields.stream().filter(FieldGraph::isNotId)
.flatMap(f -> f.toElements(this, getConverters()).stream())
.collect(Collectors.toList());
}
@Override
public <T> T toEntity(Vertex vertex) {
requireNonNull(vertex, "vertex is required");
ClassRepresentation representation = getClassRepresentations().findByName(vertex.label());
List<Property> properties = vertex.keys().stream().map(k -> DefaultProperty.of(k, vertex.value(k))).collect(toList());
T entity = toEntity((Class<T>) representation.getClassInstance(), properties);
feedId(vertex, entity);
return entity;
}
@Override
public <T> T toEntity(Class<T> entityClass, Vertex vertex) {
requireNonNull(entityClass, "entityClass is required");
requireNonNull(vertex, "vertex is required");
List<Property> properties = vertex.keys().stream().map(k -> DefaultProperty.of(k, vertex.value(k))).collect(toList());
T entity = toEntity(entityClass, properties);
feedId(vertex, entity);
return entity;
}
@Override
public <T> T toEntity(T entityInstance, Vertex vertex) {
requireNonNull(entityInstance, "entityInstance is required");
requireNonNull(vertex, "vertex is required");
List<Property> properties = vertex.keys().stream().map(k -> DefaultProperty.of(k, vertex.value(k))).collect(toList());
ClassRepresentation representation = getClassRepresentations().get(entityInstance.getClass());
convertEntity(properties, representation, entityInstance);
feedId(vertex, entityInstance);
return entityInstance;
}
@Override
public EdgeEntity toEdgeEntity(Edge edge) {
requireNonNull(edge, "vertex is required");
Object out = toEntity(edge.outVertex());
Object in = toEntity(edge.inVertex());
return EdgeEntity.of(out, edge, in);
}
@Override
public Edge toEdge(EdgeEntity edge) {
requireNonNull(edge, "vertex is required");
Object id = edge.getId().get();
Iterator<Edge> edges = getGraph().edges(id);
if (edges.hasNext()) {
return edges.next();
}
throw new EntityNotFoundException("Edge does not found in the database with id: " + id);
}
private <T> void feedId(Vertex vertex, T entity) {
ClassRepresentation representation = getClassRepresentations().get(entity.getClass());
Optional<FieldRepresentation> id = representation.getId();
Object vertexId = vertex.id();
if (Objects.nonNull(vertexId) && id.isPresent()) {
FieldRepresentation fieldRepresentation = id.get();
Field fieldId = fieldRepresentation.getNativeField();
if (fieldRepresentation.getConverter().isPresent()) {
AttributeConverter attributeConverter = getConverters().get(fieldRepresentation.getConverter().get());
Object attributeConverted = attributeConverter.convertToEntityAttribute(vertexId);
getReflections().setValue(entity, fieldId, fieldRepresentation.getValue(Value.of(attributeConverted)));
} else {
getReflections().setValue(entity, fieldId, fieldRepresentation.getValue(Value.of(vertexId)));
}
}
}
private <T> T toEntity(Class<T> entityClass, List<Property> properties) {
ClassRepresentation representation = getClassRepresentations().get(entityClass);
T instance = getReflections().newInstance(representation.getConstructor());
return convertEntity(properties, representation, instance);
}
private <T> T convertEntity(List<Property> elements, ClassRepresentation representation, T instance) {
Map<String, FieldRepresentation> fieldsGroupByName = representation.getFieldsGroupByName();
List<String> names = elements.stream()
.map(Property::key)
.sorted()
.collect(toList());
Predicate<String> existField = k -> Collections.binarySearch(names, k) >= 0;
fieldsGroupByName.keySet().stream()
.filter(existField.or(k -> EMBEDDED.equals(fieldsGroupByName.get(k).getType())))
.forEach(feedObject(instance, elements, fieldsGroupByName));
return instance;
}
private <T> Consumer<String> feedObject(T instance, List<Property> elements,
Map<String, FieldRepresentation> fieldsGroupByName) {
return k -> {
Optional<Property> element = elements
.stream()
.filter(c -> c.key().equals(k))
.findFirst();
FieldRepresentation field = fieldsGroupByName.get(k);
if (EMBEDDED.equals(field.getType())) {
setEmbeddedField(instance, elements, field);
} else {
setSingleField(instance, element, field);
}
};
}
private <T> void setSingleField(T instance, Optional<Property> element, FieldRepresentation field) {
Object value = element.get().value();
Optional<Class<? extends AttributeConverter>> converter = field.getConverter();
if (converter.isPresent()) {
AttributeConverter attributeConverter = getConverters().get(converter.get());
Object attributeConverted = attributeConverter.convertToEntityAttribute(value);
getReflections().setValue(instance, field.getNativeField(), field.getValue(Value.of(attributeConverted)));
} else {
getReflections().setValue(instance, field.getNativeField(), field.getValue(Value.of(value)));
}
}
private <T> void setEmbeddedField(T instance, List<Property> elements,
FieldRepresentation field) {
getReflections().setValue(instance, field.getNativeField(), toEntity(field.getNativeField().getType(), elements));
}
private FieldGraph to(FieldRepresentation field, Object entityInstance) {
Object value = getReflections().getValue(entityInstance, field.getNativeField());
return FieldGraph.of(value, field);
}
}
|
package com.tinkerpop.gremlin.structure.io.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.tinkerpop.gremlin.structure.Direction;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Element;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Property;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.io.GraphReader;
import com.tinkerpop.gremlin.structure.util.batch.BatchGraph;
import com.tinkerpop.gremlin.util.function.QuadConsumer;
import com.tinkerpop.gremlin.util.function.QuintFunction;
import com.tinkerpop.gremlin.util.function.TriFunction;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
public class KryoReader implements GraphReader {
private final Kryo kryo;
private final GremlinKryo.HeaderReader headerReader;
private final long batchSize;
private final String vertexIdKey;
private final String edgeIdKey;
private final File tempFile;
final AtomicLong counter = new AtomicLong(0);
private KryoReader(final File tempFile, final long batchSize,
final String vertexIdKey, final String edgeIdKey,
final GremlinKryo gremlinKryo) {
this.kryo = gremlinKryo.createKryo();
this.headerReader = gremlinKryo.getHeaderReader();
this.vertexIdKey = vertexIdKey;
this.edgeIdKey = edgeIdKey;
this.tempFile = tempFile;
this.batchSize = batchSize;
}
@Override
public Vertex readVertex(final InputStream inputStream,
final Direction directionRequested,
final TriFunction<Object, String, Object[], Vertex> vertexMaker,
final QuintFunction<Object, Object, Object, String, Object[], Edge> edgeMaker) throws IOException {
final Input input = new Input(inputStream);
return readVertex(directionRequested, vertexMaker, edgeMaker, input);
}
@Override
public Iterator<Vertex> readVertices(final InputStream inputStream, final Direction direction,
final TriFunction<Object, String, Object[], Vertex> vertexMaker,
final QuintFunction<Object, Object, Object, String, Object[], Edge> edgeMaker) throws IOException {
final Input input = new Input(inputStream);
return new Iterator<Vertex>() {
@Override
public boolean hasNext() {
return !input.eof();
}
@Override
public Vertex next() {
try {
final Vertex v = readVertex(direction, vertexMaker, edgeMaker, input);
// read the vertex terminator
kryo.readClassAndObject(input);
return v;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
};
}
@Override
public Vertex readVertex(final InputStream inputStream, final TriFunction<Object, String, Object[], Vertex> vertexMaker) throws IOException {
return readVertex(inputStream, null, vertexMaker, null);
}
@Override
public Edge readEdge(final InputStream inputStream, final QuintFunction<Object, Object, Object, String, Object[], Edge> edgeMaker) throws IOException {
final Input input = new Input(inputStream);
this.headerReader.read(kryo, input);
final Object outId = kryo.readClassAndObject(input);
final Object inId = kryo.readClassAndObject(input);
final Object edgeId = kryo.readClassAndObject(input);
final String label = input.readString();
final List<Object> edgeArgs = new ArrayList<>();
readElementProperties(input, edgeArgs);
return edgeMaker.apply(edgeId, outId, inId, label, edgeArgs.toArray());
}
@Override
public void readGraph(final InputStream inputStream, final Graph graphToWriteTo) throws IOException {
this.counter.set(0);
final Input input = new Input(inputStream);
this.headerReader.read(kryo, input);
// will throw an exception if not constructed properly
final BatchGraph graph = BatchGraph.create(graphToWriteTo)
.vertexIdKey(vertexIdKey)
.edgeIdKey(edgeIdKey)
.bufferSize(batchSize).build();
try (final Output output = new Output(new FileOutputStream(tempFile))) {
final boolean supportedMemory = input.readBoolean();
if (supportedMemory) {
// if the graph that serialized the data supported memory then the memory needs to be read
// to advance the reader forward. if the graph being read into doesn't support the memory
// then we just setting the data to memory.
final Map<String, Object> memMap = (Map<String, Object>) kryo.readObject(input, HashMap.class);
if (graphToWriteTo.getFeatures().graph().memory().supportsVariables()) {
final Graph.Variables variables = graphToWriteTo.variables();
memMap.forEach(variables::set);
}
}
final boolean hasSomeVertices = input.readBoolean();
if (hasSomeVertices) {
while (!input.eof()) {
final List<Object> vertexArgs = new ArrayList<>();
final Object current = kryo.readClassAndObject(input);
vertexArgs.addAll(Arrays.asList(Element.ID, current));
vertexArgs.addAll(Arrays.asList(Element.LABEL, input.readString()));
readElementProperties(input, vertexArgs);
final Vertex v = graph.addVertex(vertexArgs.toArray());
// the gio file should have been written with a direction specified
final boolean hasDirectionSpecified = input.readBoolean();
final Direction directionInStream = kryo.readObject(input, Direction.class);
final Direction directionOfEdgeBatch = kryo.readObject(input, Direction.class);
// graph serialization requires that a direction be specified in the stream and that the
// direction of the edges be OUT
if (!hasDirectionSpecified || directionInStream != Direction.OUT || directionOfEdgeBatch != Direction.OUT)
throw new IllegalStateException(String.format("Stream must specify edge direction and that direction must be %s", Direction.OUT));
// if there are edges then read them to end and write to temp, otherwise read what should be
// the vertex terminator
if (!input.readBoolean())
kryo.readClassAndObject(input);
else {
// writes the real new id of the outV to the temp. only need to write vertices to temp that
// have edges. no need to reprocess those that don't again.
kryo.writeClassAndObject(output, v.id());
readToEndOfEdgesAndWriteToTemp(input, output);
}
}
}
}
// done writing to temp
// start reading in the edges now from the temp file
try (final Input edgeInput = new Input(new FileInputStream(tempFile))) {
readFromTempEdges(edgeInput, graph);
} finally {
if (graph.getFeatures().graph().supportsTransactions())
graph.tx().commit();
deleteTempFileSilently();
}
}
private Vertex readVertex(final Direction directionRequested, final TriFunction<Object, String, Object[], Vertex> vertexMaker,
final QuintFunction<Object, Object, Object, String, Object[], Edge> edgeMaker, final Input input) throws IOException {
if (null != directionRequested && null == edgeMaker)
throw new IllegalArgumentException("If a directionRequested is specified then an edgeAdder function should also be specified");
this.headerReader.read(kryo, input);
final List<Object> vertexArgs = new ArrayList<>();
final Object vertexId = kryo.readClassAndObject(input);
final String label = input.readString();
readElementProperties(input, vertexArgs);
final Vertex v = vertexMaker.apply(vertexId, label, vertexArgs.toArray());
final boolean streamContainsEdgesInSomeDirection = input.readBoolean();
if (!streamContainsEdgesInSomeDirection && directionRequested != null)
throw new IllegalStateException(String.format("The direction %s was requested but no attempt was made to serialize edges into this stream", directionRequested));
// if there are edges in the stream and the direction is not present then the rest of the stream is
// simply ignored
if (directionRequested != null) {
final Direction directionsInStream = kryo.readObject(input, Direction.class);
if (directionsInStream != Direction.BOTH && directionsInStream != directionRequested)
throw new IllegalStateException(String.format("Stream contains %s edges, but requesting %s", directionsInStream, directionRequested));
final Direction firstDirection = kryo.readObject(input, Direction.class);
if (firstDirection == Direction.OUT && (directionRequested == Direction.BOTH || directionRequested == Direction.OUT))
readEdges(input, (eId, vId, l, properties) -> edgeMaker.apply(eId, v.id(), vId, l, properties));
else {
// prior to this IF should have caught a problem where IN is not supported at all
if (firstDirection == Direction.OUT && directionRequested == Direction.IN)
skipEdges(input);
}
if (directionRequested == Direction.BOTH || directionRequested == Direction.IN) {
// if the first direction was OUT then it was either read or skipped. in that case, the marker
// of the stream is currently ready to read the IN direction. otherwise it's in the perfect place
// to start reading edges
if (firstDirection == Direction.OUT)
kryo.readObject(input, Direction.class);
readEdges(input, (eId, vId, l, properties) -> edgeMaker.apply(eId, vId, v.id(), l, properties));
}
}
return v;
}
private void readEdges(final Input input, final QuadConsumer<Object, Object, String, Object[]> edgeMaker) {
if (input.readBoolean()) {
Object inOrOutVId = kryo.readClassAndObject(input);
while (!inOrOutVId.equals(EdgeTerminator.INSTANCE)) {
final List<Object> edgeArgs = new ArrayList<>();
final Object edgeId = kryo.readClassAndObject(input);
final String edgeLabel = input.readString();
readElementProperties(input, edgeArgs);
edgeMaker.accept(edgeId, inOrOutVId, edgeLabel, edgeArgs.toArray());
inOrOutVId = kryo.readClassAndObject(input);
}
}
}
private void skipEdges(final Input input) {
if (input.readBoolean()) {
Object inOrOutId = kryo.readClassAndObject(input);
while (!inOrOutId.equals(EdgeTerminator.INSTANCE)) {
// skip edgeid
kryo.readClassAndObject(input);
// skip label
input.readString();
// read property count so we know how many properties to skip
final int numberOfProperties = input.readInt();
IntStream.range(0, numberOfProperties).forEach(i -> {
input.readString();
kryo.readClassAndObject(input);
});
// read hidden count so we know how many properties to skip
final int numberOfHiddens = input.readInt();
IntStream.range(0, numberOfHiddens).forEach(i -> {
input.readString();
kryo.readClassAndObject(input);
});
// next in/out id to skip
inOrOutId = kryo.readClassAndObject(input);
}
}
}
/**
* Reads through the all the edges for a vertex and writes the edges to a temp file which will be read later.
*/
private void readToEndOfEdgesAndWriteToTemp(final Input input, final Output output) throws IOException {
Object inId = kryo.readClassAndObject(input);
while (!inId.equals(EdgeTerminator.INSTANCE)) {
kryo.writeClassAndObject(output, inId);
// edge id
kryo.writeClassAndObject(output, kryo.readClassAndObject(input));
// label
output.writeString(input.readString());
// standard properties
final int props = input.readInt();
output.writeInt(props);
IntStream.range(0, props).forEach(i -> {
// key
output.writeString(input.readString());
// value
kryo.writeClassAndObject(output, kryo.readClassAndObject(input));
});
// hidden properties
final int hiddens = input.readInt();
output.writeInt(hiddens);
IntStream.range(0, hiddens).forEach(i -> {
// key
output.writeString(input.readString());
// value
kryo.writeClassAndObject(output, kryo.readClassAndObject(input));
});
// next inId or terminator
inId = kryo.readClassAndObject(input);
}
// this should be the vertex terminator
kryo.readClassAndObject(input);
kryo.writeClassAndObject(output, EdgeTerminator.INSTANCE);
kryo.writeClassAndObject(output, VertexTerminator.INSTANCE);
}
/**
* Read the edges from the temp file and load them to the graph.
*/
private void readFromTempEdges(final Input input, final Graph graphToWriteTo) {
while (!input.eof()) {
// in this case the outId is the id assigned by the graph
final Object outId = kryo.readClassAndObject(input);
Object inId = kryo.readClassAndObject(input);
while (!inId.equals(EdgeTerminator.INSTANCE)) {
final List<Object> edgeArgs = new ArrayList<>();
final Vertex vOut = graphToWriteTo.v(outId);
final Object edgeId = kryo.readClassAndObject(input);
edgeArgs.addAll(Arrays.asList(Element.ID, edgeId));
final String edgeLabel = input.readString();
final Vertex inV = graphToWriteTo.v(inId);
readElementProperties(input, edgeArgs);
vOut.addEdge(edgeLabel, inV, edgeArgs.toArray());
inId = kryo.readClassAndObject(input);
}
// vertex terminator
kryo.readClassAndObject(input);
}
}
private void readElementProperties(final Input input, final List<Object> elementArgs) {
final int numberOfProperties = input.readInt();
IntStream.range(0, numberOfProperties).forEach(i -> {
final String key = input.readString();
elementArgs.add(key);
elementArgs.add(kryo.readClassAndObject(input));
});
final int numberOfHiddens = input.readInt();
IntStream.range(0, numberOfHiddens).forEach(i -> {
final String key = input.readString();
elementArgs.add(Property.hidden(key));
elementArgs.add(kryo.readClassAndObject(input));
});
}
private void deleteTempFileSilently() {
try {
tempFile.delete();
} catch (Exception ex) {
}
}
public static Builder create() {
return new Builder();
}
public static class Builder {
private File tempFile;
private long batchSize = BatchGraph.DEFAULT_BUFFER_SIZE;
private String vertexIdKey = Element.ID;
private String edgeIdKey = Element.ID;
/**
* Always use the most recent kryo version by default
*/
private GremlinKryo gremlinKryo = GremlinKryo.create().build();
private Builder() {
this.tempFile = new File(UUID.randomUUID() + ".tmp");
}
public Builder batchSize(final long batchSize) {
this.batchSize = batchSize;
return this;
}
public Builder custom(final GremlinKryo gremlinKryo) {
this.gremlinKryo = gremlinKryo;
return this;
}
public Builder vertexIdKey(final String vertexIdKey) {
this.vertexIdKey = vertexIdKey;
return this;
}
public Builder edgeIdKey(final String edgeIdKey) {
this.edgeIdKey = edgeIdKey;
return this;
}
/**
* The reader requires a working directory to write temp files to. If this value is not set, it will write
* the temp file to the local directory.
*/
public Builder setWorkingDirectory(final String workingDirectory) {
final File f = new File(workingDirectory);
if (!f.exists() || !f.isDirectory())
throw new IllegalArgumentException("The workingDirectory is not a directory or does not exist");
tempFile = new File(workingDirectory + File.separator + UUID.randomUUID() + ".tmp");
return this;
}
public KryoReader build() {
return new KryoReader(tempFile, batchSize, this.vertexIdKey, this.edgeIdKey, this.gremlinKryo);
}
}
}
|
package com.nsqre.insquare.Activities;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.crashlytics.android.Crashlytics;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.gson.Gson;
import com.nsqre.insquare.InSquareProfile;
import com.nsqre.insquare.R;
import com.nsqre.insquare.Utilities.Analytics.AnalyticsApplication;
import com.nsqre.insquare.Utilities.PushNotification.RegistrationIntentService;
import com.nsqre.insquare.User.User;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import io.fabric.sdk.android.Fabric;
/**
* This is the first activity the user will see. This activity deals with the login, taking tokens from Facebook or Google,
* sending them to the back-end and elaborating the InSquareProfile
* @see InSquareProfile
*/
public class LoginActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks
{
private static final String TAG = "LoginActivity";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private User user;
private InSquareProfile profile;
// Facebook Login
private Button fbLoginButton;
private CallbackManager fbCallbackManager;
private String fbUserId;
/**
* The token received from Facebook
*/
private String fbAccessToken;
private AccessTokenTracker fbTokenTracker;
// Google Login
/**
* The token received from Google
*/
private String gAccessToken;
private GoogleApiClient gApiClient;
private GoogleSignInOptions gSo;
private static final int RC_SIGN_IN = 9001;
private Button gLoginButton;
private Tracker mTracker;
/**
* The OnCreate method of LoginActivity deals with the initialization of Google Analytics, the InSquareProfile data stored locally
* and if they're not present gives the user the possibility to login via Facebook or Google
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
//ANALYTICS
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName(this.getClass().getSimpleName());
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
// Profilo statico perche' non puo' cambiare.
// Singleton perche' cosi non puo' essere duplicato
profile = InSquareProfile.getInstance(getApplicationContext());
if (profile.hasLoginData() && isNetworkAvailable()) {
Log.d(TAG, "onCreate: haslogindata & networkavailable");
launchInSquare();
return;
}else if(!isNetworkAvailable()) {
Toast.makeText(LoginActivity.this, "Senza internet nel 2016?... non posso fare niente.", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "onCreate: going past launching..?");
fbCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(fbCallbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "Success Login");
requestFacebookData(); //fa la post
//fbLoginButton.setText(R.string.fb_logout_string);
}
@Override
public void onCancel() {
Log.d(TAG, "Facebook Login canceled");
}
@Override
public void onError(FacebookException exception) {
Log.d(TAG, "onError:\n" + exception.toString());
CharSequence text = getString(R.string.connFail);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
toast.show();
}
});
gLoginButton = (Button) findViewById(R.id.google_login_button);
fbLoginButton = (Button) findViewById(R.id.fb_login_button);
// Permessi da richiedere durante il login
fbLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile", "email", "user_friends"));
}
});
// setup delle opzioni di google+
gSo = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestProfile()
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
gApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gSo)
.build();
gApiClient.connect();
gLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(gApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
// Se il login e' gia' stato effettuato, fai le post
if(isGoogleSignedIn()) {
Log.d(TAG, "Google is already logged in!");
//gLoginButton.setText(R.string.google_logout_string);
googlePostRequest();
} else if(isFacebookSignedIn())
{
Log.d(TAG, "onCreate: Facebook is already logged in!");
//fbLoginButton.setText(R.string.fb_logout_string);
facebookPostRequest();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Ritorno dal login di Google+
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
googleSignInResult(result); //dalla post parte l'app
} else {
// Ritorno dal Login di Facebook
fbCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
mTracker.setScreenName(this.getClass().getSimpleName());
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution())
{
try
{
connectionResult.startResolutionForResult(this, 9000);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}else
{
Log.d(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
Log.d(TAG, "Error on connection!\n" + connectionResult.getErrorMessage());
}
/**
* This method initializes the values of the InSquareProfile
* @param jsonUser the json string that represents the user
* @see InSquareProfile
*/
private void json2login(String jsonUser) {
Gson gson = new Gson();
user = gson.fromJson(jsonUser, User.class);
Log.d(TAG, "json2login: " + user);
profile.userId = user.getId();
profile.username = user.getName();
profile.email = user.getEmail();
profile.pictureUrl = user.getPicture();
if("undefined?sz=200".equals(profile.pictureUrl)){
profile.pictureUrl = getString(R.string.avatarURL);
}
profile.save(getApplicationContext());
if (checkPlayServices()) {
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
launchInSquare();
}
/**
* This method is called after the login is considered successful. It creates an intent to MapActivity to open the map
* or the ProfileFragment, depending on the extras that are put in it.
* @see MapActivity
*/
private void launchInSquare() {
Log.d(TAG, "launchInSquare: launching!");
Intent intent = new Intent(getApplicationContext(), MapActivity.class);
if(getIntent().getExtras() != null && getIntent().getExtras().getInt("profile") == 2) {
intent.putExtra("profile",getIntent().getExtras().getInt("profile"));
getIntent().getExtras().clear();
}
startActivity(intent);
}
/**
* This method creates a POST request to the backend to manage Facebook login
* The backend answers with data that are used in json2login
* @see #json2login(String)
*/
private void facebookPostRequest() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
String url = getString(R.string.facebookTokenUrl);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "ServerResponse " + response);
json2login(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "ServerResponse" + error.toString());
}
}) {
//TOKEN messo nei parametri della query
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", fbAccessToken);
return params;
}
};
queue.add(stringRequest);
}
/**
* This method creates a POST request to the backend to manage Google login
* The backend answers with data that are used in json2login
* @see #json2login(String)
*/
private void googlePostRequest() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
String url = getString(R.string.googleTokenUrl);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Google+ Response: " + response);
json2login(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Google+ Error Response: " + error.toString());
}
}) {
@Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", gAccessToken);
return params;
}
};
queue.add(stringRequest);
}
/**
* This method manages the result of the Google Authentication calling googlePostRequest() in case of success
* @see #googlePostRequest()
*/
private void googleSignInResult(GoogleSignInResult result) {
Log.d("Google" + TAG, "Success? " + result.isSuccess() + "\nStatus Code: " + result.getStatus().getStatusCode());
if (result.isSuccess())
{
GoogleSignInAccount acct = result.getSignInAccount();
gAccessToken = acct.getIdToken();
Log.d(TAG, "Login was a success: " + acct.getDisplayName() + ": " + acct.getEmail());
Log.d(TAG, "Token is: " + acct.getIdToken());
//gLoginButton.setText(R.string.google_logout_string);
profile.googleEmail = acct.getEmail();
profile.googleToken = acct.getIdToken();
profile.googleName = acct.getDisplayName();
profile.googleId = acct.getId();
profile.save(getApplicationContext());
googlePostRequest();
} else { //connessione fallita
CharSequence text = getString(R.string.connFail);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
toast.show();
}
}
/**
* This method manages Facebook's authentication calling facebookPostRequest() in case of success
* @see #facebookPostRequest()
*/
private void requestFacebookData()
{
// Creazione di una nuova richiesta al grafo di Facebook per le informazioni necessarie
GraphRequest graphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d(TAG, "Hello Facebook!" + response.toString());
try {
String nome = object.getString("name");
String email = object.getString("email");
String gender = object.getString("gender");
String id = object.getString("id");
fbAccessToken = AccessToken.getCurrentAccessToken().getToken();
profile.facebookName = nome;
profile.facebookEmail = email;
profile.facebookId = id;
profile.facebookToken = fbAccessToken;
profile.save(getApplicationContext());
Log.d(TAG, "Name: " + nome
+ " email: " + email
+ " Gender: " + gender
+ " ID: " + id);
facebookPostRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle params = new Bundle();
params.putString("fields", "id,name,gender,email,picture");
graphRequest.setParameters(params);
graphRequest.executeAsync();
}
/**
* This method checks if the user is logged in via Google
* @return true if the user is logged in via Google
*/
private boolean isGoogleSignedIn()
{
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(gApiClient);
boolean result = opr.isDone();
if(result)
gAccessToken = opr.get().getSignInAccount().getIdToken();
return result;
}
/**
* This method checks if the user is logged in via Facebook
* @return true if the user is logged in via Facebook
*/
private boolean isFacebookSignedIn()
{
try {
AccessToken token = AccessToken.getCurrentAccessToken();
if(token != null)
{
fbAccessToken = token.getToken();
Log.d(TAG, "FB Token: " + fbAccessToken);
return true;
}
return false;
}
catch (Exception e) {
Log.d(TAG, "FB token error: " + e.toString());
}
return false;
}
/**
* This method checks if the network is currently available
* @return true if the Network is available
*/
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* This method creates the action menu
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return true;
}
/**
* This method manages the options from the Action menu
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.instfeedback:
// [START feedback_event]
mTracker.send(new HitBuilders.EventBuilder()
.setCategory("Action")
.setAction("Feedback")
.build());
// [END feedback_event]
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_feedback);
d.setTitle("Feedback");
d.setCancelable(true);
d.show();
final EditText feedbackText = (EditText) d.findViewById(R.id.dialog_feedbacktext);
Button confirm = (Button) d.findViewById(R.id.dialog_feedback_confirm_button);
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String feedback = feedbackText.getText().toString();
final String activity = this.getClass().getSimpleName();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
String url = getString(R.string.feedbackUrl);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "VOLLEY ServerResponse: " + response);
CharSequence text = getString(R.string.thanks_feedback);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
toast.show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "VOLLEY Error: " + error.toString());
CharSequence text = getString(R.string.error_feedback);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
toast.show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("feedback", feedback);
if (user != null)
params.put("username", user.getId());
params.put("activity", activity);
return params;
}
};
queue.add(stringRequest);
d.dismiss();
}
});
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}
|
package org.pdxfinder.dataloaders.updog;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.pdxfinder.BaseTest;
import org.pdxfinder.graph.dao.*;
import org.pdxfinder.services.DataImportService;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DomainObjectCreatorTest extends BaseTest {
@MockBean
private DataImportService dataImportService;
private DomainObjectCreator domainObjectCreator;
private Group providerGroup;
private Patient testPatient;
private ModelCreation testModel;
@Before
public void setUp(){
Map<String, Table> pdxDataTables = getTestDataTable();
domainObjectCreator = new DomainObjectCreator(dataImportService, pdxDataTables);
providerGroup = new Group("TestProvider", "TP", "description", "",
"", "");
providerGroup.setType("Provider");
testPatient = new Patient("patient1", "female", "-", "ethnicity",providerGroup );
testModel = new ModelCreation("model1");
}
@Test
public void Given_ProviderTable_When_CreateProviderIsCalled_Then_ProviderNodeIsInDomainMap(){
when(dataImportService.getProviderGroup(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(providerGroup);
domainObjectCreator.createProvider();
Group provider = (Group) domainObjectCreator.getDomainObject("provider_group", null);
Assert.assertEquals("TP", provider.getAbbreviation());
}
@Test
public void Given_PatientTable_When_CreatePatient_Then_PatientNodeIsInMap(){
domainObjectCreator.addDomainObject("provider_group", null, providerGroup);
when(dataImportService.createPatient("patient1", providerGroup, "female", "", "ethnicity")).thenReturn(testPatient);
when(dataImportService.savePatient(testPatient)).thenReturn(testPatient);
domainObjectCreator.createPatientData();
Patient patient = (Patient) domainObjectCreator.getDomainObject("patient", "patient1");
Assert.assertEquals("patient1", patient.getExternalId());
Assert.assertEquals("female", patient.getSex());
}
@Test
public void Given_ModelTable_When_CreateModel_Then_ModelNodeIsInMap(){
domainObjectCreator.addDomainObject("provider_group", null, providerGroup);
domainObjectCreator.createModelData();
ModelCreation model = (ModelCreation) domainObjectCreator.getDomainObject("model", "model1");
Assert.assertEquals("model1", model.getSourcePdxId());
}
@Test
public void Given_SampleTable_When_CreateSample_Then_SampleIsInMap(){
domainObjectCreator.addDomainObject("provider_group", null, providerGroup);
domainObjectCreator.addDomainObject("patient", "patient1", testPatient);
domainObjectCreator.addDomainObject("model", "model1", testModel);
when(dataImportService.getTumorType("Primary")).thenReturn(new TumorType("Primary"));
domainObjectCreator.createSampleData();
ModelCreation model = (ModelCreation) domainObjectCreator.getDomainObject("model", "model1");
Patient patient = (Patient) domainObjectCreator.getDomainObject("patient", "patient1");
Sample sample = model.getSample();
Assert.assertEquals("sample1", sample.getSourceSampleId());
Assert.assertEquals("70",patient.getSnapshotByDate("01/01/1900").getAgeAtCollection());
Assert.assertEquals("Primary", sample.getType().getName());
}
@Test
public void Given_SharingTable_When_CreateSharing_Then_SharingInfoAdded(){
domainObjectCreator.addDomainObject("provider_group", null, providerGroup);
domainObjectCreator.addDomainObject("model", "model1", testModel);
when(dataImportService.getProjectGroup("EuroPDX")).thenReturn(getProjectGroup("EuroPDX"));
when(dataImportService.getAccessibilityGroup("academia", "collaboration only")).thenReturn(getAccessGroup("academia", "collaboration only"));
domainObjectCreator.createSharingData();
ModelCreation model = (ModelCreation) domainObjectCreator.getDomainObject("model", "model1");
Set<Group> groups = model.getGroups();
Group projectGroup = new Group();
Group accessGroup = new Group();
for(Group group : groups){
if(group != null && group.getType().equals("Project")) projectGroup = group;
if(group != null && group.getType().equals("Accessibility")) accessGroup = group;
}
Assert.assertEquals("EuroPDX", projectGroup.getName());
Assert.assertEquals("academia", accessGroup.getAccessibility());
Assert.assertEquals("collaboration only", accessGroup.getAccessModalities());
}
private Map<String, Table> getTestDataTable(){
Map<String, Table> tableMap = new HashMap<>();
String[] loaderCol1 = {"v1", "v2", "v3", "v4", "Test Provider"};
String[] loaderCol2 = {"v1", "v2", "v3", "v4", "TP"};
String[] loaderCol3 = {"v1", "v2", "v3", "v4", "/source/test"};
String[] loaderCol4 = {"v1", "v2", "v3", "v4", ""};
Table loaderTable = Table.create("metadata-loader.tsv").addColumns(
StringColumn.create("name", loaderCol1),
StringColumn.create("abbreviation", loaderCol2),
StringColumn.create("internal_url", loaderCol3),
StringColumn.create("internal_dosing_url", loaderCol4)
);
tableMap.put("metadata-loader.tsv", loaderTable);
String[] patientCol1 = {"v1", "v2", "v3", "v4","patient1"};
String[] patientCol2 = {"v1", "v2", "v3", "v4","female"};
String[] patientCol3 = {"v1", "v2", "v3", "v4","history"};
String[] patientCol4 = {"v1", "v2", "v3", "v4","ethnicity"};
String[] patientCol5 = {"v1", "v2", "v3", "v4","initial diagnosis"};
String[] patientCol6 = {"v1", "v2", "v3", "v4","age at initial diagnosis"};
Table patientTable = Table.create("metadata-patient.tsv").addColumns(
StringColumn.create("patient_id", patientCol1),
StringColumn.create("sex", patientCol2),
StringColumn.create("history", patientCol3),
StringColumn.create("ethnicity", patientCol4),
StringColumn.create("initial_diagnosis", patientCol5),
StringColumn.create("age_at_initial_diagnosis", patientCol6)
);
tableMap.put("metadata-patient.tsv", patientTable);
String[] modelCol1 = {"v1", "v2", "v3", "v4","model1"};
String[] modelCol2 = {"v1", "v2", "v3", "v4","hoststrainname1"};
String[] modelCol3 = {"v1", "v2", "v3", "v4","hoststrainnomenclature1"};
String[] modelCol4 = {"v1", "v2", "v3", "v4","engraftmentsite1"};
String[] modelCol5 = {"v1", "v2", "v3", "v4","engraftmenttype1"};
String[] modelCol6 = {"v1", "v2", "v3", "v4","sampletype1"};
String[] modelCol7 = {"v1", "v2", "v3", "v4","samplestate1"};
String[] modelCol8 = {"v1", "v2", "v3", "v4","1"};
String[] modelCol9 = {"v1", "v2", "v3", "v4","publications1"};
Table modelTable = Table.create("metadata-model.tsv").addColumns(
StringColumn.create("model_id", modelCol1),
StringColumn.create("host_strain", modelCol2),
StringColumn.create("host_strain_full", modelCol3),
StringColumn.create("engraftment_site", modelCol4),
StringColumn.create("engraftment_type", modelCol5),
StringColumn.create("sample_type", modelCol6),
StringColumn.create("sample_state", modelCol7),
StringColumn.create("passage_number", modelCol8),
StringColumn.create("publications", modelCol9)
);
tableMap.put("metadata-model.tsv", modelTable);
String[] modelValCol1 = {"v1", "v2", "v3", "v4","model1"};
String[] modelValCol2 = {"v1", "v2", "v3", "v4","techique1"};
String[] modelValCol3 = {"v1", "v2", "v3", "v4","description1"};
String[] modelValCol4 = {"v1", "v2", "v3", "v4","passage1"};
String[] modelValCol5 = {"v1", "v2", "v3", "v4","hoststrain1"};
Table modelValidationTable = Table.create("metadata-model_validation.tsv").addColumns(
StringColumn.create("model_id", modelValCol1),
StringColumn.create("validation_technique", modelValCol2),
StringColumn.create("description", modelValCol3),
StringColumn.create("passages_tested", modelValCol4),
StringColumn.create("validation_host_strain_full", modelValCol5)
);
tableMap.put("metadata-model_validation.tsv", modelValidationTable);
String[] sampleCol1 = {"v1", "v2", "v3", "v4","patient1"};
String[] sampleCol2 = {"v1", "v2", "v3", "v4","sample1"};
String[] sampleCol3 = {"v1", "v2", "v3", "v4","01/01/1900"};
String[] sampleColEmpty = {"v1", "v2", "v3", "v4",""};
String[] sampleCol6 = {"v1", "v2", "v3", "v4","70"};
String[] sampleCol7 = {"v1", "v2", "v3", "v4","Cancer"};
String[] sampleCol8 = {"v1", "v2", "v3", "v4","Primary"};
String[] sampleCol9 = {"v1", "v2", "v3", "v4","Breast"};
String[] sampleCol10 = {"v1", "v2", "v3", "v4","Breast"};
String[] sampleCol11 = {"v1", "v2", "v3", "v4","model1"};
Table sampleTable = Table.create("metadata-sample.tsv").addColumns(
StringColumn.create("patient_id", sampleCol1),
StringColumn.create("sample_id", sampleCol2),
StringColumn.create("collection_date", sampleCol3),
StringColumn.create("age_in_years_at_collection", sampleCol6),
StringColumn.create("diagnosis", sampleCol7),
StringColumn.create("tumour_type", sampleCol8),
StringColumn.create("primary_site", sampleCol9),
StringColumn.create("collection_site", sampleCol10),
StringColumn.create("model_id", sampleCol11),
StringColumn.create("collection_event", sampleColEmpty),
StringColumn.create("months_since_collection_1", sampleColEmpty),
StringColumn.create("virology_status", sampleColEmpty),
StringColumn.create("stage", sampleColEmpty),
StringColumn.create("staging_system", sampleColEmpty),
StringColumn.create("grade", sampleColEmpty),
StringColumn.create("grading_system", sampleColEmpty),
StringColumn.create("treatment_naive_at_collection", sampleColEmpty)
);
tableMap.put("metadata-sample.tsv", sampleTable);
String[] shareCol1 = {"v1", "v2", "v3", "v4","model1"};
String[] shareCol2 = {"v1", "v2", "v3", "v4","academia"};
String[] shareCol3 = {"v1", "v2", "v3", "v4","academia"};
String[] shareCol4 = {"v1", "v2", "v3", "v4","collaboration only"};
String[] shareCol5 = {"v1", "v2", "v3", "v4","test@test.com"};
String[] shareCol6 = {"v1", "v2", "v3", "v4","Test Contact"};
String[] shareCol7 = {"v1", "v2", "v3", "v4",""};
String[] shareCol8 = {"v1", "v2", "v3", "v4","EuroPDX"};
Table shareTable = Table.create("metadata-sharing.tsv").addColumns(
StringColumn.create("model_id", shareCol1),
StringColumn.create("provider_type", shareCol2),
StringColumn.create("accessibility", shareCol3),
StringColumn.create("europdx_access_modality", shareCol4),
StringColumn.create("email", shareCol5),
StringColumn.create("form_url", shareCol6),
StringColumn.create("database_url", shareCol7),
StringColumn.create("project", shareCol8)
);
tableMap.put("metadata-sharing.tsv", shareTable);
return tableMap;
}
private Group getProjectGroup(String name){
Group group = new Group();
group.setType("Project");
group.setName(name);
return group;
}
private Group getAccessGroup(String accessibility, String accessModalities){
Group group = new Group(accessibility, accessModalities);
group.setType("Accessibility");
return group;
}
}
|
package com.intellij.execution.ui;
import com.intellij.application.options.ModuleDescriptionsComboBox;
import com.intellij.execution.ShortenCommandLine;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Computable;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.Consumer;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.function.Supplier;
public class ShortenCommandLineModeCombo extends ComboBox<ShortenCommandLine> {
private final Supplier<ShortenCommandLine> myDefaultMethodSupplier;
public ShortenCommandLineModeCombo(Project project,
JrePathEditor pathEditor,
ModuleDescriptionsComboBox component) {
this(project, pathEditor, component::getSelectedModule, component::addActionListener);
}
public ShortenCommandLineModeCombo(Project project,
JrePathEditor pathEditor,
Computable<? extends Module> component,
Consumer<? super ActionListener> listenerConsumer) {
myDefaultMethodSupplier = () -> ShortenCommandLine.getDefaultMethod(project, getJdkRoot(pathEditor, component.compute()));
initModel(myDefaultMethodSupplier.get(), pathEditor, component.compute());
setRenderer(new ColoredListCellRenderer<>() {
@Override
protected void customizeCellRenderer(@NotNull JList<? extends ShortenCommandLine> list,
ShortenCommandLine value,
int index,
boolean selected,
boolean hasFocus) {
append(value.getPresentableName()).append(" - " + value.getDescription(), SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
});
ActionListener updateModelListener = e -> {
ShortenCommandLine item = getSelectedItem();
initModel(item, pathEditor, component.compute());
};
pathEditor.addActionListener(updateModelListener);
listenerConsumer.consume(updateModelListener);
}
private void initModel(ShortenCommandLine preselection, JrePathEditor pathEditor, Module module) {
removeAllItems();
String jdkRoot = getJdkRoot(pathEditor, module);
for (ShortenCommandLine mode : ShortenCommandLine.values()) {
if (mode.isApplicable(jdkRoot)) {
addItem(mode);
}
}
setSelectedItem(preselection);
}
@Nullable
private String getJdkRoot(JrePathEditor pathEditor, Module module) {
if (!pathEditor.isAlternativeJreSelected()) {
if (module != null) {
Sdk sdk = JavaParameters.getJdkToRunModule(module, productionOnly());
return sdk != null ? sdk.getHomePath() : null;
}
return null;
}
String jrePathOrName = pathEditor.getJrePathOrName();
if (jrePathOrName != null) {
Sdk configuredJdk = ProjectJdkTable.getInstance().findJdk(jrePathOrName);
if (configuredJdk != null) {
return configuredJdk.getHomePath();
}
else {
return jrePathOrName;
}
}
return null;
}
protected boolean productionOnly() {
return true;
}
@Nullable
@Override
public ShortenCommandLine getSelectedItem() {
return (ShortenCommandLine)super.getSelectedItem();
}
@Override
public void setSelectedItem(Object anObject) {
super.setSelectedItem(ObjectUtils.notNull(anObject, myDefaultMethodSupplier.get()));
}
}
|
package de.hsmannheim.iws2014.analyzers;
import com.sun.corba.se.impl.orb.ParserTable;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.simple.SimpleQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class PiglatinTest {
private String[] terms = new String[] {
"foobar", "gumba", "trantual", "alfredolino", "ugulu", "bla"
};
@Test
public void test_without_analyzer() throws Exception {
RAMDirectory dir = new RAMDirectory();
CustomAnalyzingIndexer indexer = new CustomAnalyzingIndexer(new StandardAnalyzer(), dir);
indexer.index(Arrays.asList(terms));
TopDocs foobar = contentSearch("foobar", dir);
assertThat(foobar.totalHits, is(equalTo(1)));
TopDocs oobarfay = contentSearch("oobarfay", dir);
assertThat(oobarfay.totalHits, is(equalTo(0)));
}
@Test
public void test_with_pig_lating_analyzer() throws Exception {
RAMDirectory dir = new RAMDirectory();
CustomAnalyzingIndexer indexer = new CustomAnalyzingIndexer(new PigLatinAnalyzer(), dir);
indexer.index(Arrays.asList(terms));
TopDocs foobar = contentSearch("foobar", dir);
assertThat(foobar.totalHits, is(equalTo(0)));
TopDocs oobarfay = contentSearch("oobarfay", dir);
assertThat(oobarfay.totalHits, is(equalTo(1)));
}
@Test
public void test_conversion() throws Exception {
StringBuffer sb = new StringBuffer();
for (String term : terms) {
sb.append(term).append(" ");
}
AnalyzerUtils.displayTokens(new PigLatinAnalyzer(), sb.toString());
}
private static TopDocs contentSearch(String query, Directory directory) throws IOException {
IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(directory));
SimpleQueryParser queryParser = new SimpleQueryParser(new StandardAnalyzer(), "content");
return indexSearcher.search(queryParser.parse(query), 1000);
}
}
|
package org.ccnx.ccn.profiles.security.access.group;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.CCNFlowControl.SaveType;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.io.content.ContentGoneException;
import org.ccnx.ccn.io.content.ContentNotReadyException;
import org.ccnx.ccn.io.content.KeyDirectory;
import org.ccnx.ccn.io.content.Link;
import org.ccnx.ccn.io.content.Link.LinkObject;
import org.ccnx.ccn.io.content.WrappedKey.WrappedKeyObject;
import org.ccnx.ccn.profiles.VersionMissingException;
import org.ccnx.ccn.profiles.security.access.AccessDeniedException;
import org.ccnx.ccn.profiles.security.access.group.GroupAccessControlProfile.PrincipalInfo;
import org.ccnx.ccn.protocol.ContentName;
/**
* This structure is used for representing both node keys and group
* (private) keys. We encapsulate functionality to walk such a directory
* and find our target key here.
*
* We store links providing additional information about how to retrieve
* this key -- e.g. a link from a given group or principal name to a key ID-named
* block, in case a group member does not know an earlier version of their
* group public key. Or links to keys this key supercedes or precedes.
*/
public class PrincipalKeyDirectory extends KeyDirectory {
GroupAccessControlManager _manager; // to get at GroupManager
/**
* Maps the friendly names of principals (typically groups) to their information.
*/
HashMap<String, PrincipalInfo> _principals = new HashMap<String, PrincipalInfo>();
final ReadWriteLock _principalsLock = new ReentrantReadWriteLock();
/**
* Directory name should be versioned, else we pull the latest version; start
* enumeration.
* @param manager the access control manager.
* @param directoryName the root of the KeyDirectory.
* @param handle
* @throws IOException
*/
public PrincipalKeyDirectory(GroupAccessControlManager manager, ContentName directoryName, CCNHandle handle)
throws IOException {
this(manager, directoryName, true, handle);
}
/**
* Directory name should be versioned, else we pull the latest version.
* @param manager the access control manager - must not be null
* @param directoryName the root of the KeyDirectory.
* @param handle
* @throws IOException
*/
public PrincipalKeyDirectory(GroupAccessControlManager manager, ContentName directoryName, boolean enumerate, CCNHandle handle)
throws IOException {
super(directoryName, enumerate, handle);
_manager = manager;
}
/**
* Called each time new data comes in, gets to parse it and load processed
* arrays.
*/
@Override
protected void processNewChild(byte [] wkChildName) {
if (PrincipalInfo.isPrincipalNameComponent(wkChildName)) {
addPrincipal(wkChildName);
} else
super.processNewChild(wkChildName);
}
/**
* Return a copy to avoid synchronization problems.
* @throws ContentNotReadyException
*/
public HashMap<String, PrincipalInfo> getCopyOfPrincipals() throws ContentNotReadyException {
if (!hasChildren()) {
throw new ContentNotReadyException("Need to call waitForData(); assuming directory known to be non-empty!");
}
HashMap<String, PrincipalInfo> copy = new HashMap<String, PrincipalInfo>();
try {
_principalsLock.readLock().lock();
for (String key: _principals.keySet()) {
PrincipalInfo value = _principals.get(key);
copy.put(key, value);
}
} finally {
_principalsLock.readLock().unlock();
}
return copy;
}
/**
* Adds a principal name
* @param wkChildName the principal name
*/
protected void addPrincipal(byte [] wkChildName) {
PrincipalInfo pi = new PrincipalInfo(wkChildName);
try{
_principalsLock.writeLock().lock();
_principals.put(pi.friendlyName(), pi);
}finally{
_principalsLock.writeLock().unlock();
}
}
/**
* Store an additional link object pointing to the wrapped key object
* in the KeyDirectory. The link object is named with the Principal's name
* to allow searching the KeyDirectory by Principal name rather than KeyID.
*/
@Override
public WrappedKeyObject addWrappedKeyBlock(Key secretKeyToWrap,
ContentName publicKeyName, PublicKey publicKey)
throws ContentEncodingException, IOException, InvalidKeyException,
VersionMissingException {
WrappedKeyObject wko = super.addWrappedKeyBlock(secretKeyToWrap, publicKeyName, publicKey);
LinkObject lo = new LinkObject(getWrappedKeyNameForPrincipal(publicKeyName), new Link(wko.getVersionedName()), SaveType.REPOSITORY, _handle);
lo.save();
return wko;
}
@Override
protected KeyDirectory factory(ContentName name) throws IOException {
return new PrincipalKeyDirectory(_manager, name, _handle);
}
/**
* Returns the wrapped key object corresponding to a specified principal.
* @param principalName the principal.
* @return the corresponding wrapped key object.
* @throws IOException
* @throws ContentNotReadyException
* @throws ContentDecodingException
*/
protected WrappedKeyObject getWrappedKeyForPrincipal(String principalName)
throws ContentNotReadyException, ContentDecodingException, IOException {
if (!hasChildren()) {
throw new ContentNotReadyException("Need to call waitForData(); assuming directory known to be non-empty!");
}
PrincipalInfo pi = null;
try{
_principalsLock.readLock().lock();
if (!_principals.containsKey(principalName)) {
return null;
}
pi = _principals.get(principalName);
}finally{
_principalsLock.readLock().unlock();
}
if (null == pi) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "No block available for principal: {0}", principalName);
}
return null;
}
ContentName principalLinkName = getWrappedKeyNameForPrincipal(pi);
// This should be a link to the actual key block
// TODO DKS should wait on link data...
LinkObject principalLink = new LinkObject(principalLinkName, _handle);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Retrieving wrapped key for principal {0} at {1}", principalName, principalLink.getTargetName());
}
ContentName wrappedKeyName = principalLink.getTargetName();
return getWrappedKey(wrappedKeyName);
}
/**
* Returns the wrapped key name for a specified principal.
* @param isGroup whether the principal is a group.
* @param principalName the name of the principal.
* @param principalVersion the version of the principal.
* @return the corresponding wrapped key name.
*/
protected ContentName getWrappedKeyNameForPrincipal(PrincipalInfo pi) {
ContentName principalLinkName = new ContentName(_namePrefix, pi.toNameComponent());
return principalLinkName;
}
/**
* Returns the wrapped key name for a principal specified by the name of its public key.
* @param principalPublicKeyName the name of the public key of the principal.
* @return the corresponding wrapped key name.
* @throws VersionMissingException
* @throws ContentEncodingException
*/
protected ContentName getWrappedKeyNameForPrincipal(ContentName principalPublicKeyName) throws VersionMissingException, ContentEncodingException {
PrincipalInfo info = new PrincipalInfo(_manager, principalPublicKeyName);
return getWrappedKeyNameForPrincipal(info);
}
@Override
protected Key findUnwrappedKey(byte[] expectedKeyID) throws IOException,
ContentNotReadyException, InvalidKeyException,
ContentDecodingException, NoSuchAlgorithmException {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINEST)) {
Log.finest(Log.FAC_ACCESSCONTROL, "PrincipalKeyDirectory.findUnwrappedKey({0})", DataUtils.printHexBytes(expectedKeyID));
}
Key unwrappedKey = super.findUnwrappedKey(expectedKeyID);
if (unwrappedKey == null) {
// This is the current key. Enumerate principals and see if we can get a key to unwrap.
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "PrincipalKeyDirectory.findUnwrappedKey: at latest version of key {0}, attempting to unwrap.", getName());
}
// Assumption: if this key was encrypted directly for me, I would have had a cache
// hit already. The assumption is that I pre-load my cache with my own private key(s).
// So I don't care about principal entries if I get here, I only care about groups.
// Groups may come in three types: ones I know I am a member of, but don't have this
// particular key version for, ones I don't know anything about, and ones I believe
// I'm not a member of but someone might have added me.
if (_manager.haveKnownGroupMemberships()) {
unwrappedKey = unwrapKeyViaKnownGroupMembership();
}
if (unwrappedKey == null) {
// OK, we don't have any groups we know we are a member of. Do the other ones.
// Slower, as we crawl the groups tree.
unwrappedKey = unwrapKeyViaNotKnownGroupMembership();
}
return unwrappedKey;
}
return unwrappedKey;
}
protected Key unwrapKeyViaKnownGroupMembership() throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
Key unwrappedKey = null;
try{
_principalsLock.readLock().lock();
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "PrincipalKeyDirectory.unwrapKeyViaKnownGroupMembership: the directory has {0} principals.", _principals.size());
}
for (String principal : _principals.keySet()) {
PrincipalInfo pInfo = _principals.get(principal);
GroupManager pgm = _manager.groupManager(pInfo.distinguishingHash());
if ((pgm == null) || (! pgm.isGroup(principal, SystemConfiguration.EXTRA_LONG_TIMEOUT)) ||
(! pgm.amKnownGroupMember(principal))) {
// On this pass, only do groups that I think I'm a member of. Do them
// first as it is likely faster.
continue;
}
// I know I am a member of this group, or at least I was last time I checked.
// Attempt to get this version of the group private key as I don't have it in my cache.
try {
Key principalKey = pgm.getVersionedPrivateKeyForGroup(pInfo);
unwrappedKey = unwrapKeyForPrincipal(principal, principalKey);
if (null == unwrappedKey)
continue;
} catch (AccessDeniedException aex) {
// we're not a member
continue;
}
}
} finally {
_principalsLock.readLock().unlock();
}
return unwrappedKey;
}
protected Key unwrapKeyViaNotKnownGroupMembership() throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
Key unwrappedKey = null;
try{
_principalsLock.readLock().lock();
for (PrincipalInfo pInfo : _principals.values()) {
String principal = pInfo.friendlyName();
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "PrincipalKeyDirectory.unwrapKeyViaNotKnownGroupMembership: the KD secret key is wrapped under the key of principal {0}",
pInfo);
}
GroupManager pgm = _manager.groupManager(pInfo.distinguishingHash());
if ((pgm == null) || (! pgm.isGroup(principal, SystemConfiguration.EXTRA_LONG_TIMEOUT)) ||
(pgm.amKnownGroupMember(principal))) {
// On this pass, only do groups that I don't think I'm a member of.
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "PrincipalKeyDirectory.unwrapKeyViaNotKnownGroupMembership: skipping principal {0}.", principal);
}
continue;
}
if (pgm.amCurrentGroupMember(principal)) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "PrincipalKeyDirectory.unwrapKeyViaNotKnownGroupMembership: I am a member of group {0} ", principal);
}
try {
Key principalKey = pgm.getVersionedPrivateKeyForGroup(pInfo);
unwrappedKey = unwrapKeyForPrincipal(principal, principalKey);
if (null == unwrappedKey) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "Unexpected: we are a member of group {0} but get a null key.", principal);
}
continue;
}
} catch (AccessDeniedException aex) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "Unexpected: we are a member of group " + principal + " but get an access denied exception when we try to get its key: " + aex.getMessage());
}
continue;
}
}
else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "PrincipalKeyDirectory.unwrapKeyViaNotKnownGroupMembership: I am not a member of group {0} ", principal);
}
}
}
} finally {
_principalsLock.readLock().unlock();
}
return unwrappedKey;
}
/**
* Unwrap the key wrapped under a specified principal, with a specified unwrapping key.
* @param principal
* @param unwrappingKey
* @return
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws IOException
* @throws NoSuchAlgorithmException
*/
protected Key unwrapKeyForPrincipal(String principal, Key unwrappingKey)
throws InvalidKeyException, ContentNotReadyException,
ContentDecodingException, ContentGoneException, IOException, NoSuchAlgorithmException {
Key unwrappedKey = null;
if (null == unwrappingKey) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Null unwrapping key. Cannot unwrap.");
}
return null;
}
WrappedKeyObject wko = getWrappedKeyForPrincipal(principal); // checks hasChildren
if (null != wko.wrappedKey()) {
unwrappedKey = wko.wrappedKey().unwrapKey(unwrappingKey);
} else {
try{
_principalsLock.readLock().lock();
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Unexpected: retrieved version {0} of {1} group key, but cannot retrieve wrapped key object.",
_principals.get(principal), principal);
}
}finally{
_principalsLock.readLock().unlock();
}
}
return unwrappedKey;
}
}
|
import com.example.cloudwatch.DeleteAlarm;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.*;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import com.example.cloudwatch.*;
import java.io.*;
import java.util.*;
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class CloudWatchServiceIntegrationTest {
private static CloudWatchClient cw = null;
private static CloudWatchLogsClient cloudWatchLogsClient = null;
private static String logGroup="";
private static String alarmName="";
private static String streamName ="";
private static String metricId = "";
private static String instanceId="";
private static String ruleResource = "";
private static String filterName="";
private static String destinationArn="";
private static String roleArn ="";
private static String filterPattern = "";
@BeforeAll
public static void setUp() throws IOException {
Region region = Region.US_WEST_2;;
cw = CloudWatchClient.builder()
.region(region)
.build();
cloudWatchLogsClient = CloudWatchLogsClient.builder().build();
try (InputStream input = CloudWatchServiceIntegrationTest.class.getClassLoader().getResourceAsStream("config.properties")) {
Properties prop = new Properties();
if (input == null) {
System.out.println("Sorry, unable to find config.properties");
return;
}
//load a properties file from class path, inside static method
prop.load(input);
// Populate the data members required for all tests
logGroup = prop.getProperty("logGroup");
alarmName = prop.getProperty("alarmName");
streamName = prop.getProperty("streamName");
ruleResource = prop.getProperty("ruleResource");
metricId = prop.getProperty("metricId");
filterName = prop.getProperty("filterName");
destinationArn = prop.getProperty("destinationArn");
roleArn= prop.getProperty("roleArn");
filterPattern= prop.getProperty("filterPattern");
instanceId= prop.getProperty("instanceId");
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Test
@Order(1)
public void whenInitializingAWSCWService_thenNotNull() {
assertNotNull(cw);
assertNotNull(cloudWatchLogsClient);
System.out.printf("\n Test 1 passed");
}
@Test
@Order(2)
public void CreateAlarm() {
try {
PutMetricAlarm.putMetricAlarm(cw,alarmName,instanceId );
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf("\n Test 2 passed");
}
@Test
@Order(3)
public void DescribeAlarms() {
try {
DescribeAlarms.deleteCWAlarms(cw);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf("\n Test 3 passed");
}
@Test
@Order(4)
public void CreateSubscriptionFilters() {
try {
PutSubscriptionFilter.putSubFilters(cloudWatchLogsClient, filterName, filterPattern, logGroup, roleArn, destinationArn);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf("\n Test 4 passed");
}
@Test
@Order(5)
public void DescribeSubscriptionFilters() {
try {
DescribeSubscriptionFilters.describeFilters(cloudWatchLogsClient,logGroup);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf("\n Test 5 passed");
}
@Test
@Order(6)
public void DisableAlarmActions() {
try {
DisableAlarmActions.disableActions(cw, alarmName);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("\n Test 6 passed");
}
@Test
@Order(7)
public void EnableAlarmActions() {
try {
EnableAlarmActions.enableActions(cw, alarmName) ;
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("\n Test 7 passed");
}
@Test
@Order(8)
public void GetLogEvents() {
try {
GetLogEvents.getCWLogEvebts(cloudWatchLogsClient,logGroup,streamName);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("\n Test 8 passed");
}
@Test
@Order(9)
void PutCloudWatchEvent() {
CloudWatchEventsClient cwe =
CloudWatchEventsClient.builder().build();
try {
PutEvents.putCWEvents(cwe,ruleResource );
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("\n Test 9 passed");
}
@Test
@Order(10)
public void GetMetricData() {
try {
GetMetricData.getMetData(cw);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("\n Test 10 passed");
}
@Test
@Order(11)
public void DeleteSubscriptionFilter() {
try {
DeleteSubscriptionFilter.deleteSubFilter(cloudWatchLogsClient, filterName,logGroup );
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("\n Test 11 passed");
}
@Test
@Order(12)
public void DeleteAlarm() {
try {
DeleteAlarm.deleteCWAlarm(cw, alarmName);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("\n Test 12 passed");
}
}
|
package org.jtrim.concurrent.executor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jtrim.collections.RefCollection;
import org.jtrim.collections.RefLinkedList;
import org.jtrim.collections.RefList;
import org.jtrim.event.*;
import org.jtrim.utils.ExceptionHelper;
import org.jtrim.utils.ObjectFinalizer;
/**
*
* @author Kelemen Attila
*/
public final class ThreadPoolTaskExecutor extends AbstractTaskExecutorService {
private static final Logger LOGGER = Logger.getLogger(ThreadPoolTaskExecutor.class.getName());
private static final long DEFAULT_THREAD_TIMEOUT_MS = 5000;
private final ObjectFinalizer finalizer;
private final String poolName;
private final ListenerManager<Runnable, Void> listeners;
private volatile int maxQueueSize;
private volatile long threadTimeoutNanos;
private volatile int maxThreadCount;
private final Lock mainLock;
// activeWorkers contains workers which may execute tasks and not only
// cleanup tasks.
private final RefList<Worker> activeWorkers;
private final RefList<Worker> runningWorkers;
private final RefList<QueuedItem> queue; // the oldest task is the head of the queue
private final Condition notFullQueueSignal;
private final Condition checkQueueSignal;
private final Condition terminateSignal;
private volatile ExecutorState state;
public ThreadPoolTaskExecutor(String poolName) {
this(poolName, Runtime.getRuntime().availableProcessors());
}
public ThreadPoolTaskExecutor(String poolName, int maxThreadCount) {
this(poolName, maxThreadCount, Integer.MAX_VALUE);
}
public ThreadPoolTaskExecutor(String poolName, int maxThreadCount, int maxQueueSize) {
this(poolName, maxThreadCount, maxQueueSize,
DEFAULT_THREAD_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
public ThreadPoolTaskExecutor(
String poolName,
int maxThreadCount,
int maxQueueSize,
long threadTimeout,
TimeUnit timeUnit) {
ExceptionHelper.checkNotNullArgument(poolName, "poolName");
ExceptionHelper.checkArgumentInRange(maxThreadCount, 1, Integer.MAX_VALUE, "maxThreadCount");
ExceptionHelper.checkArgumentInRange(maxQueueSize, 1, Integer.MAX_VALUE, "maxQueueSize");
ExceptionHelper.checkArgumentInRange(threadTimeout, 0, Long.MAX_VALUE, "threadTimeout");
ExceptionHelper.checkNotNullArgument(timeUnit, "timeUnit");
this.poolName = poolName;
this.listeners = new CopyOnTriggerListenerManager<>();
this.maxThreadCount = maxThreadCount;
this.maxQueueSize = maxQueueSize;
this.threadTimeoutNanos = timeUnit.toNanos(threadTimeout);
this.state = ExecutorState.RUNNING;
this.activeWorkers = new RefLinkedList<>();
this.runningWorkers = new RefLinkedList<>();
this.queue = new RefLinkedList<>();
this.mainLock = new ReentrantLock();
this.notFullQueueSignal = mainLock.newCondition();
this.checkQueueSignal = mainLock.newCondition();
this.terminateSignal = mainLock.newCondition();
this.finalizer = new ObjectFinalizer(new Runnable() {
@Override
public void run() {
doShutdown();
}
}, poolName + " ThreadPoolTaskExecutor shutdown");
}
public void setMaxThreadCount(int maxThreadCount) {
ExceptionHelper.checkArgumentInRange(maxThreadCount, 1, Integer.MAX_VALUE, "maxThreadCount");
this.maxThreadCount = maxThreadCount;
}
public void setMaxQueueSize(int maxQueueSize) {
ExceptionHelper.checkArgumentInRange(maxQueueSize, 1, Integer.MAX_VALUE, "maxQueueSize");
this.maxQueueSize = maxQueueSize;
mainLock.lock();
try {
// Actually it might be full but awaking all the waiting threads
// cause only a performance loss. This performance loss is of
// little consequence becuase we don't expect this method to be
// called that much.
notFullQueueSignal.signalAll();
} finally {
mainLock.unlock();
}
}
public void setThreadTimeout(long threadTimeout, TimeUnit timeUnit) {
ExceptionHelper.checkArgumentInRange(threadTimeout, 0, Long.MAX_VALUE, "threadTimeout");
this.threadTimeoutNanos = timeUnit.toNanos(threadTimeout);
}
@Override
protected void submitTask(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask,
boolean hasUserDefinedCleanup) {
CancellationToken waitQueueCancelToken = hasUserDefinedCleanup
? CancellationSource.UNCANCELABLE_TOKEN
: cancelToken;
QueuedItem newItem = isShutdown()
? new QueuedItem(cleanupTask)
: new QueuedItem(cancelToken, cancelController, task, cleanupTask);
try {
boolean submitted = false;
do {
Worker newWorker = new Worker();
if (newWorker.tryStartWorker(newItem)) {
submitted = true;
}
else {
mainLock.lock();
try {
if (!runningWorkers.isEmpty()) {
if (queue.size() < maxQueueSize) {
queue.addLastGetReference(newItem);
checkQueueSignal.signal();
submitted = true;
}
else {
CancelableWaits.await(waitQueueCancelToken, notFullQueueSignal);
}
}
} finally {
mainLock.unlock();
}
}
} while (!submitted);
} catch (OperationCanceledException ex) {
// Notice that this can only be thrown if there
// is no user defined cleanup task and only when waiting for the
// queue to allow adding more elements.
cleanupTask.run();
}
}
private void doShutdown() {
mainLock.lock();
try {
if (state == ExecutorState.RUNNING) {
state = ExecutorState.SHUTTING_DOWN;
checkQueueSignal.signalAll();
}
} finally {
mainLock.unlock();
tryTerminateAndNotify();
}
}
@Override
public void shutdown() {
finalizer.doFinalize();
}
private void setTerminating() {
mainLock.lock();
try {
if (!isTerminating()) {
state = ExecutorState.TERMINATING;
}
// All the workers must wake up, so that they can detect that
// the executor is shutting down and so must they.
checkQueueSignal.signalAll();
} finally {
mainLock.unlock();
tryTerminateAndNotify();
}
}
private void cancelTasksOfWorkers() {
List<Worker> currentWorkers;
mainLock.lock();
try {
currentWorkers = new ArrayList<>(activeWorkers);
} finally {
mainLock.unlock();
}
Throwable toThrow = null;
for (Worker worker: currentWorkers) {
try {
worker.cancelCurrentTask();
} catch (Throwable ex) {
if (toThrow == null) {
toThrow = ex;
}
else {
toThrow.addSuppressed(ex);
}
}
}
if (toThrow != null) {
ExceptionHelper.rethrow(toThrow);
}
}
@Override
public void shutdownAndCancel() {
// First, stop allowing submitting anymore tasks.
// Also, the current implementation mandates shutdown() to be called
// before this ThreadPoolTaskExecutor becomes unreachable.
shutdown();
setTerminating();
cancelTasksOfWorkers();
}
@Override
public boolean isShutdown() {
return state.getStateIndex() >= ExecutorState.SHUTTING_DOWN.getStateIndex();
}
private boolean isTerminating() {
return state.getStateIndex() >= ExecutorState.TERMINATING.getStateIndex();
}
@Override
public boolean isTerminated() {
return state == ExecutorState.TERMINATED;
}
private void notifyTerminate() {
listeners.onEvent(RunnableDispatcher.INSTANCE, null);
}
@Override
public ListenerRef addTerminateListener(Runnable listener) {
ExceptionHelper.checkNotNullArgument(listener, "listener");
// A quick check for the already terminate case.
if (isTerminated()) {
listener.run();
return UnregisteredListenerRef.INSTANCE;
}
AutoUnregisterListener autoListener = new AutoUnregisterListener(listener);
ListenerRef result = autoListener.registerWith(listeners);
if (isTerminated()) {
autoListener.run();
}
return result;
}
@Override
public boolean awaitTermination(CancellationToken cancelToken, long timeout, TimeUnit unit) {
if (!isTerminated()) {
long startTime = System.nanoTime();
long timeoutNanos = unit.toNanos(startTime);
mainLock.lock();
try {
while (!isTerminated()) {
long elapsed = System.nanoTime() - startTime;
long toWaitNanos = timeoutNanos - elapsed;
if (toWaitNanos <= 0) {
throw new OperationCanceledException();
}
CancelableWaits.await(cancelToken,
toWaitNanos, TimeUnit.NANOSECONDS, terminateSignal);
}
} finally {
mainLock.unlock();
}
}
return true;
}
private void tryTerminateAndNotify() {
if (tryTerminate()) {
notifyTerminate();
}
}
private boolean tryTerminate() {
if (isShutdown() && state != ExecutorState.TERMINATED) {
mainLock.lock();
try {
// This check should be more clever because this way can only
// terminate if even cleanup methods were finished.
if (isShutdown() && activeWorkers.isEmpty()) {
if (state != ExecutorState.TERMINATED) {
state = ExecutorState.TERMINATED;
terminateSignal.signalAll();
return true;
}
}
} finally {
mainLock.unlock();
}
}
return false;
}
private void writeLog(Level level, String prefix, Throwable ex) {
if (LOGGER.isLoggable(level)) {
LOGGER.log(level, prefix + " in the " + poolName
+ " ThreadPoolTaskExecutor", ex);
}
}
private class Worker extends Thread {
private RefCollection.ElementRef<?> activeSelfRef;
private RefCollection.ElementRef<?> selfRef;
private QueuedItem firstTask;
private final AtomicReference<CancellationController> currentControllerRef;
public Worker() {
this.firstTask = null;
this.activeSelfRef = null;
this.selfRef = null;
this.currentControllerRef = new AtomicReference<>(null);
}
public boolean tryStartWorker(QueuedItem firstTask) {
mainLock.lock();
try {
if (firstTask == null && queue.isEmpty()) {
return false;
}
if (runningWorkers.size() >= maxThreadCount) {
return false;
}
if (!isTerminated()) {
activeSelfRef = activeWorkers.addLastGetReference(this);
}
selfRef = runningWorkers.addLastGetReference(this);
} finally {
mainLock.unlock();
}
this.firstTask = firstTask;
start();
return true;
}
public void cancelCurrentTask() {
CancellationController currentController = currentControllerRef.get();
if (currentController != null) {
currentController.cancel();
}
}
private void executeTask(QueuedItem item) {
assert Thread.currentThread() == this;
currentControllerRef.set(item.cancelController);
try {
if (!isTerminating()) {
if (!item.cancelToken.isCanceled()) {
item.task.execute(item.cancelToken);
}
}
else {
if (activeSelfRef != null) {
mainLock.lock();
try {
activeSelfRef.remove();
} finally {
mainLock.unlock();
}
activeSelfRef = null;
}
tryTerminateAndNotify();
}
} finally {
currentControllerRef.set(null);
item.cleanupTask.run();
}
}
private void restartIfNeeded() {
Worker newWorker = null;
mainLock.lock();
try {
if (!queue.isEmpty()) {
newWorker = new Worker();
}
} finally {
mainLock.unlock();
}
if (newWorker != null) {
newWorker.tryStartWorker(null);
}
}
private void finishWorking() {
mainLock.lock();
try {
if (activeSelfRef != null) {
activeSelfRef.remove();
}
selfRef.remove();
} finally {
mainLock.unlock();
}
}
private QueuedItem pollFromQueue() {
long startTime = System.nanoTime();
long toWaitNanos = threadTimeoutNanos;
mainLock.lock();
try {
do {
if (!queue.isEmpty()) {
QueuedItem result = queue.remove(0);
notFullQueueSignal.signal();
return result;
}
if (isShutdown()) {
return null;
}
try {
toWaitNanos = checkQueueSignal.awaitNanos(toWaitNanos);
} catch (InterruptedException ex) {
// In this thread, we don't care about interrupts but
// we need to recalculate the allowed waiting time.
toWaitNanos = threadTimeoutNanos - (System.nanoTime() - startTime);
}
} while (toWaitNanos > 0);
} finally {
mainLock.unlock();
}
return null;
}
private void processQueue() {
QueuedItem itemToProcess = pollFromQueue();
while (itemToProcess != null) {
executeTask(itemToProcess);
itemToProcess = pollFromQueue();
}
}
@Override
public void run() {
try {
if (firstTask != null) {
executeTask(firstTask);
firstTask = null;
}
processQueue();
} catch (Throwable ex) {
writeLog(Level.SEVERE, "Unexpected exception", ex);
} finally {
finishWorking();
try {
tryTerminateAndNotify();
} finally {
restartIfNeeded();
}
}
}
}
private static class QueuedItem {
public final CancellationToken cancelToken;
public final CancellationController cancelController;
public final CancelableTask task;
public final Runnable cleanupTask;
public QueuedItem(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask) {
this.cancelToken = cancelToken;
this.cancelController = cancelController;
this.task = task;
this.cleanupTask = cleanupTask;
}
public QueuedItem(Runnable cleanupTask) {
this.cancelToken = CancellationSource.CANCELED_TOKEN;
this.cancelController = DummyCancellationController.INSTANCE;
this.task = DummyCancelableTask.INSTANCE;
this.cleanupTask = cleanupTask;
}
}
public enum DummyCancelableTask implements CancelableTask {
INSTANCE;
@Override
public void execute(CancellationToken cancelToken) {
}
}
public enum DummyCancellationController implements CancellationController {
INSTANCE;
@Override
public void cancel() {
}
}
private enum ExecutorState {
RUNNING(0),
SHUTTING_DOWN(1),
TERMINATING(2), // = tasks are to be canceled
TERMINATED(3);
private final int stateIndex;
private ExecutorState(int stateIndex) {
this.stateIndex = stateIndex;
}
public int getStateIndex() {
return stateIndex;
}
}
private static class AutoUnregisterListener implements Runnable {
private final AtomicReference<Runnable> listener;
private volatile ListenerRef listenerRef;
public AutoUnregisterListener(Runnable listener) {
this.listener = new AtomicReference<>(listener);
this.listenerRef = null;
}
public ListenerRef registerWith(ListenerManager<Runnable, ?> manager) {
ListenerRef currentRef = manager.registerListener(this);
this.listenerRef = currentRef;
if (listener.get() == null) {
this.listenerRef = null;
currentRef.unregister();
}
return currentRef;
}
@Override
public void run() {
Runnable currentListener = listener.getAndSet(null);
ListenerRef currentRef = listenerRef;
if (currentRef != null) {
currentRef.unregister();
}
if (currentListener != null) {
currentListener.run();
}
}
}
private enum RunnableDispatcher implements EventDispatcher<Runnable, Void> {
INSTANCE;
@Override
public void onEvent(Runnable eventListener, Void arg) {
eventListener.run();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package se.kth.karamel.backend.launcher.amazon;
import se.kth.karamel.common.launcher.amazon.InstanceType;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.jclouds.aws.AWSResponseException;
import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
import org.jclouds.aws.ec2.features.AWSSecurityGroupApi;
import org.jclouds.aws.ec2.options.CreateSecurityGroupOptions;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.ec2.domain.BlockDeviceMapping;
import org.jclouds.ec2.domain.KeyPair;
import org.jclouds.ec2.domain.SecurityGroup;
import org.jclouds.ec2.features.SecurityGroupApi;
import org.jclouds.net.domain.IpPermission;
import org.jclouds.net.domain.IpProtocol;
import org.jclouds.rest.AuthorizationException;
import se.kth.karamel.backend.converter.UserClusterDataExtractor;
import se.kth.karamel.backend.launcher.Launcher;
import se.kth.karamel.backend.running.model.ClusterRuntime;
import se.kth.karamel.backend.running.model.GroupRuntime;
import se.kth.karamel.backend.running.model.MachineRuntime;
import se.kth.karamel.common.util.Settings;
import se.kth.karamel.common.exception.KaramelException;
import se.kth.karamel.common.clusterdef.Ec2;
import se.kth.karamel.common.clusterdef.Provider;
import se.kth.karamel.common.clusterdef.json.JsonCluster;
import se.kth.karamel.common.clusterdef.json.JsonGroup;
import se.kth.karamel.common.util.Confs;
import se.kth.karamel.common.util.Ec2Credentials;
import se.kth.karamel.common.util.SshKeyPair;
import se.kth.karamel.common.exception.InvalidEc2CredentialsException;
/**
* @author kamal
*/
public final class Ec2Launcher extends Launcher {
private static final Logger logger = Logger.getLogger(Ec2Launcher.class);
public static boolean TESTING = true;
public final Ec2Context context;
public final SshKeyPair sshKeyPair;
public Ec2Launcher(Ec2Context context, SshKeyPair sshKeyPair) {
this.context = context;
this.sshKeyPair = sshKeyPair;
logger.info(String.format("Access-key='%s'", context.getCredentials().getAccessKey()));
logger.info(String.format("Public-key='%s'", sshKeyPair.getPublicKeyPath()));
logger.info(String.format("Private-key='%s'", sshKeyPair.getPrivateKeyPath()));
}
public static Ec2Context validateCredentials(Ec2Credentials credentials) throws InvalidEc2CredentialsException {
try {
if (credentials.getAccessKey().isEmpty() || credentials.getSecretKey().isEmpty()) {
throw new InvalidEc2CredentialsException("Ec2 credentials empty - not entered yet.");
}
Ec2Context cxt = new Ec2Context(credentials);
SecurityGroupApi securityGroupApi = cxt.getSecurityGroupApi();
securityGroupApi.describeSecurityGroupsInRegion(Settings.AWS_REGION_CODE_DEFAULT);
return cxt;
} catch (AuthorizationException e) {
throw new InvalidEc2CredentialsException(e.getMessage() + " - accountid:" + credentials.getAccessKey(), e);
}
}
public static Ec2Credentials readCredentials(Confs confs) {
String accessKey = System.getenv(Settings.AWS_ACCESSKEY_ENV_VAR);
String secretKey = System.getenv(Settings.AWS_SECRETKEY_ENV_VAR);
if (accessKey == null || accessKey.isEmpty()) {
accessKey = confs.getProperty(Settings.AWS_ACCESSKEY_KEY);
}
if (secretKey == null || secretKey.isEmpty()) {
secretKey = confs.getProperty(Settings.AWS_SECRETKEY_KEY);
}
Ec2Credentials credentials = null;
if (accessKey != null && !accessKey.isEmpty() && secretKey != null && !accessKey.isEmpty()) {
credentials = new Ec2Credentials();
credentials.setAccessKey(accessKey);
credentials.setSecretKey(secretKey);
}
return credentials;
}
@Override
public String forkGroup(JsonCluster definition, ClusterRuntime runtime, String groupName) throws KaramelException {
JsonGroup jg = UserClusterDataExtractor.findGroup(definition, groupName);
Provider provider = UserClusterDataExtractor.getGroupProvider(definition, groupName);
Ec2 ec2 = (Ec2) provider;
Set<String> ports = new HashSet<>();
ports.addAll(Settings.AWS_VM_PORTS_DEFAULT);
String groupId = createSecurityGroup(definition.getName(), jg.getName(), ec2, ports);
return groupId;
}
public String createSecurityGroup(String clusterName, String groupName, Ec2 ec2, Set<String> ports)
throws KaramelException {
String uniqeGroupName = Settings.AWS_UNIQUE_GROUP_NAME(clusterName, groupName);
logger.info(String.format("Creating security group '%s' ...", uniqeGroupName));
if (context == null) {
throw new KaramelException("Register your valid credentials first :-| ");
}
if (sshKeyPair == null) {
throw new KaramelException("Choose your ssh keypair first :-| ");
}
Optional<? extends org.jclouds.ec2.features.SecurityGroupApi> securityGroupExt
= context.getEc2api().getSecurityGroupApiForRegion(ec2.getRegion());
if (securityGroupExt.isPresent()) {
AWSSecurityGroupApi client = (AWSSecurityGroupApi) securityGroupExt.get();
String groupId = null;
if (ec2.getVpc() != null) {
CreateSecurityGroupOptions csgos = CreateSecurityGroupOptions.Builder.vpcId(ec2.getVpc());
groupId = client.createSecurityGroupInRegionAndReturnId(ec2.getRegion(), uniqeGroupName, uniqeGroupName, csgos);
} else {
groupId = client.createSecurityGroupInRegionAndReturnId(ec2.getRegion(), uniqeGroupName, uniqeGroupName);
}
if (!TESTING) {
for (String port : ports) {
Integer p = null;
IpProtocol pr = null;
if (port.contains("/")) {
String[] s = port.split("/");
p = Integer.valueOf(s[0]);
pr = IpProtocol.valueOf(s[1]);
} else {
p = Integer.valueOf(port);
pr = IpProtocol.TCP;
}
client.authorizeSecurityGroupIngressInRegion(ec2.getRegion(),
uniqeGroupName, pr, p, Integer.valueOf(port), "0.0.0.0/0");
logger.info(String.format("Ports became open for '%s'", uniqeGroupName));
}
} else {
IpPermission tcpPerms = IpPermission.builder().ipProtocol(IpProtocol.TCP).
fromPort(0).toPort(65535).cidrBlock("0.0.0.0/0").build();
IpPermission udpPerms = IpPermission.builder().ipProtocol(IpProtocol.UDP).
fromPort(0).toPort(65535).cidrBlock("0.0.0.0/0").build();
ArrayList<IpPermission> perms = Lists.newArrayList(tcpPerms, udpPerms);
client.authorizeSecurityGroupIngressInRegion(ec2.getRegion(), groupId, perms);
logger.info(String.format("Ports became open for '%s'", uniqeGroupName));
}
logger.info(String.format("Security group '%s' was created :)", uniqeGroupName));
return groupId;
}
return null;
}
public void uploadSshPublicKey(String keyPairName, Ec2 ec2, boolean removeOld) throws KaramelException {
if (context == null) {
throw new KaramelException("Register your valid credentials first :-| ");
}
if (sshKeyPair == null) {
throw new KaramelException("Choose your ssh keypair first :-| ");
}
HashSet<String> regions = new HashSet();
if (!regions.contains(ec2.getRegion())) {
Set<KeyPair> keypairs = context.getKeypairApi().describeKeyPairsInRegion(ec2.getRegion(),
new String[]{keyPairName});
if (keypairs.isEmpty()) {
logger.info(String.format("New keypair '%s' is being uploaded to EC2", keyPairName));
context.getKeypairApi().importKeyPairInRegion(ec2.getRegion(), keyPairName, sshKeyPair.getPublicKey());
} else {
if (removeOld) {
logger.info(String.format("Removing the old keypair '%s' and uploading the new one ...", keyPairName));
context.getKeypairApi().deleteKeyPairInRegion(ec2.getRegion(), keyPairName);
context.getKeypairApi().importKeyPairInRegion(ec2.getRegion(), keyPairName, sshKeyPair.getPublicKey());
}
}
regions.add(ec2.getRegion());
}
}
Set<String> keys = new HashSet<>();
@Override
public List<MachineRuntime> forkMachines(JsonCluster definition, ClusterRuntime runtime, String groupName)
throws KaramelException {
Ec2 ec2 = (Ec2) UserClusterDataExtractor.getGroupProvider(definition, groupName);
JsonGroup definedGroup = UserClusterDataExtractor.findGroup(definition, groupName);
GroupRuntime group = UserClusterDataExtractor.findGroup(runtime, groupName);
HashSet<String> gids = new HashSet<>();
gids.add(group.getId());
String keypairname = Settings.AWS_KEYPAIR_NAME(runtime.getName(), ec2.getRegion());
if (!keys.contains(keypairname)) {
uploadSshPublicKey(keypairname, ec2, true);
keys.add(keypairname);
}
int numForked = 0;
final int numMachines = definedGroup.getSize();
List<MachineRuntime> allMachines = new ArrayList<>();
int requestSize = context.getVmBatchSize();
try {
while (numForked < numMachines) {
int forkSize = Math.min(numMachines, requestSize);
List<MachineRuntime> machines = forkMachines(keypairname, group, gids, numForked, forkSize, ec2);
allMachines.addAll(machines);
numForked += forkSize;
}
} catch (KaramelException ex) {
logger.error(
"Didn't get all machines in this node group. Got " + allMachines.size() + "/" + definedGroup.getSize());
}
return allMachines;
}
public List<MachineRuntime> forkMachines(String keyPairName, GroupRuntime mainGroup,
Set<String> securityGroupIds, int startCount, int numberToLaunch, Ec2 ec2) throws KaramelException {
String uniqueGroupName = Settings.AWS_UNIQUE_GROUP_NAME(mainGroup.getCluster().getName(), mainGroup.getName());
List<String> allVmNames = Settings.AWS_UNIQUE_VM_NAMES(mainGroup.getCluster().getName(), mainGroup.getName(),
startCount, numberToLaunch);
logger.info(String.format("Start forking %d machine(s) for '%s' ...", numberToLaunch, uniqueGroupName));
if (context == null) {
throw new KaramelException("Register your valid credentials first :-| ");
}
if (sshKeyPair == null) {
throw new KaramelException("Choose your ssh keypair first :-| ");
}
AWSEC2TemplateOptions options = context.getComputeService().templateOptions().as(AWSEC2TemplateOptions.class);
if (ec2.getPrice() != null) {
options.spotPrice(ec2.getPrice());
}
Confs confs = Confs.loadKaramelConfs();
String prepStorages = confs.getProperty(Settings.PREPARE_STORAGES_KEY);
if (prepStorages != null && prepStorages.equalsIgnoreCase("true")) {
InstanceType instanceType = InstanceType.valueByModel(ec2.getType());
List<BlockDeviceMapping> maps = instanceType.getEphemeralDeviceMappings();
options.blockDeviceMappings(maps);
}
boolean succeed = false;
int tries = 0;
Set<NodeMetadata> successfulNodes = Sets.newLinkedHashSet();
List<String> unforkedVmNames = new ArrayList<>();
List<String> toBeForkedVmNames;
unforkedVmNames.addAll(allVmNames);
Map<NodeMetadata, Throwable> failedNodes = Maps.newHashMap();
int numSuccess = 0, numFailed = 0;
while (!succeed && tries < Settings.AWS_RETRY_MAX) {
long startTime = System.currentTimeMillis();
int requestSize = numberToLaunch - successfulNodes.size();
if (requestSize > Settings.EC2_MAX_FORK_VMS_PER_REQUEST) {
requestSize = Settings.EC2_MAX_FORK_VMS_PER_REQUEST;
toBeForkedVmNames = unforkedVmNames.subList(0, Settings.EC2_MAX_FORK_VMS_PER_REQUEST);
} else {
toBeForkedVmNames = unforkedVmNames;
}
TemplateBuilder template = context.getComputeService().templateBuilder();
options.keyPair(keyPairName);
options.as(AWSEC2TemplateOptions.class).securityGroupIds(securityGroupIds);
options.nodeNames(toBeForkedVmNames);
if (ec2.getSubnet() != null) {
options.as(AWSEC2TemplateOptions.class).subnetId(ec2.getSubnet());
}
template.options(options);
template.os64Bit(true);
template.hardwareId(ec2.getType());
template.imageId(ec2.getRegion() + "/" + ec2.getAmi());
template.locationId(ec2.getRegion());
tries++;
Set<NodeMetadata> succ = new HashSet<>();
try {
logger.info(String.format("Forking %d machine(s) for '%s', so far(succeeded:%d, failed:%d, total:%d)",
requestSize, uniqueGroupName, successfulNodes.size(), failedNodes.size(), numberToLaunch));
succ.addAll(context.getComputeService().createNodesInGroup(uniqueGroupName, requestSize, template.build()));
long finishTime = System.currentTimeMillis();
numSuccess += succ.size();
} catch (RunNodesException ex) {
addSuccessAndLostNodes(ex, succ, failedNodes);
numSuccess += succ.size();
numFailed += failedNodes.size();
} catch (AWSResponseException e) {
if ("InstanceLimitExceeded".equals(e.getError().getCode())) {
throw new KaramelException("It seems your ec2 account has instance limit.. if thats the case either decrease "
+ "size of your cluster or increase the limitation of your account.", e);
} else if ("RequestLimitExceeded".equals(e.getError().getCode())) {
logger.warn("RequestLimitExceeded. Can recover from it by sleeping longer between requests.");
} else if ("InsufficientInstanceCapacity".equals(e.getError().getCode())) {
logger.warn(
"InsufficientInstanceCapacity. Can recover from it, by reducing the number of instances in the request, "
+ "or waiting for additional capacity to become available");
} else {
logger.error(e.getMessage(), e);
}
} catch (IllegalStateException ex) {
logger.error("", ex);
logger.info(String.format("#%d Hurry up EC2!! I want machines for %s, will ask you again in %d ms :@", tries,
uniqueGroupName, Settings.AWS_RETRY_INTERVAL), ex);
}
unforkedVmNames = findLeftVmNames(succ, unforkedVmNames);
successfulNodes.addAll(succ);
sanityCheckSuccessfulNodes(successfulNodes, failedNodes);
if (successfulNodes.size() < numberToLaunch) {
try {
succeed = false;
logger.info(String.format("So far we got %d successful-machine(s) and %d failed-machine(s) out of %d "
+ "original-number for '%s'. Failed nodes will be killed later.", successfulNodes.size(),
failedNodes.size(),
numberToLaunch, uniqueGroupName));
Thread.currentThread().sleep(Settings.AWS_RETRY_INTERVAL);
} catch (InterruptedException ex1) {
logger.error("", ex1);
}
} else {
succeed = true;
logger.info(String.format("Cool!! we got all %d machine(s) for '%s' |;-) we have %d failed-machines to kill "
+ "before we go on..", numberToLaunch, uniqueGroupName, failedNodes.size()));
if (failedNodes.size() > 0) {
cleanupFailedNodes(failedNodes);
}
List<MachineRuntime> machines = new ArrayList<>();
for (NodeMetadata node : successfulNodes) {
if (node != null) {
MachineRuntime machine = new MachineRuntime(mainGroup);
ArrayList<String> privateIps = new ArrayList();
ArrayList<String> publicIps = new ArrayList();
privateIps.addAll(node.getPrivateAddresses());
publicIps.addAll(node.getPublicAddresses());
machine.setMachineType("ec2/" + ec2.getRegion() + "/" + ec2.getType() + "/" + ec2.getAmi() + "/"
+ ec2.getVpc() + "/" + ec2.getPrice());
machine.setVmId(node.getId());
machine.setName(node.getName());
// we check availability of ip addresses in the sanitycheck
machine.setPrivateIp(privateIps.get(0));
machine.setPublicIp(publicIps.get(0));
machine.setSshPort(node.getLoginPort());
machine.setSshUser(ec2.getUsername());
machines.add(machine);
}
}
// Report aggregrate results
// timeTaken (#machines, #batchSize)
// numSuccess, numFailed, numberToLaunch, InstanceType, **RequestLimitExceeded, **InsufficientInstanceCapacity,
// RequestResourceCountExceeded, ResourceCountExceeded, InsufficientAddressCapacity**
// If your requests have been throttled, you'll get the following error: Client.RequestLimitExceeded. For more
//information, see Query API Request Rate.
// http://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#api-request-rate
// InvalidInstanceID.NotFound, InvalidGroup.NotFound -> eventual consistency
// Spot instances: MaxSpotInstanceCountExceeded
// Groups of Spot instances: MaxSpotFleetRequestCountExceeded
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet.html#spot-fleet-limitations
return machines;
}
}
// Report aggregrate results
throw new KaramelException(String.format("Couldn't fork machines for group'%s'", mainGroup.getName()));
}
private void cleanupFailedNodes(Map<NodeMetadata, Throwable> failedNodes) {
if (failedNodes.size() > 0) {
Set<String> lostIds = Sets.newLinkedHashSet();
for (Map.Entry<NodeMetadata, Throwable> lostNode : failedNodes.entrySet()) {
lostIds.add(lostNode.getKey().getId());
}
logger.info(String.format("Destroying failed nodes with ids: %s", lostIds.toString()));
Set<? extends NodeMetadata> destroyedNodes = context.getComputeService().destroyNodesMatching(
Predicates.in(failedNodes.keySet()));
lostIds.clear();
for (NodeMetadata destroyed : destroyedNodes) {
lostIds.add(destroyed.getId());
}
logger.info("Failed nodes destroyed ;)");
}
}
private void sanityCheckSuccessfulNodes(Set<NodeMetadata> successfulNodes,
Map<NodeMetadata, Throwable> lostNodes) {
logger.info(String.format("Sanity check on successful nodes... "));
List<NodeMetadata> tmpNodes = new ArrayList<>();
tmpNodes.addAll(successfulNodes);
successfulNodes.clear();
for (int i = 0; i < tmpNodes.size(); i++) {
NodeMetadata nm = tmpNodes.get(i);
if (nm == null) {
logger.info("for some reason one of the nodes is null, we removed it from the successfull nodes");
} else if (nm.getPublicAddresses() == null || nm.getPublicAddresses().isEmpty()) {
logger.info("Ec2 hasn't assined public-ip address to a node, we remove it from successfull nodes");
lostNodes.put(nm, new KaramelException("No public-ip assigned"));
} else if (nm.getPrivateAddresses() == null || nm.getPrivateAddresses().isEmpty()) {
logger.info("Ec2 hasn't assined private-ip address to a node, we remove it from successfull nodes");
lostNodes.put(nm, new KaramelException("No private-ip assigned"));
} else {
successfulNodes.add(nm);
}
}
}
private void addSuccessAndLostNodes(RunNodesException rnex, Set<NodeMetadata> successfulNodes,
Map<NodeMetadata, Throwable> lostNodes) {
// by ensuring that any nodes in the "NodeErrors" do not get considered
// successful
Set<? extends NodeMetadata> reportedSuccessfulNodes = rnex.getSuccessfulNodes();
Map<? extends NodeMetadata, ? extends Throwable> errorNodesMap = rnex.getNodeErrors();
Set<? extends NodeMetadata> errorNodes = errorNodesMap.keySet();
// "actual" successful nodes are ones that don't appear in the errorNodes
successfulNodes.addAll(Sets.difference(reportedSuccessfulNodes, errorNodes));
lostNodes.putAll(errorNodesMap);
}
private List<String> findLeftVmNames(Set<? extends NodeMetadata> successfulNodes, List<String> vmNames) {
List<String> leftVmNames = new ArrayList<>();
leftVmNames.addAll(vmNames);
int unnamedVms = 0;
for (NodeMetadata nodeMetadata : successfulNodes) {
String nodeName = nodeMetadata.getName();
if (leftVmNames.contains(nodeName)) {
leftVmNames.remove(nodeName);
} else {
unnamedVms++;
}
}
for (int i = 0; i < unnamedVms; i++) {
if (leftVmNames.size() > 0) {
logger.debug(String.format("Taking %s as one of the unnamed vms.", leftVmNames.get(0)));
leftVmNames.remove(0);
}
}
return leftVmNames;
}
@Override
public void cleanup(JsonCluster definition, ClusterRuntime runtime) throws KaramelException {
runtime.resolveFailures();
List<GroupRuntime> groups = runtime.getGroups();
Set<String> allEc2Vms = new HashSet<>();
Set<String> allEc2VmsIds = new HashSet<>();
Map<String, String> groupRegion = new HashMap<>();
for (GroupRuntime group : groups) {
group.getCluster().resolveFailures();
Provider provider = UserClusterDataExtractor.getGroupProvider(definition, group.getName());
if (provider instanceof Ec2) {
for (MachineRuntime machine : group.getMachines()) {
if (machine.getVmId() != null) {
allEc2VmsIds.add(machine.getVmId());
}
}
JsonGroup jg = UserClusterDataExtractor.findGroup(definition, group.getName());
List<String> vmNames = Settings.AWS_UNIQUE_VM_NAMES(group.getCluster().getName(), group.getName(),
1, jg.getSize());
allEc2Vms.addAll(vmNames);
groupRegion.put(group.getName(), ((Ec2) provider).getRegion());
}
}
cleanup(definition.getName(), allEc2VmsIds, allEc2Vms, groupRegion);
}
public void cleanup(String clusterName, Set<String> vmIds, Set<String> vmNames, Map<String, String> groupRegion)
throws KaramelException {
if (context == null) {
throw new KaramelException("Register your valid credentials first :-| ");
}
if (sshKeyPair == null) {
throw new KaramelException("Choose your ssh keypair first :-| ");
}
Set<String> groupNames = new HashSet<>();
for (Map.Entry<String, String> gp : groupRegion.entrySet()) {
groupNames.add(Settings.AWS_UNIQUE_GROUP_NAME(clusterName, gp.getKey()));
}
logger.info(String.format("Killing following machines with names: \n %s \nor inside group names %s \nor with ids: "
+ "%s", vmNames.toString(), groupNames, vmIds));
logger.info(String.format("Killing all machines in groups: %s", groupNames.toString()));
context.getComputeService().destroyNodesMatching(withPredicate(vmIds, vmNames, groupNames));
logger.info(String.format("All machines destroyed in all the security groups. :) "));
for (Map.Entry<String, String> gp : groupRegion.entrySet()) {
String uniqueGroupName = Settings.AWS_UNIQUE_GROUP_NAME(clusterName, gp.getKey());
for (SecurityGroup secgroup : context.getSecurityGroupApi().describeSecurityGroupsInRegion(gp.getValue())) {
if (secgroup.getName().startsWith("jclouds#" + uniqueGroupName) || secgroup.getName().equals(uniqueGroupName)) {
logger.info(String.format("Destroying security group '%s' ...", secgroup.getName()));
boolean retry = false;
int count = 0;
do {
count++;
try {
logger.info(String.format("#%d Destroying security group '%s' ...", count, secgroup.getName()));
((AWSSecurityGroupApi) context.getSecurityGroupApi()).deleteSecurityGroupInRegionById(gp.getValue(),
secgroup.getId());
} catch (IllegalStateException ex) {
Throwable cause = ex.getCause();
if (cause instanceof AWSResponseException) {
AWSResponseException e = (AWSResponseException) cause;
if (e.getError().getCode().equals("InvalidGroup.InUse") || e.getError().getCode().
equals("DependencyViolation")) {
logger.info(String.format("Hurry up EC2!! terminate machines!! '%s', will retry in %d ms :@",
uniqueGroupName, Settings.AWS_RETRY_INTERVAL));
retry = true;
try {
Thread.currentThread().sleep(Settings.AWS_RETRY_INTERVAL);
} catch (InterruptedException ex1) {
logger.error("", ex1);
}
} else {
throw ex;
}
}
}
} while (retry);
logger.info(String.format("The security group '%s' destroyed ^-^", secgroup.getName()));
}
}
}
}
public static Predicate<NodeMetadata> withPredicate(final Set<String> ids, final Set<String> names,
final Set<String> groupNames) {
return new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nodeMetadata) {
String id = nodeMetadata.getId();
String name = nodeMetadata.getName();
String group = nodeMetadata.getGroup();
return ((id != null && ids.contains(id)) || (name != null && names.contains(name)
|| (group != null && groupNames.contains(group))));
}
@Override
public String toString() {
return "machines predicate";
}
};
}
}
|
package com.haulmont.cuba.core.sys;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.chile.core.model.Instance;
import com.haulmont.cuba.core.entity.BaseEntity;
import com.haulmont.cuba.core.entity.SoftDelete;
import com.haulmont.cuba.core.entity.Updatable;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.MetadataProvider;
import com.haulmont.cuba.core.global.View;
import com.haulmont.cuba.core.global.ViewProperty;
import com.haulmont.cuba.core.global.PersistenceHelper;
import com.haulmont.cuba.core.PersistenceProvider;
import com.haulmont.cuba.core.EntityManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.openjpa.persistence.FetchPlan;
import java.util.*;
public class ViewHelper
{
private static Log log = LogFactory.getLog(ViewHelper.class);
public static void setView(FetchPlan fetchPlan, View view) {
if (fetchPlan == null)
throw new IllegalArgumentException("FetchPlan is null");
fetchPlan.clearFetchGroups();
if (view != null) {
fetchPlan.removeFetchGroup(FetchPlan.GROUP_DEFAULT);
processView(view, fetchPlan);
} else {
fetchPlan.addFetchGroup(FetchPlan.GROUP_DEFAULT);
}
}
public static void addView(FetchPlan fetchPlan, View view) {
if (fetchPlan == null)
throw new IllegalArgumentException("FetchPlan is null");
if (view == null)
throw new IllegalArgumentException("View is null");
processView(view, fetchPlan);
}
public static View intersectViews(View first, View second) {
if (first == null)
throw new IllegalArgumentException("View is null");
if (second == null)
throw new IllegalArgumentException("View is null");
View resultView = new View(first.getEntityClass());
Collection<ViewProperty> firstProps = first.getProperties();
for (ViewProperty firstProperty : firstProps) {
if (second.containsProperty(firstProperty.getName())) {
View resultPropView = null;
ViewProperty secondProperty = second.getProperty(firstProperty.getName());
if ((firstProperty.getView() != null) && (secondProperty.getView() != null)) {
resultPropView = intersectViews(firstProperty.getView(), secondProperty.getView());
}
resultView.addProperty(firstProperty.getName(), resultPropView);
}
}
return resultView;
}
private static void processView(View view, FetchPlan fetchPlan) {
if (view.isIncludeSystemProperties()) {
includeSystemProperties(view, fetchPlan);
}
MetaClass metaClass = MetadataProvider.getSession().getClass(view.getEntityClass());
if (metaClass == null)
throw new RuntimeException("View '" + view + "' definition error: metaClass not found for '"
+ view.getEntityClass() + "'");
for (ViewProperty property : view.getProperties()) {
if (property.isLazy())
continue;
MetaProperty metaProperty = metaClass.getProperty(property.getName());
if (metaProperty == null)
throw new RuntimeException("View '" + view + "' definition error: property '"
+ property.getName() + "' not found in entity '" + metaClass + "'");
Class declaringClass = metaProperty.getDeclaringClass();
if (declaringClass != null) {
fetchPlan.addField(declaringClass, property.getName());
if (property.getView() != null) {
processView(property.getView(), fetchPlan);
}
}
}
}
private static void includeSystemProperties(View view, FetchPlan fetchPlan) {
Class<? extends BaseEntity> entityClass = view.getEntityClass();
MetaClass metaClass = MetadataProvider.getSession().getClass(entityClass);
Class<?> declaringClass;
if (BaseEntity.class.isAssignableFrom(entityClass)) {
declaringClass = metaClass.getProperty("createTs").getDeclaringClass();
if (declaringClass != null) {
fetchPlan.addField(declaringClass, "createTs");
fetchPlan.addField(declaringClass, "createdBy");
}
}
if (Updatable.class.isAssignableFrom(entityClass)) {
declaringClass = metaClass.getProperty("updateTs").getDeclaringClass();
if (declaringClass != null) {
fetchPlan.addField(declaringClass, "updateTs");
fetchPlan.addField(declaringClass, "updatedBy");
}
}
if (SoftDelete.class.isAssignableFrom(entityClass)) {
declaringClass = metaClass.getProperty("deleteTs").getDeclaringClass();
if (declaringClass != null) {
fetchPlan.addField(declaringClass, "deleteTs");
fetchPlan.addField(declaringClass, "deletedBy");
}
}
}
public static void fetchInstance(Instance instance, View view) {
if (PersistenceHelper.isDetached(instance))
throw new IllegalArgumentException("Can not fetch detached entity. Merge first.");
__fetchInstance(instance, view, new HashMap<Instance, Set<View>>());
}
private static void __fetchInstance(Instance instance, View view, Map<Instance, Set<View>> visited) {
Set<View> views = visited.get(instance);
if (views == null) {
views = new HashSet<View>();
visited.put(instance, views);
} else if (views.contains(view)) {
return;
}
views.add(view);
log.trace("Fetching instance " + instance);
for (ViewProperty property : view.getProperties()) {
Object value = instance.getValue(property.getName());
View propertyView = property.getView();
if (value != null && propertyView != null) {
if (value instanceof Collection) {
for (Object item : ((Collection) value)) {
if (item instanceof Instance)
__fetchInstance((Instance) item, propertyView, visited);
}
} else if (value instanceof Instance) {
if (PersistenceHelper.isDetached(value)) {
log.trace("Object " + value + " is detached, loading it");
EntityManager em = PersistenceProvider.getEntityManager();
Entity entity = (Entity) value;
value = em.find(entity.getClass(), entity.getId());
if (value == null) {
// the instance is most probably deleted
continue;
}
instance.setValue(property.getName(), value);
}
__fetchInstance((Instance) value, propertyView, visited);
}
}
}
}
public static boolean hasLazyProperties(View view) {
for (ViewProperty property : view.getProperties()) {
if (property.isLazy())
return true;
if (property.getView() != null) {
if (hasLazyProperties(property.getView()))
return true;
}
}
return false;
}
}
|
package com.danikula.android.garden.task;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Process;
import android.os.ResultReceiver;
import android.util.Log;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RequestExecutorService extends Service {
private static final String LOG_TAG = "RequestExecutorService";
private static final String EXTRA_REQUEST = "com.danikula.android.garden.task.ExtraCommand";
private static final String EXTRA_RESULT_RECEIVER = "com.danikula.android.garden.task.ExtraResultReceiver";
private ExecutorService executor = Executors.newFixedThreadPool(5);
private Handler uiThreadHandler;
static void start(Context context, Request request, ResultReceiver callback) {
Intent intent = new Intent(context, RequestExecutorService.class);
intent.putExtra(RequestExecutorService.EXTRA_REQUEST, request);
intent.putExtra(RequestExecutorService.EXTRA_RESULT_RECEIVER, callback);
context.startService(intent);
}
static void stop(Context context) {
Intent intent = new Intent(context, RequestExecutorService.class);
context.stopService(intent);
}
@Override
public void onCreate() {
super.onCreate();
this.uiThreadHandler = new Handler();
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (intent == null) {
Log.e(LOG_TAG, "Intent is null! Skip command...");
return START_NOT_STICKY;
}
if (!intent.hasExtra(EXTRA_REQUEST)) {
Log.e(LOG_TAG, "There is no command in extras");
return START_NOT_STICKY;
}
if (!intent.hasExtra(EXTRA_RESULT_RECEIVER)) {
Log.e(LOG_TAG, "There is no result receiver in extras");
return START_NOT_STICKY;
}
Request command = (Request) intent.getSerializableExtra(EXTRA_REQUEST);
ResultReceiver receiver = intent.getParcelableExtra(EXTRA_RESULT_RECEIVER);
submitTask(command, receiver);
return START_NOT_STICKY;
}
private void submitTask(final Request command, final ResultReceiver receiver) {
executor.submit(new Runnable() {
@Override
public void run() {
runTask(command, receiver);
}
});
}
private void runTask(Request command, ResultReceiver receiver) {
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
command.execute(getApplicationContext(), receiver, uiThreadHandler);
} catch (Throwable e) {
// deliver any uncatched errors to TaskServiceHelper
command.onError(receiver, new RuntimeException(e));
}
}
@Override
public IBinder onBind(Intent intent) {
// not bindable service
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
executor.shutdown();
}
}
|
package com.github.ltsopensource.queue.support;
import com.github.ltsopensource.core.commons.utils.DateUtils;
import com.github.ltsopensource.core.constant.Constants;
import com.github.ltsopensource.core.logger.Logger;
import com.github.ltsopensource.core.logger.LoggerFactory;
import com.github.ltsopensource.core.support.CronExpressionUtils;
import com.github.ltsopensource.core.support.JobUtils;
import com.github.ltsopensource.queue.CronJobQueue;
import com.github.ltsopensource.queue.ExecutableJobQueue;
import com.github.ltsopensource.queue.RepeatJobQueue;
import com.github.ltsopensource.queue.domain.JobPo;
import com.github.ltsopensource.store.jdbc.exception.DupEntryException;
import java.util.Date;
/**
* @author Robert HG (254963746@qq.com) on 4/6/16.
*/
public class NonRelyJobUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(NonRelyJobUtils.class);
public static void addCronJobForInterval(ExecutableJobQueue executableJobQueue,
CronJobQueue cronJobQueue,
int scheduleIntervalMinute,
final JobPo finalJobPo,
Date lastGenerateTime) {
JobPo jobPo = JobUtils.copy(finalJobPo);
String cronExpression = jobPo.getCronExpression();
long endTime = DateUtils.addMinute(lastGenerateTime, scheduleIntervalMinute).getTime();
Date timeAfter = lastGenerateTime;
boolean stop = false;
while (!stop) {
Date nextTriggerTime = CronExpressionUtils.getNextTriggerTime(cronExpression, timeAfter);
if (nextTriggerTime == null) {
stop = true;
} else {
if (nextTriggerTime.getTime() <= endTime) {
jobPo.setTriggerTime(nextTriggerTime.getTime());
jobPo.setJobId(JobUtils.generateJobId());
jobPo.setTaskId(finalJobPo.getTaskId() + "_" + DateUtils.format(nextTriggerTime, "MMdd-HHmmss"));
jobPo.setInternalExtParam(Constants.ONCE, Boolean.TRUE.toString());
try {
executableJobQueue.add(jobPo);
} catch (DupEntryException e) {
LOGGER.warn("Cron Job[taskId={}, taskTrackerNodeGroup={}] Already Exist in ExecutableJobQueue",
jobPo.getTaskId(), jobPo.getTaskTrackerNodeGroup());
}
} else {
stop = true;
}
}
timeAfter = nextTriggerTime;
}
cronJobQueue.updateLastGenerateTriggerTime(finalJobPo.getJobId(), endTime);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Add CronJob {} to {}", jobPo, DateUtils.formatYMD_HMS(new Date(endTime)));
}
}
public static void addRepeatJobForInterval(
ExecutableJobQueue executableJobQueue,
RepeatJobQueue repeatJobQueue,
int scheduleIntervalMinute, final JobPo finalJobPo, Date lastGenerateTime) {
JobPo jobPo = JobUtils.copy(finalJobPo);
long firstTriggerTime = Long.valueOf(jobPo.getInternalExtParam(Constants.FIRST_FIRE_TIME));
Long repeatInterval = jobPo.getRepeatInterval();
Integer repeatCount = jobPo.getRepeatCount();
long endTime = DateUtils.addMinute(lastGenerateTime, scheduleIntervalMinute).getTime();
if (endTime <= firstTriggerTime) {
return;
}
int repeatedCount = Long.valueOf((lastGenerateTime.getTime() - firstTriggerTime) / jobPo.getRepeatInterval()).intValue();
boolean stop = false;
while (!stop) {
Long nextTriggerTime = firstTriggerTime + repeatedCount * repeatInterval;
if (nextTriggerTime <= endTime &&
(repeatCount == -1 || repeatedCount <= repeatCount)) {
jobPo.setTriggerTime(nextTriggerTime);
jobPo.setJobId(JobUtils.generateJobId());
jobPo.setTaskId(finalJobPo.getTaskId() + "_" + DateUtils.format(new Date(nextTriggerTime), "MMdd-HHmmss"));
jobPo.setRepeatedCount(repeatedCount);
jobPo.setInternalExtParam(Constants.ONCE, Boolean.TRUE.toString());
try {
executableJobQueue.add(jobPo);
} catch (DupEntryException e) {
LOGGER.warn("Repeat Job[taskId={}, taskTrackerNodeGroup={}] Already Exist in ExecutableJobQueue",
jobPo.getTaskId(), jobPo.getTaskTrackerNodeGroup());
}
repeatedCount++;
} else {
stop = true;
}
}
repeatJobQueue.updateLastGenerateTriggerTime(finalJobPo.getJobId(), endTime);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Add RepeatJob {} to {}", jobPo, DateUtils.formatYMD_HMS(new Date(endTime)));
}
}
}
|
package com.thaiopensource.relaxng.pattern;
import com.thaiopensource.util.VoidValue;
/**
* Common base class for PossibleAttributeNamesFunction and PossibleStartTagNamesFunction.
* @see PossibleAttributeNamesFunction
* @see PossibleStartTagNamesFunction
*/
abstract class PossibleNamesFunction extends AbstractPatternFunction<VoidValue> {
private final UnionNameClassNormalizer normalizer = new UnionNameClassNormalizer();
NormalizedNameClass applyTo(Pattern p) {
normalizer.setNameClass(new NullNameClass());
p.apply(this);
return normalizer.normalize();
}
void add(NameClass nc) {
normalizer.add(nc);
}
public VoidValue caseAfter(AfterPattern p) {
return p.getOperand1().apply(this);
}
public VoidValue caseBinary(BinaryPattern p) {
p.getOperand1().apply(this);
p.getOperand2().apply(this);
return VoidValue.VOID;
}
public VoidValue caseChoice(ChoicePattern p) {
return caseBinary(p);
}
public VoidValue caseInterleave(InterleavePattern p) {
return caseBinary(p);
}
public VoidValue caseOneOrMore(OneOrMorePattern p) {
return p.getOperand().apply(this);
}
public VoidValue caseOther(Pattern p) {
return VoidValue.VOID;
}
}
|
package se.sics.cooja.mspmote;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Observable;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.ContikiError;
import se.sics.cooja.GUI;
import se.sics.cooja.Mote;
import se.sics.cooja.MoteInterface;
import se.sics.cooja.MoteInterfaceHandler;
import se.sics.cooja.MoteMemory;
import se.sics.cooja.MoteType;
import se.sics.cooja.Simulation;
import se.sics.cooja.Watchpoint;
import se.sics.cooja.WatchpointMote;
import se.sics.cooja.interfaces.IPAddress;
import se.sics.cooja.motes.AbstractEmulatedMote;
import se.sics.cooja.mspmote.interfaces.MspSerial;
import se.sics.cooja.mspmote.interfaces.Msp802154Radio;
import se.sics.cooja.mspmote.plugins.CodeVisualizerSkin;
import se.sics.cooja.mspmote.plugins.MspBreakpoint;
import se.sics.cooja.plugins.Visualizer;
import se.sics.mspsim.cli.CommandContext;
import se.sics.mspsim.cli.CommandHandler;
import se.sics.mspsim.cli.LineListener;
import se.sics.mspsim.cli.LineOutputStream;
import se.sics.mspsim.core.EmulationException;
import se.sics.mspsim.core.MSP430;
import se.sics.mspsim.platform.GenericNode;
import se.sics.mspsim.ui.JFrameWindowManager;
import se.sics.mspsim.util.ComponentRegistry;
import se.sics.mspsim.util.ConfigManager;
import se.sics.mspsim.util.DebugInfo;
import se.sics.mspsim.util.ELF;
import se.sics.mspsim.util.MapEntry;
import se.sics.mspsim.util.MapTable;
import se.sics.mspsim.util.SimpleProfiler;
/**
* @author Fredrik Osterlind
*/
public abstract class MspMote extends AbstractEmulatedMote implements Mote, WatchpointMote {
private static Logger logger = Logger.getLogger(MspMote.class);
private final static int EXECUTE_DURATION_US = 1; /* We always execute in 1 us steps */
{
Visualizer.registerVisualizerSkin(CodeVisualizerSkin.class);
}
private CommandHandler commandHandler;
private MSP430 myCpu = null;
private MspMoteType myMoteType = null;
private MspMoteMemory myMemory = null;
private MoteInterfaceHandler myMoteInterfaceHandler = null;
public ComponentRegistry registry = null;
/* Stack monitoring variables */
private boolean stopNextInstruction = false;
private boolean monitorStackUsage = false;
private int stackPointerLow = Integer.MAX_VALUE;
private int heapStartAddress;
private StackOverflowObservable stackOverflowObservable = new StackOverflowObservable();
public MspMote(MspMoteType moteType, Simulation simulation) {
this.simulation = simulation;
myMoteType = moteType;
/* Schedule us immediately */
requestImmediateWakeup();
}
protected void initMote() {
if (myMoteType != null) {
initEmulator(myMoteType.getContikiFirmwareFile());
myMoteInterfaceHandler = createMoteInterfaceHandler();
/* TODO Setup COOJA-specific window manager */
registry.registerComponent("windowManager", new JFrameWindowManager());
try {
debuggingInfo = ((MspMoteType)getType()).getFirmwareDebugInfo();
} catch (IOException e) {
throw (RuntimeException) new RuntimeException("Error: " + e.getMessage()).initCause(e);
}
}
}
/**
* Abort execution immediately.
* May for example be called by a breakpoint handler.
*/
public void stopNextInstruction() {
stopNextInstruction = true;
getCPU().stop();
}
protected MoteInterfaceHandler createMoteInterfaceHandler() {
return new MoteInterfaceHandler(this, getType().getMoteInterfaceClasses());
}
/**
* @return MSP430 CPU
*/
public MSP430 getCPU() {
return myCpu;
}
public void setCPU(MSP430 cpu) {
myCpu = cpu;
}
public MoteMemory getMemory() {
return myMemory;
}
public void setMemory(MoteMemory memory) {
myMemory = (MspMoteMemory) memory;
}
/* Stack monitoring variables */
public class StackOverflowObservable extends Observable {
public void signalStackOverflow() {
setChanged();
notifyObservers();
}
}
/**
* Enable/disable stack monitoring
*
* @param monitoring Monitoring enabled
*/
public void monitorStack(boolean monitoring) {
this.monitorStackUsage = monitoring;
resetLowestStackPointer();
}
/**
* @return Lowest SP since stack monitoring was enabled
*/
public int getLowestStackPointer() {
return stackPointerLow;
}
/**
* Resets lowest stack pointer variable
*/
public void resetLowestStackPointer() {
stackPointerLow = Integer.MAX_VALUE;
}
/**
* @return Stack overflow observable
*/
public StackOverflowObservable getStackOverflowObservable() {
return stackOverflowObservable;
}
/**
* Prepares CPU, memory and ELF module.
*
* @param fileELF ELF file
* @param cpu MSP430 cpu
* @throws IOException Preparing mote failed
*/
protected void prepareMote(File fileELF, GenericNode node) throws IOException {
this.commandHandler = new CommandHandler(System.out, System.err);
node.setCommandHandler(commandHandler);
ConfigManager config = new ConfigManager();
node.setup(config);
this.myCpu = node.getCPU();
this.myCpu.setMonitorExec(true);
this.myCpu.setTrace(0); /* TODO Enable */
logger.info("Loading firmware from: " + fileELF.getAbsolutePath());
GUI.setProgressMessage("Loading " + fileELF.getName());
node.loadFirmware(((MspMoteType)getType()).getELF());
/* Throw exceptions at bad memory access */
/*myCpu.setThrowIfWarning(true);*/
/* Create mote address memory */
MapTable map = ((MspMoteType)getType()).getELF().getMap();
MapEntry[] allEntries = map.getAllEntries();
myMemory = new MspMoteMemory(this, allEntries, myCpu);
heapStartAddress = map.heapStartAddress;
myCpu.reset();
}
public CommandHandler getCLICommandHandler() {
return commandHandler;
}
/* called when moteID is updated */
public void idUpdated(int newID) {
}
public MoteType getType() {
return myMoteType;
}
public void setType(MoteType type) {
myMoteType = (MspMoteType) type;
}
public MoteInterfaceHandler getInterfaces() {
return myMoteInterfaceHandler;
}
public void setInterfaces(MoteInterfaceHandler moteInterfaceHandler) {
myMoteInterfaceHandler = moteInterfaceHandler;
}
/**
* Initializes emulator by creating CPU, memory and node object.
*
* @param ELFFile ELF file
* @return True if successful
*/
protected abstract boolean initEmulator(File ELFFile);
private boolean booted = false;
public void simTimeChanged(long diff) {
/* Compensates for simulation time changes (without simulation execution) */
lastExecute -= diff;
nextExecute -= diff;
scheduleNextWakeup(nextExecute);
}
private long lastExecute = -1; /* Last time mote executed */
private long nextExecute;
public void execute(long time) {
execute(time, EXECUTE_DURATION_US);
}
public void execute(long t, int duration) {
/* Wait until mote boots */
if (!booted && myMoteInterfaceHandler.getClock().getTime() < 0) {
scheduleNextWakeup(t - myMoteInterfaceHandler.getClock().getTime());
return;
}
booted = true;
if (stopNextInstruction) {
stopNextInstruction = false;
scheduleNextWakeup(t);
throw new RuntimeException("MSPSim requested simulation stop");
}
if (lastExecute < 0) {
/* Always execute one microsecond the first time */
lastExecute = t;
}
if (t < lastExecute) {
throw new RuntimeException("Bad event ordering: " + lastExecute + " < " + t);
}
/* Execute MSPSim-based mote */
/* TODO Try-catch overhead */
try {
nextExecute =
t + duration +
myCpu.stepMicros(t - lastExecute, duration);
lastExecute = t;
} catch (EmulationException e) {
String trace = e.getMessage() + "\n\n" + getStackTrace();
throw (ContikiError)
new ContikiError(trace).initCause(e);
}
/* Schedule wakeup */
if (nextExecute < t) {
throw new RuntimeException(t + ": MSPSim requested early wakeup: " + nextExecute);
}
/*logger.debug(t + ": Schedule next wakeup at " + nextExecute);*/
scheduleNextWakeup(nextExecute);
if (stopNextInstruction) {
stopNextInstruction = false;
throw new RuntimeException("MSPSim requested simulation stop");
}
/* XXX TODO Reimplement stack monitoring using MSPSim internals */
/*if (monitorStackUsage) {
int newStack = cpu.reg[MSP430.SP];
if (newStack < stackPointerLow && newStack > 0) {
stackPointerLow = cpu.reg[MSP430.SP];
// Check if stack is writing in memory
if (stackPointerLow < heapStartAddress) {
stackOverflowObservable.signalStackOverflow();
stopNextInstruction = true;
getSimulation().stopSimulation();
}
}
}*/
}
public String getStackTrace() {
return executeCLICommand("stacktrace");
}
public int executeCLICommand(String cmd, CommandContext context) {
return commandHandler.executeCommand(cmd, context);
}
public String executeCLICommand(String cmd) {
final StringBuilder sb = new StringBuilder();
LineListener ll = new LineListener() {
public void lineRead(String line) {
sb.append(line).append("\n");
}
};
PrintStream po = new PrintStream(new LineOutputStream(ll));
CommandContext c = new CommandContext(commandHandler, null, "", new String[0], 1, null);
c.out = po;
c.err = po;
if (0 != executeCLICommand(cmd, c)) {
sb.append("\nWarning: command failed");
}
return sb.toString();
}
public int getCPUFrequency() {
return myCpu.getDCOFrequency();
}
public int getID() {
return getInterfaces().getMoteID().getMoteID();
}
public boolean setConfigXML(Simulation simulation, Collection<Element> configXML, boolean visAvailable) {
setSimulation(simulation);
if (myMoteInterfaceHandler == null) {
myMoteInterfaceHandler = createMoteInterfaceHandler();
}
try {
debuggingInfo = ((MspMoteType)getType()).getFirmwareDebugInfo();
} catch (IOException e) {
throw (RuntimeException) new RuntimeException("Error: " + e.getMessage()).initCause(e);
}
for (Element element: configXML) {
String name = element.getName();
if (name.equals("motetype_identifier")) {
/* Ignored: handled by simulation */
} else if ("breakpoints".equals(element.getName())) {
setWatchpointConfigXML(element.getChildren(), visAvailable);
} else if (name.equals("interface_config")) {
String intfClass = element.getText().trim();
if (intfClass.equals("se.sics.cooja.mspmote.interfaces.MspIPAddress")) {
intfClass = IPAddress.class.getName();
}
if (intfClass.equals("se.sics.cooja.mspmote.interfaces.ESBLog")) {
intfClass = MspSerial.class.getName();
}
if (intfClass.equals("se.sics.cooja.mspmote.interfaces.SkyByteRadio")) {
intfClass = Msp802154Radio.class.getName();
}
if (intfClass.equals("se.sics.cooja.mspmote.interfaces.SkySerial")) {
intfClass = MspSerial.class.getName();
}
Class<? extends MoteInterface> moteInterfaceClass = simulation.getGUI().tryLoadClass(
this, MoteInterface.class, intfClass);
if (moteInterfaceClass == null) {
logger.fatal("Could not load mote interface class: " + intfClass);
return false;
}
MoteInterface moteInterface = getInterfaces().getInterfaceOfType(moteInterfaceClass);
if (moteInterface == null) {
logger.fatal("Could not find mote interface of class: " + moteInterfaceClass);
return false;
}
moteInterface.setConfigXML(element.getChildren(), visAvailable);
}
}
/* Schedule us immediately */
requestImmediateWakeup();
return true;
}
public Collection<Element> getConfigXML() {
ArrayList<Element> config = new ArrayList<Element>();
Element element;
/* Breakpoints */
element = new Element("breakpoints");
element.addContent(getWatchpointConfigXML());
config.add(element);
// Mote interfaces
for (MoteInterface moteInterface: getInterfaces().getInterfaces()) {
element = new Element("interface_config");
element.setText(moteInterface.getClass().getName());
Collection<Element> interfaceXML = moteInterface.getConfigXML();
if (interfaceXML != null) {
element.addContent(interfaceXML);
config.add(element);
}
}
return config;
}
public String getExecutionDetails() {
return executeCLICommand("stacktrace");
}
public String getPCString() {
int pc = myCpu.getPC();
ELF elf = myCpu.getRegistry().getComponent(ELF.class);
DebugInfo di = elf.getDebugInfo(pc);
/* Following code examples from MSPsim, DebugCommands.java */
if (di == null) {
di = elf.getDebugInfo(pc + 1);
}
if (di == null) {
/* Return PC value */
SimpleProfiler sp = (SimpleProfiler)myCpu.getProfiler();
try {
MapEntry mapEntry = sp.getCallMapEntry(0);
if (mapEntry != null) {
String file = mapEntry.getFile();
if (file != null) {
if (file.indexOf('/') >= 0) {
file = file.substring(file.lastIndexOf('/')+1);
}
}
String name = mapEntry.getName();
return file + ":?:" + name;
}
return String.format("*%02x", pc);
} catch (Exception e) {
return null;
}
}
int lineNo = di.getLine();
String file = di.getFile();
file = file==null?"?":file;
if (file.contains("/")) {
/* strip path */
file = file.substring(file.lastIndexOf('/')+1, file.length());
}
String function = di.getFunction();
function = function==null?"":function;
if (function.contains(":")) {
/* strip arguments */
function = function.substring(0, function.lastIndexOf(':'));
}
if (function.equals("* not available")) {
function = "?";
}
return file + ":" + lineNo + ":" + function;
/*return executeCLICommand("line " + myCpu.getPC());*/
}
/* WatchpointMote */
private ArrayList<WatchpointListener> watchpointListeners = new ArrayList<WatchpointListener>();
private ArrayList<MspBreakpoint> watchpoints = new ArrayList<MspBreakpoint>();
private Hashtable<File, Hashtable<Integer, Integer>> debuggingInfo = null;
public void addWatchpointListener(WatchpointListener listener) {
watchpointListeners.add(listener);
}
public void removeWatchpointListener(WatchpointListener listener) {
watchpointListeners.remove(listener);
}
public WatchpointListener[] getWatchpointListeners() {
return watchpointListeners.toArray(new WatchpointListener[0]);
}
public Watchpoint addBreakpoint(File codeFile, int lineNr, int address) {
MspBreakpoint bp = new MspBreakpoint(this, address, codeFile, new Integer(lineNr));
watchpoints.add(bp);
for (WatchpointListener listener: watchpointListeners) {
listener.watchpointsChanged();
}
return bp;
}
public void removeBreakpoint(Watchpoint watchpoint) {
((MspBreakpoint)watchpoint).unregisterBreakpoint();
watchpoints.remove(watchpoint);
for (WatchpointListener listener: watchpointListeners) {
listener.watchpointsChanged();
}
}
public Watchpoint[] getBreakpoints() {
return watchpoints.toArray(new Watchpoint[0]);
}
public boolean breakpointExists(int address) {
if (address < 0) {
return false;
}
for (Watchpoint watchpoint: watchpoints) {
if (watchpoint.getExecutableAddress() == address) {
return true;
}
}
return false;
}
public boolean breakpointExists(File file, int lineNr) {
for (Watchpoint watchpoint: watchpoints) {
if (watchpoint.getCodeFile() == null) {
continue;
}
if (watchpoint.getCodeFile().compareTo(file) != 0) {
continue;
}
if (watchpoint.getLineNumber() != lineNr) {
continue;
}
return true;
}
return false;
}
public int getExecutableAddressOf(File file, int lineNr) {
if (file == null || lineNr < 0 || debuggingInfo == null) {
return -1;
}
/* Match file */
Hashtable<Integer, Integer> lineTable = debuggingInfo.get(file);
if (lineTable == null) {
for (File f: debuggingInfo.keySet()) {
if (f != null && f.getName().equals(file.getName())) {
lineTable = debuggingInfo.get(f);
break;
}
}
}
if (lineTable == null) {
return -1;
}
/* Match line number */
Integer address = lineTable.get(lineNr);
if (address != null) {
for (Integer l: lineTable.keySet()) {
if (l != null && l.intValue() == lineNr) {
/* Found line address */
return lineTable.get(l);
}
}
}
return -1;
}
private long lastBreakpointCycles = -1;
public void signalBreakpointTrigger(MspBreakpoint b) {
if (lastBreakpointCycles == myCpu.cycles) {
return;
}
lastBreakpointCycles = myCpu.cycles;
if (b.stopsSimulation() && getSimulation().isRunning()) {
/* Stop simulation immediately */
stopNextInstruction();
}
/* Notify listeners */
WatchpointListener[] listeners = getWatchpointListeners();
for (WatchpointListener listener: listeners) {
listener.watchpointTriggered(b);
}
}
public Collection<Element> getWatchpointConfigXML() {
ArrayList<Element> config = new ArrayList<Element>();
Element element;
for (MspBreakpoint breakpoint: watchpoints) {
element = new Element("breakpoint");
element.addContent(breakpoint.getConfigXML());
config.add(element);
}
return config;
}
public boolean setWatchpointConfigXML(Collection<Element> configXML, boolean visAvailable) {
for (Element element : configXML) {
if (element.getName().equals("breakpoint")) {
MspBreakpoint breakpoint = new MspBreakpoint(this);
if (!breakpoint.setConfigXML(element.getChildren(), visAvailable)) {
logger.warn("Could not restore breakpoint: " + breakpoint);
} else {
watchpoints.add(breakpoint);
}
}
}
return true;
}
}
|
// @java.file.header
package org.gridgain.grid.kernal.processors.cache;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.*;
import org.gridgain.grid.dr.*;
import org.gridgain.grid.dr.cache.sender.*;
import org.gridgain.grid.kernal.managers.deployment.*;
import org.gridgain.grid.kernal.processors.cache.distributed.dht.*;
import org.gridgain.grid.kernal.processors.cache.extras.*;
import org.gridgain.grid.kernal.processors.cache.query.*;
import org.gridgain.grid.kernal.processors.dr.*;
import org.gridgain.grid.kernal.processors.ggfs.*;
import org.gridgain.grid.lang.*;
import org.gridgain.grid.logger.*;
import org.gridgain.grid.util.*;
import org.gridgain.grid.util.typedef.*;
import org.gridgain.grid.util.typedef.internal.*;
import org.gridgain.grid.util.lang.*;
import org.gridgain.grid.util.offheap.unsafe.*;
import org.gridgain.grid.util.tostring.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.gridgain.grid.events.GridEventType.*;
import static org.gridgain.grid.cache.GridCacheFlag.*;
import static org.gridgain.grid.cache.GridCachePeekMode.*;
import static org.gridgain.grid.cache.GridCacheTxState.*;
import static org.gridgain.grid.kernal.processors.cache.GridCacheOperation.*;
import static org.gridgain.grid.kernal.processors.dr.GridDrType.*;
/**
* Adapter for cache entry.
*
* @author @java.author
* @version @java.version
*/
@SuppressWarnings({
"NonPrivateFieldAccessedInSynchronizedContext", "TooBroadScope", "FieldAccessedSynchronizedAndUnsynchronized"})
public abstract class GridCacheMapEntry<K, V> implements GridCacheEntryEx<K, V> {
private static final byte IS_REFRESHING_MASK = 0x01;
private static final byte IS_DELETED_MASK = 0x02;
private static final Comparator<GridCacheVersion> ATOMIC_VER_COMPARATOR = new GridCacheAtomicVersionComparator();
private static final int SIZE_OVERHEAD = 87 /*entry*/ + 32 /* version */;
/** Static logger to avoid re-creation. Made static for test purpose. */
protected static final AtomicReference<GridLogger> logRef = new AtomicReference<>();
/** Logger. */
protected static volatile GridLogger log;
/** Cache registry. */
@GridToStringExclude
protected final GridCacheContext<K, V> cctx;
/** Key. */
@GridToStringInclude
protected final K key;
/** Value. */
@GridToStringInclude
protected V val;
/** Start version. */
@GridToStringInclude
protected final long startVer;
/** Version. */
@GridToStringInclude
protected GridCacheVersion ver;
/** Next entry in the linked list. */
@GridToStringExclude
private volatile GridCacheMapEntry<K, V> next0;
/** Next entry in the linked list. */
@GridToStringExclude
private volatile GridCacheMapEntry<K, V> next1;
/** Key hash code. */
@GridToStringInclude
private final int hash;
/** Key bytes. */
@GridToStringExclude
private volatile byte[] keyBytes;
/** Value bytes. */
@GridToStringExclude
protected byte[] valBytes;
/** Off-heap value pointer. */
private long valPtr;
/** Extras */
@GridToStringInclude
private GridCacheEntryExtras<K> extras;
/**
* Flags:
* <ul>
* <li>Refreshing flag - mask {@link #IS_REFRESHING_MASK}</li>
* <li>Deleted flag - mask {@link #IS_DELETED_MASK}</li>
* </ul>
*/
@GridToStringInclude
protected byte flags;
/**
* @param cctx Cache context.
* @param key Cache key.
* @param hash Key hash value.
* @param val Entry value.
* @param next Next entry in the linked list.
* @param ttl Time to live.
* @param hdrId Header id.
*/
protected GridCacheMapEntry(GridCacheContext<K, V> cctx, K key, int hash, V val,
GridCacheMapEntry<K, V> next, long ttl, int hdrId) {
this.key = key;
this.hash = hash;
this.cctx = cctx;
ttlAndExpireTimeExtras(ttl, toExpireTime(ttl));
synchronized (this) {
value(val, null);
}
next(hdrId, next);
ver = cctx.versions().next();
startVer = ver.order();
log = U.logger(cctx.kernalContext(), logRef, this);
}
/** {@inheritDoc} */
@Override public long startVersion() {
return startVer;
}
/**
* Sets entry value. If off-heap value storage is enabled, will serialize value to off-heap.
*
* @param val Value to store.
* @param valBytes Value bytes to store.
*/
protected void value(@Nullable V val, @Nullable byte[] valBytes) {
assert Thread.holdsLock(this);
// In case we deal with GGFS cache, count updated data
if (cctx.cache().isGgfsDataCache() && key() instanceof GridGgfsBlockKey) {
int newSize = valueLength((byte[])val, valBytes != null ? GridCacheValueBytes.marshaled(valBytes) :
GridCacheValueBytes.nil());
int oldSize = valueLength((byte[])this.val, this.val == null ? valueBytesUnlocked() :
GridCacheValueBytes.nil());
int delta = newSize - oldSize;
if (delta != 0 && !cctx.isNear())
cctx.cache().onGgfsDataSizeChanged(delta);
}
if (!isOffHeapValuesOnly()) {
this.val = val;
this.valBytes = isStoreValueBytes() ? valBytes : null;
}
else {
try {
if (cctx.kernalContext().config().isPeerClassLoadingEnabled()) {
if (val != null || valBytes != null) {
if (val == null)
val = cctx.marshaller().unmarshal(valBytes, cctx.deploy().globalLoader());
if (val != null)
cctx.gridDeploy().deploy(val.getClass(), val.getClass().getClassLoader());
}
if (U.p2pLoader(val)) {
cctx.deploy().addDeploymentContext(
new GridDeploymentInfoBean((GridDeploymentInfo)val.getClass().getClassLoader()));
}
}
GridUnsafeMemory mem = cctx.unsafeMemory();
assert mem != null;
if (val != null || valBytes != null) {
boolean valIsByteArr = val != null && val instanceof byte[];
if (valBytes == null && !valIsByteArr)
valBytes = CU.marshal(cctx, val);
valPtr = mem.putOffHeap(valPtr, valIsByteArr ? (byte[]) val : valBytes, valIsByteArr);
}
else {
mem.removeOffHeap(valPtr);
valPtr = 0;
}
}
catch (GridException e) {
U.error(log, "Failed to deserialize value [entry=" + this + ", val=" + val + ']');
throw new GridRuntimeException(e);
}
}
}
/**
* Isolated method to get length of GGFS block.
*
* @param val Value.
* @param valBytes Value bytes.
* @return Length of value.
*/
private int valueLength(@Nullable byte[] val, GridCacheValueBytes valBytes) {
assert valBytes != null;
return val != null ? val.length : valBytes.isNull() ? 0 : valBytes.get().length - (valBytes.isPlain() ? 0 : 6);
}
/**
* @return Value bytes.
*/
protected GridCacheValueBytes valueBytesUnlocked() {
assert Thread.holdsLock(this);
if (!isOffHeapValuesOnly()) {
if (valBytes != null)
return GridCacheValueBytes.marshaled(valBytes);
}
else {
if (valPtr != 0) {
GridUnsafeMemory mem = cctx.unsafeMemory();
assert mem != null;
return mem.getOffHeap(valPtr);
}
}
return GridCacheValueBytes.nil();
}
/** {@inheritDoc} */
@Override public int memorySize() throws GridException {
byte[] kb;
GridCacheValueBytes vb;
V v;
int extrasSize;
synchronized (this) {
kb = keyBytes;
vb = valueBytesUnlocked();
v = val;
extrasSize = extrasSize();
}
if (kb == null || (vb.isNull() && v != null)) {
if (kb == null)
kb = CU.marshal(cctx, key);
if (vb.isNull())
vb = (v != null && v instanceof byte[]) ? GridCacheValueBytes.plain(v) :
GridCacheValueBytes.marshaled(CU.marshal(cctx, v));
synchronized (this) {
if (keyBytes == null)
keyBytes = kb;
// If value didn't change.
if (!isOffHeapValuesOnly() && valBytes == null && val == v)
valBytes = vb.isPlain() ? null : vb.get();
}
}
return SIZE_OVERHEAD + extrasSize + kb.length + (vb.isNull() ? 0 : vb.get().length);
}
/** {@inheritDoc} */
@Override public boolean isInternal() {
return key instanceof GridCacheInternal;
}
/** {@inheritDoc} */
@Override public boolean isDht() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isLocal() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isNear() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isReplicated() {
return false;
}
/** {@inheritDoc} */
@Override public boolean detached() {
return false;
}
/** {@inheritDoc} */
@Override public GridCacheContext<K, V> context() {
return cctx;
}
/** {@inheritDoc} */
@Override public boolean isNew() throws GridCacheEntryRemovedException {
assert Thread.holdsLock(this);
checkObsolete();
return isStartVersion();
}
/** {@inheritDoc} */
@Override public synchronized boolean isNewLocked() throws GridCacheEntryRemovedException {
checkObsolete();
return isStartVersion();
}
/**
* @return {@code True} if start version.
*/
protected boolean isStartVersion() {
return ver.nodeOrder() == cctx.localNode().order() && ver.order() == startVer;
}
/** {@inheritDoc} */
@Override public boolean valid(long topVer) {
return true;
}
/** {@inheritDoc} */
@Override public int partition() {
return 0;
}
/** {@inheritDoc} */
@Override public boolean partitionValid() {
return true;
}
/** {@inheritDoc} */
@Nullable @Override public GridCacheEntryInfo<K, V> info() {
GridCacheEntryInfo<K, V> info = null;
long time = U.currentTimeMillis();
try {
synchronized (this) {
if (!obsolete()) {
info = new GridCacheEntryInfo<>();
info.key(key);
long expireTime = expireTimeExtras();
boolean expired = expireTime != 0 && expireTime <= time;
info.keyBytes(keyBytes);
info.ttl(ttlExtras());
info.expireTime(expireTime);
info.version(ver);
info.setNew(isStartVersion());
info.setDeleted(deletedUnlocked());
if (!expired) {
info.value(cctx.kernalContext().config().isPeerClassLoadingEnabled() ?
rawGetOrUnmarshalUnlocked() : val);
GridCacheValueBytes valBytes = valueBytesUnlocked();
if (!valBytes.isNull()) {
if (valBytes.isPlain())
info.value((V)valBytes.get());
else
info.valueBytes(valBytes.get());
}
}
}
}
}
catch (GridException e) {
throw new GridRuntimeException("Failed to unmarshal object while creating entry info: " + this, e);
}
return info;
}
/**
* Unswaps an entry.
*
* @throws GridException If failed.
*/
@Override public V unswap() throws GridException {
return unswap(false);
}
/**
* Unswaps an entry.
*
* @param ignoreFlags Whether to ignore swap flags.
* @throws GridException If failed.
*/
@Override public V unswap(boolean ignoreFlags) throws GridException {
boolean swapEnabled = cctx.swap().swapEnabled() && (ignoreFlags || !cctx.hasFlag(SKIP_SWAP));
if (!swapEnabled && !cctx.isOffHeapEnabled())
return null;
synchronized (this) {
if (isStartVersion()) {
GridCacheSwapEntry<V> e = cctx.swap().readAndRemove(this);
if (log.isDebugEnabled())
log.debug("Read swap entry [swapEntry=" + e + ", cacheEntry=" + this + ']');
// If there is a value.
if (e != null) {
long delta = e.expireTime() == 0 ? 0 : e.expireTime() - U.currentTimeMillis();
if (delta >= 0) {
// Set unswapped value.
update(e.value(), e.valueBytes(), e.expireTime(), e.ttl(), e.version());
return e.value();
}
else
clearIndex(e.value());
}
}
}
return null;
}
/**
* @throws GridException If failed.
*/
private void swap() throws GridException {
if (cctx.isSwapOrOffheapEnabled() && !deletedUnlocked()) {
assert Thread.holdsLock(this);
long expireTime = expireTimeExtras();
if (expireTime > 0 && U.currentTimeMillis() >= expireTime)
// Don't swap entry if it's expired.
return;
V val = rawGetOrUnmarshalUnlocked();
GridCacheValueBytes valBytes = valueBytesUnlocked();
if (valBytes.isNull())
valBytes = createValueBytes(val);
GridUuid valClsLdrId = null;
if (val != null)
valClsLdrId = cctx.deploy().getClassLoaderId(val.getClass().getClassLoader());
cctx.swap().write(key(), getOrMarshalKeyBytes(), hash, valBytes.get(), valBytes.isPlain(), ver,
ttlExtras(), expireTime, cctx.deploy().getClassLoaderId(U.detectObjectClassLoader(key)), valClsLdrId);
if (log.isDebugEnabled())
log.debug("Wrote swap entry: " + this);
}
}
/**
* @throws GridException If failed.
*/
protected final void releaseSwap() throws GridException {
if (cctx.isSwapOrOffheapEnabled()) {
synchronized (this){
cctx.swap().remove(key(), getOrMarshalKeyBytes());
}
if (log.isDebugEnabled())
log.debug("Removed swap entry [entry=" + this + ']');
}
}
/**
* @param key Key.
* @param matchVer Version to match.
*/
protected void refreshAhead(final K key, final GridCacheVersion matchVer) {
if (log.isDebugEnabled())
log.debug("Scheduling asynchronous refresh for entry: " + this);
// Asynchronous execution (we don't check filter here).
cctx.closures().runLocalSafe(new GPR() {
@SuppressWarnings({"unchecked"})
@Override public void run() {
if (log.isDebugEnabled())
log.debug("Refreshing-ahead entry: " + GridCacheMapEntry.this);
synchronized (GridCacheMapEntry.this){
// If there is a point to refresh.
if (!matchVer.equals(ver)) {
refreshingLocked(false);
if (log.isDebugEnabled())
log.debug("Will not refresh value as entry has been recently updated: " +
GridCacheMapEntry.this);
return;
}
}
V val = null;
try {
val = cctx.store().loadFromStore(null, key);
}
catch (GridException e) {
U.error(log, "Failed to refresh-ahead entry: " + GridCacheMapEntry.this, e);
}
finally {
synchronized (GridCacheMapEntry.this) {
refreshingLocked(false);
// If version matched, set value. Note that we don't update
// swap here, as asynchronous refresh happens only if
// value is already in memory.
if (val != null && matchVer.equals(ver)) {
try {
V prev = rawGetOrUnmarshalUnlocked();
long ttl = ttlExtras();
long expTime = toExpireTime(ttl);
updateIndex(val, null, expTime, ver, prev);
// Don't change version for read-through.
update(val, null, expTime, ttl, ver);
}
catch (GridException e) {
U.error(log, "Failed to update cache index: " + GridCacheMapEntry.this, e);
}
}
}
}
}
}, true);
}
/**
* @param tx Transaction.
* @param key Key.
* @param reload flag.
* @param filter Filter.
* @return Read value.
* @throws GridException If failed.
*/
@SuppressWarnings({"RedundantTypeArguments"})
@Nullable protected V readThrough(@Nullable GridCacheTxEx<K, V> tx, K key, boolean reload,
GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
// NOTE: Do not remove explicit cast as it breaks ANT builds.
return cctx.store().loadFromStore(tx, key);
}
/** {@inheritDoc} */
@Nullable @Override public final V innerGet(@Nullable GridCacheTxEx<K, V> tx, boolean readSwap,
boolean readThrough, boolean failFast, boolean unmarshal, boolean updateMetrics, boolean evt,
GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException, GridCacheEntryRemovedException,
GridCacheFilterFailedException {
cctx.denyOnFlag(LOCAL);
return innerGet0(tx, readSwap, readThrough, evt, failFast, unmarshal, updateMetrics, filter);
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked", "RedundantTypeArguments", "TooBroadScope"})
private V innerGet0(GridCacheTxEx<K, V> tx, boolean readSwap, boolean readThrough, boolean evt, boolean failFast,
boolean unmarshal, boolean updateMetrics, GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridException, GridCacheEntryRemovedException, GridCacheFilterFailedException {
// Disable read-through if there is no store.
if (readThrough && !cctx.isStoreEnabled())
readThrough = false;
GridCacheMvccCandidate<K> owner;
V old;
V ret = null;
if (!F.isEmpty(filter) && !cctx.isAll(
(new GridCacheFilterEvaluationEntry<>(key, rawGetOrUnmarshal(), this, true)), filter))
return CU.<V>failed(failFast);
boolean asyncRefresh = false;
GridCacheVersion startVer;
boolean expired = false;
V expiredVal = null;
boolean hasOldBytes;
synchronized (this) {
checkObsolete();
// Cache version for optimistic check.
startVer = ver;
GridCacheMvcc<K> mvcc = mvccExtras();
owner = mvcc == null ? null : mvcc.anyOwner();
double delta = Double.MAX_VALUE;
long expireTime = expireTimeExtras();
if (expireTime > 0) {
delta = expireTime - U.currentTimeMillis();
if (log.isDebugEnabled())
log.debug("Checked expiration time for entry [timeLeft=" + delta + ", entry=" + this + ']');
if (delta <= 0)
expired = true;
}
V val = this.val;
hasOldBytes = valBytes != null || valPtr != 0;
if ((unmarshal || isOffHeapValuesOnly()) && !expired && val == null && hasOldBytes)
val = rawGetOrUnmarshalUnlocked();
// Attempt to load from swap.
if (val == null && !hasOldBytes && readSwap) {
// Only promote when loading initial state.
if (isNew()) {
// If this entry is already expired (expiration time was too low),
// we simply remove from swap and clear index.
if (expired) {
releaseSwap();
// Previous value is guaranteed to be null
clearIndex(null);
}
else {
// Read and remove swap entry.
val = unswap();
// Recalculate expiration after swap read.
if (expireTime > 0) {
delta = expireTime - U.currentTimeMillis();
if (log.isDebugEnabled())
log.debug("Checked expiration time for entry [timeLeft=" + delta +
", entry=" + this + ']');
if (delta <= 0)
expired = true;
}
}
}
}
// Only calculate asynchronous refresh-ahead, if there is no other
// one in progress and if not expired.
if (delta > 0 && expireTime > 0 && !refreshingUnlocked()) {
double refreshRatio = cctx.config().getRefreshAheadRatio();
if (1 - delta / ttlExtras() >= refreshRatio)
asyncRefresh = true;
}
boolean valid = valid(tx != null ? tx.topologyVersion() : -1);
old = expired || !valid ? null : val;
if (expired) {
expiredVal = val;
value(null, null);
}
if (old == null && !hasOldBytes) {
asyncRefresh = false;
if (updateMetrics)
cctx.cache().metrics0().onRead(false);
}
else {
if (updateMetrics)
cctx.cache().metrics0().onRead(true);
// Set retVal here for event notification.
ret = old;
// Mark this entry as refreshing, so other threads won't schedule
// asynchronous refresh while this one is in progress.
if (asyncRefresh || readThrough)
refreshingLocked(true);
}
if (evt && expired && cctx.events().isRecordable(EVT_CACHE_OBJECT_EXPIRED)) {
cctx.events().addEvent(partition(), key, tx, owner, EVT_CACHE_OBJECT_EXPIRED, null, false, expiredVal,
expiredVal != null || hasOldBytes);
// No more notifications.
evt = false;
}
if (evt && !expired && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) {
cctx.events().addEvent(partition(), key, tx, owner, EVT_CACHE_OBJECT_READ, ret, ret != null, old,
hasOldBytes || old != null);
// No more notifications.
evt = false;
}
}
if (asyncRefresh && !readThrough && cctx.isStoreEnabled()) {
assert ret != null;
refreshAhead(key, startVer);
}
// Check before load.
if (!cctx.isAll(this, filter))
return CU.<V>failed(failFast, ret);
if (ret != null) {
// If return value is consistent, then done.
if (F.isEmpty(filter) || version().equals(startVer))
return ret;
// Try again (recursion).
return innerGet0(tx, readSwap, readThrough, false, failFast, unmarshal, updateMetrics, filter);
}
boolean loadedFromStore = false;
if (ret == null && readThrough) {
GridCacheTxEx tx0 = null;
if (tx != null && tx.local()) {
if (cctx.isReplicated() || cctx.isColocated() || tx.near())
tx0 = tx;
else if (tx.dht()) {
GridCacheVersion ver = ((GridDhtTxLocalAdapter)tx).nearXidVersion();
tx0 = cctx.dht().near().context().tm().tx(ver);
}
}
ret = readThrough(tx0, key, false, filter);
loadedFromStore = true;
}
boolean match = false;
synchronized (this) {
long ttl = ttlExtras();
// If version matched, set value.
if (startVer.equals(ver)) {
match = true;
if (ret != null) {
GridCacheVersion nextVer = nextVersion();
V prevVal = rawGetOrUnmarshalUnlocked();
long expTime = toExpireTime(ttl);
if (loadedFromStore) {
// Update indexes before actual write to entry.
if (ret != null)
updateIndex(ret, null, expTime, nextVer, prevVal);
else
clearIndex(prevVal);
}
// Don't change version for read-through.
update(ret, null, expTime, ttl, nextVer);
if (cctx.deferredDelete() && deletedUnlocked() && !isInternal() && !detached())
deletedUnlocked(false);
}
if (evt && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ))
cctx.events().addEvent(partition(), key, tx, owner, EVT_CACHE_OBJECT_READ, ret, ret != null,
old, hasOldBytes);
}
}
if (F.isEmpty(filter) || match)
return ret;
// Try again (recursion).
return innerGet0(tx, readSwap, readThrough, false, failFast, unmarshal, updateMetrics, filter);
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked", "TooBroadScope"})
@Nullable @Override public final V innerReload(GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridException, GridCacheEntryRemovedException {
cctx.denyOnFlag(GridCacheFlag.READ);
CU.checkStore(cctx);
GridCacheVersion startVer;
boolean wasNew;
synchronized (this) {
checkObsolete();
// Cache version for optimistic check.
startVer = ver;
wasNew = isNew();
}
// Check before load.
if (cctx.isAll(this, filter)) {
// TODO Read through will change version for near cache.
V ret = readThrough(null, key, true, filter);
boolean touch = false;
try {
synchronized (this) {
long ttl = ttlExtras();
// Generate new version.
GridCacheVersion nextVer = nextVersion();
// If entry was loaded during read step.
if (wasNew && !isNew())
// Map size was updated on entry creation.
return ret;
// If version matched, set value.
if (startVer.equals(ver)) {
releaseSwap();
V old = rawGetOrUnmarshalUnlocked();
long expTime = toExpireTime(ttl);
// Update indexes.
if (ret != null) {
updateIndex(ret, null, expTime, nextVer, old);
if (cctx.deferredDelete() && !isInternal() && !detached() && deletedUnlocked())
deletedUnlocked(false);
}
else {
clearIndex(old);
if (cctx.deferredDelete() && !isInternal() && !detached() && !deletedUnlocked())
deletedUnlocked(true);
}
update(ret, null, expTime, ttl, nextVer);
touch = true;
// If value was set - return, otherwise try again.
return ret;
}
}
if (F.isEmpty(filter)) {
touch = true;
return ret;
}
}
finally {
if (touch)
cctx.evicts().touch(this);
}
// Recursion.
return innerReload(filter);
}
// If filter didn't pass.
return null;
}
/**
* @param nodeId Node ID.
*/
protected void recordNodeId(UUID nodeId) {
// No-op.
}
/** {@inheritDoc} */
@Override public final GridCacheUpdateTxResult<V> innerSet(
@Nullable GridCacheTxEx<K, V> tx,
UUID evtNodeId,
UUID affNodeId,
V val,
@Nullable byte[] valBytes,
boolean writeThrough,
boolean retval,
long ttl,
boolean evt,
boolean metrics,
GridPredicate<GridCacheEntry<K, V>>[] filter,
GridDrType drType,
long drExpireTime,
@Nullable GridCacheVersion explicitVer
) throws GridException, GridCacheEntryRemovedException {
V old;
boolean valid = valid(tx != null ? tx.topologyVersion() : -1);
// Lock should be held by now.
if (!cctx.isAll(this, filter))
return new GridCacheUpdateTxResult<>(false, null);
final GridCacheVersion newVer;
synchronized (this) {
checkObsolete();
if (cctx.kernalContext().config().isCacheSanityCheckEnabled()) {
if (tx != null && tx.groupLock())
groupLockSanityCheck(tx);
else
assert tx == null || (!tx.local() && tx.onePhaseCommit()) || tx.ownsLock(this) :
"Transaction does not own lock for update [entry=" + this + ", tx=" + tx + ']';
}
// Load and remove from swap if it is new.
boolean startVer = isStartVersion();
if (startVer)
unswap(true);
newVer = explicitVer != null ? explicitVer : tx == null ?
nextVersion() : tx.writeVersion();
assert newVer != null : "Failed to get write version for tx: " + tx;
if (tx != null && !tx.local() && tx.onePhaseCommit() && explicitVer == null) {
if (!isNew() && ver.compareTo(newVer) > 0) {
if (log.isDebugEnabled())
log.debug("Skipping entry update for one-phase commit since current entry version is " +
"greater than write version [entry=" + this + ", newVer=" + newVer + ']');
return new GridCacheUpdateTxResult<>(false, null);
}
}
old = retval ? rawGetOrUnmarshalUnlocked() : this.val;
// Determine new ttl and expire time.
if (ttl < 0)
ttl = ttlExtras();
assert ttl >= 0;
long expireTime = drExpireTime < 0L ? toExpireTime(ttl) : drExpireTime;
// Update index inside synchronization since it can be updated
// in load methods without actually holding entry lock.
if (val != null || valBytes != null) {
updateIndex(val, valBytes, expireTime, newVer, old);
if (cctx.deferredDelete() && deletedUnlocked() && !isInternal() && !detached())
deletedUnlocked(false);
}
update(val, valBytes, expireTime, ttl, newVer);
drReplicate(drType, val, valBytes, newVer);
recordNodeId(affNodeId);
if (metrics)
cctx.cache().metrics0().onWrite();
if (evt && newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_PUT))
cctx.events().addEvent(partition(), key, evtNodeId, tx == null ? null : tx.xid(),
newVer, EVT_CACHE_OBJECT_PUT, val, val != null, old, old != null || hasValueUnlocked());
GridCacheMode mode = cctx.config().getCacheMode();
if (mode == GridCacheMode.LOCAL || mode == GridCacheMode.REPLICATED ||
(tx != null && (tx.dht() || tx.colocated()) && tx.local()))
cctx.continuousQueries().onEntryUpdate(this, key, val, valueBytesUnlocked(), false);
}
if (log.isDebugEnabled())
log.debug("Updated cache entry [val=" + val + ", old=" + old + ", entry=" + this + ']');
// Persist outside of synchronization. The correctness of the
// value will be handled by current transaction.
if (writeThrough)
cctx.store().putToStore(tx, key, val, newVer);
return valid ? new GridCacheUpdateTxResult<>(true, old) : new GridCacheUpdateTxResult<V>(false, null);
}
/** {@inheritDoc} */
@Override public final GridCacheUpdateTxResult<V> innerRemove(
@Nullable GridCacheTxEx<K, V> tx,
UUID evtNodeId,
UUID affNodeId,
boolean writeThrough,
boolean retval,
boolean evt,
boolean metrics,
GridPredicate<GridCacheEntry<K, V>>[] filter,
GridDrType drType,
@Nullable GridCacheVersion explicitVer
) throws GridException, GridCacheEntryRemovedException {
assert cctx.transactional();
V old;
GridCacheVersion newVer;
boolean valid = valid(tx != null ? tx.topologyVersion() : -1);
// Lock should be held by now.
if (!cctx.isAll(this, filter))
return new GridCacheUpdateTxResult<>(false, null);
GridCacheVersion obsoleteVer = null;
GridCacheVersion enqueueVer = null;
try {
synchronized (this) {
checkObsolete();
if (tx != null && tx.groupLock() && cctx.kernalContext().config().isCacheSanityCheckEnabled())
groupLockSanityCheck(tx);
else
assert tx == null || (!tx.local() && tx.onePhaseCommit()) || tx.ownsLock(this) :
"Transaction does not own lock for remove[entry=" + this + ", tx=" + tx + ']';
boolean startVer = isStartVersion();
if (startVer) {
if (tx != null && !tx.local() && tx.onePhaseCommit())
// Must promote to check version for one-phase commit tx.
unswap(true);
else
// Release swap.
releaseSwap();
}
newVer = explicitVer != null ? explicitVer : tx == null ? nextVersion() : tx.writeVersion();
if (tx != null && !tx.local() && tx.onePhaseCommit() && explicitVer == null) {
if (!startVer && ver.compareTo(newVer) > 0) {
if (log.isDebugEnabled())
log.debug("Skipping entry removal for one-phase commit since current entry version is " +
"greater than write version [entry=" + this + ", newVer=" + newVer + ']');
return new GridCacheUpdateTxResult<>(false, null);
}
if (!detached())
enqueueVer = newVer;
}
old = retval ? rawGetOrUnmarshalUnlocked() : val;
if (old == null)
old = saveValueForIndexUnlocked();
// Clear indexes inside of synchronization since indexes
// can be updated without actually holding entry lock.
clearIndex(old);
update(null, null, 0, 0, newVer);
if (cctx.deferredDelete() && !deletedUnlocked() && !detached() && !isInternal()) {
deletedUnlocked(true);
enqueueVer = newVer;
}
drReplicate(drType, null, null, newVer);
if (metrics)
cctx.cache().metrics0().onWrite();
if (tx == null)
obsoleteVer = newVer;
else {
// Only delete entry if the lock is not explicit.
if (tx.groupLock() || lockedBy(tx.xidVersion()))
obsoleteVer = tx.xidVersion();
else if (log.isDebugEnabled())
log.debug("Obsolete version was not set because lock was explicit: " + this);
}
if (evt && newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_REMOVED))
cctx.events().addEvent(partition(), key, evtNodeId, tx == null ? null : tx.xid(), newVer,
EVT_CACHE_OBJECT_REMOVED, null, false, old, old != null || hasValueUnlocked());
GridCacheMode mode = cctx.config().getCacheMode();
if (mode == GridCacheMode.LOCAL || mode == GridCacheMode.REPLICATED ||
(tx != null && (tx.dht() || tx.colocated()) && tx.local()))
cctx.continuousQueries().onEntryUpdate(this, key, null, null, false);
}
}
finally {
if (enqueueVer != null) {
assert cctx.deferredDelete();
cctx.onDeferredDelete(this, enqueueVer);
}
}
// Persist outside of synchronization. The correctness of the
// value will be handled by current transaction.
if (writeThrough)
cctx.store().removeFromStore(tx, key);
if (!cctx.deferredDelete()) {
synchronized (this) {
// If entry is still removed.
if (newVer == ver) {
if (obsoleteVer == null || !markObsolete(obsoleteVer)) {
if (log.isDebugEnabled())
log.debug("Entry could not be marked obsolete (it is still used): " + this);
}
else {
recordNodeId(affNodeId);
// If entry was not marked obsolete, then removed lock
// will be registered whenever removeLock is called.
cctx.mvcc().addRemoved(obsoleteVer);
if (log.isDebugEnabled())
log.debug("Entry was marked obsolete: " + this);
}
}
}
}
return valid ? new GridCacheUpdateTxResult<>(true, old) : new GridCacheUpdateTxResult<V>(false, null);
}
/** {@inheritDoc} */
@Override public GridCacheUpdateAtomicResult<K, V> innerUpdate(
GridCacheVersion newVer,
UUID evtNodeId,
UUID affNodeId,
GridCacheOperation op,
@Nullable Object writeObj,
@Nullable byte[] valBytes,
boolean writeThrough,
boolean retval,
long ttl,
boolean evt,
boolean metrics,
boolean primary,
boolean verCheck,
@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter,
GridDrType drType,
long drTtl,
long drExpireTime,
@Nullable GridCacheVersion drVer,
boolean drResolve
) throws GridException, GridCacheEntryRemovedException, GridClosureException {
assert cctx.atomic();
V old;
boolean res = true;
V updated;
GridCacheVersion enqueueVer = null;
GridDrReceiverConflictContextImpl<K, V> drRes = null;
long newTtl = 0L;
long newExpireTime = 0L;
long newDrExpireTime = -1L; // Explicit DR expire time which possibly will be sent to DHT node.
synchronized (this) {
boolean needVal = retval || op == GridCacheOperation.TRANSFORM || !F.isEmpty(filter);
checkObsolete();
// Load and remove from swap if it is new.
if (isNew())
unswap(true);
boolean newTtlResolved = false;
boolean drNeedResolve = false;
if (drResolve) {
GridCacheVersion oldDrVer = version().drVersion();
drNeedResolve = cctx.drNeedResolve(oldDrVer, drVer);
if (drNeedResolve) {
// Get old value.
V oldVal = rawGetOrUnmarshalUnlocked();
if (writeObj == null && valBytes != null)
writeObj = cctx.marshaller().unmarshal(valBytes, cctx.deploy().globalLoader());
if (op == TRANSFORM)
writeObj = ((GridClosure<V, V>)writeObj).apply(oldVal);
K k = key();
if (drTtl >= 0L) {
// DR TTL is set explicitly
assert drExpireTime >= 0L;
newTtl = drTtl;
newExpireTime = drExpireTime;
}
else {
newTtl = ttl < 0 ? ttlExtras() : ttl;
newExpireTime = CU.toExpireTime(newTtl);
}
newTtlResolved = true;
GridDrEntry<K, V> oldEntry = drEntry();
GridDrEntry<K, V> newEntry = new GridDrPlainEntry<>(k, (V)writeObj, newTtl, newExpireTime,
drVer);
drRes = cctx.drResolveConflict(k, oldEntry, newEntry);
assert drRes != null;
if (drRes.isUseOld()) {
old = retval ? rawGetOrUnmarshalUnlocked() : val;
return new GridCacheUpdateAtomicResult<>(false, old, null, 0L, -1L, null, null, false);
}
else if (drRes.isUseNew())
op = writeObj != null ? UPDATE : DELETE;
else {
assert drRes.isMerge();
writeObj = drRes.mergeValue();
valBytes = null;
drVer = null; // Update will be considered as local.
op = writeObj != null ? UPDATE : DELETE;
}
newTtl = drRes.ttl();
newExpireTime = drRes.expireTime();
// Explicit DR expire time will be passed to remote node only in that case.
if (!drRes.explicitTtl() && !drRes.isMerge()) {
if (drRes.isUseNew() && newEntry.dataCenterId() != cctx.gridConfig().getDataCenterId() ||
drRes.isUseOld() && oldEntry.dataCenterId() != cctx.gridConfig().getDataCenterId())
newDrExpireTime = drRes.expireTime();
}
}
else
// Nullify DR version on this update, so that we will use regular version during next updates.
drVer = null;
}
if (!drNeedResolve) { // Perform version check only in case there will be no explicit conflict resolution.
if (verCheck) {
if (!isNew() && ATOMIC_VER_COMPARATOR.compare(ver, newVer) > 0) {
if (log.isDebugEnabled())
log.debug("Received entry update for with smaller version than current (will ignore) " +
"[entry=" + this + ", newVer=" + newVer + ']');
old = retval ? rawGetOrUnmarshalUnlocked() : val;
return new GridCacheUpdateAtomicResult<>(false, old, null, 0L, -1L, null, null, false);
}
}
else
assert isNew() || ATOMIC_VER_COMPARATOR.compare(ver, newVer) <= 0 :
"Invalid version for inner update [entry=" + this + ", newVer=" + newVer + ']';
}
if (!newTtlResolved) {
// Calculate TTL and expire time for local update.
if (drTtl >= 0L) {
assert drExpireTime >= 0L;
newTtl = drTtl;
newExpireTime = drExpireTime;
}
else {
assert drExpireTime == -1L;
newTtl = ttl;
if (newTtl < 0)
newTtl = ttlExtras();
newExpireTime = toExpireTime(newTtl);
}
}
// Possibly get old value form store.
old = needVal ? rawGetOrUnmarshalUnlocked() : val;
if (needVal && old == null) {
old = readThrough(null, key, false, CU.<K, V>empty());
update(old, null, 0, 0, ver);
if (deletedUnlocked() && old != null)
deletedUnlocked(false);
}
// Check filter inside of synchronization.
if (!F.isEmpty(filter)) {
boolean pass = cctx.isAll(wrapFilterLocked(), filter);
if (!pass)
return new GridCacheUpdateAtomicResult<>(false, old, null, 0L, -1L, null, null, false);
}
// Apply metrics.
if (metrics && needVal)
cctx.cache().metrics0().onRead(old != null);
// Calculate new value.
if (op == GridCacheOperation.TRANSFORM) {
GridClosure<V, V> transform = (GridClosure<V, V>) writeObj;
updated = transform.apply(old);
valBytes = null;
}
else
updated = (V) writeObj;
op = updated == null ? GridCacheOperation.DELETE : GridCacheOperation.UPDATE;
assert op == GridCacheOperation.UPDATE || (op == GridCacheOperation.DELETE && updated == null);
boolean hadVal = hasValueUnlocked();
// Incorporate DR version into new version if needed.
if (drVer != null && drVer != newVer)
newVer = new GridCacheVersionEx(newVer.topologyVersion(), newVer.globalTime(), newVer.order(),
newVer.nodeOrder(), newVer.dataCenterId(), drVer);
// Try write-through.
if (op == GridCacheOperation.UPDATE) {
if (writeThrough)
// Must persist inside synchronization in non-tx mode.
cctx.store().putToStore(null, key, updated, newVer);
if (!hadVal) {
boolean new0 = isNew();
assert deletedUnlocked() || new0 : "Invalid entry [entry=" + this + ", locNodeId=" +
cctx.localNodeId() + ']';
if (!new0)
deletedUnlocked(false);
}
else {
assert !deletedUnlocked() : "Invalid entry [entry=" + this +
", locNodeId=" + cctx.localNodeId() + ']';
// Do not change size;
}
// Update index inside synchronization since it can be updated
// in load methods without actually holding entry lock.
updateIndex(updated, valBytes, newExpireTime, newVer, old);
update(updated, valBytes, newExpireTime, newTtl, newVer);
drReplicate(drType, updated, valBytes, newVer);
if (evt && newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_PUT))
cctx.events().addEvent(partition(), key, evtNodeId, null,
newVer, EVT_CACHE_OBJECT_PUT, updated, updated != null, old,
old != null || hadVal);
}
else {
if (writeThrough)
// Must persist inside synchronization in non-tx mode.
cctx.store().removeFromStore(null, key);
// Update index inside synchronization since it can be updated
// in load methods without actually holding entry lock.
clearIndex(old);
if (hadVal) {
assert !deletedUnlocked();
deletedUnlocked(true);
enqueueVer = newVer;
}
else {
boolean new0 = isNew();
assert deletedUnlocked() || new0 : "Invalid entry [entry=" + this + ", locNodeId=" +
cctx.localNodeId() + ']';
if (new0) {
deletedUnlocked(true);
enqueueVer = newVer;
}
}
// Clear value on backup. Entry will be removed from cache when it got evicted from queue.
update(null, null, 0, 0, newVer);
drReplicate(drType, null, null, newVer);
if (evt && newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_REMOVED))
cctx.events().addEvent(partition(), key, evtNodeId, null, newVer,
EVT_CACHE_OBJECT_REMOVED, null, false, old, old != null || hadVal);
res = hadVal;
// Do not propagate zeroed TTL and expire time.
newTtl = 0L;
newDrExpireTime = -1L;
}
if (metrics)
cctx.cache().metrics0().onWrite();
if (primary)
cctx.continuousQueries().onEntryUpdate(this, key, val, valueBytesUnlocked(), false);
}
if (log.isDebugEnabled())
log.debug("Updated cache entry [val=" + val + ", old=" + old + ", entry=" + this + ']');
return new GridCacheUpdateAtomicResult<>(res, old, updated, newTtl, newDrExpireTime, enqueueVer, drRes, true);
}
/**
* Perform DR if needed.
*
* @param drType DR type.
* @param val Value.
* @param valBytes Value bytes.
* @param ver Version.
* @throws GridException In case of exception.
*/
private void drReplicate(GridDrType drType, @Nullable V val, @Nullable byte[] valBytes, GridCacheVersion ver)
throws GridException{
if (cctx.isReplicationEnabled() && drType != DR_NONE && !isInternal()) {
GridDrSenderCacheConfiguration drSndCfg = cctx.config().getDrSenderConfiguration();
GridDrSenderCacheEntryFilter<K, V> drFilter = drSndCfg != null ?
(GridDrSenderCacheEntryFilter<K, V>)drSndCfg.getEntryFilter() : null;
GridDrRawEntry<K, V> entry = new GridDrRawEntry<>(key, keyBytes, val, valBytes, rawTtl(), rawExpireTime(),
ver.drVersion());
boolean apply = drFilter == null;
if (!apply) {
// Unmarshall entry and pass it to filter.
entry.unmarshal(cctx.marshaller());
apply = drFilter.accept(entry);
}
if (apply)
cctx.dr().replicate(entry, drType);
else
cctx.cache().metrics0().onSenderCacheEntryFiltered();
}
}
/**
* @return {@code true} if entry has readers. It makes sense only for dht entry.
* @throws GridCacheEntryRemovedException If removed.
*/
protected boolean hasReaders() throws GridCacheEntryRemovedException {
return false;
}
protected void clearReaders() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean clear(GridCacheVersion ver, boolean swap, boolean readers,
@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
cctx.denyOnFlag(GridCacheFlag.READ);
boolean ret;
boolean rmv;
while (true) {
ret = false;
rmv = false;
// For optimistic check.
GridCacheVersion startVer = null;
if (!F.isEmpty(filter)) {
synchronized (this) {
startVer = this.ver;
}
if (!cctx.isAll(this, filter))
return false;
}
synchronized (this) {
if (startVer != null && !startVer.equals(this.ver))
// Version has changed since filter checking.
continue;
V val = saveValueForIndexUnlocked();
try {
if ((!hasReaders() || readers)) {
// markObsolete will clear the value.
if (!markObsolete(ver)) {
if (log.isDebugEnabled())
log.debug("Entry could not be marked obsolete (it is still used): " + this);
break;
}
clearReaders();
}
else {
if (log.isDebugEnabled())
log.debug("Entry could not be marked obsolete (it still has readers): " + this);
break;
}
}
catch (GridCacheEntryRemovedException ignore) {
if (log.isDebugEnabled())
log.debug("Got removed entry when clearing (will simply return): " + this);
ret = true;
break;
}
if (log.isDebugEnabled())
log.debug("Entry has been marked obsolete: " + this);
clearIndex(val);
if (swap) {
releaseSwap();
if (log.isDebugEnabled())
log.debug("Entry has been cleared from swap storage: " + this);
}
ret = true;
rmv = true;
break;
}
}
if (rmv)
cctx.cache().removeEntry(this); // Clear cache.
return ret;
}
/** {@inheritDoc} */
@Override public synchronized GridCacheVersion obsoleteVersion() {
return obsoleteVersionExtras();
}
/** {@inheritDoc} */
@Override public synchronized boolean markObsolete(GridCacheVersion ver) {
GridCacheVersion obsoleteVer = obsoleteVersionExtras();
if (ver != null) {
// If already obsolete, then do nothing.
if (obsoleteVer != null)
return true;
GridCacheMvcc<K> mvcc = mvccExtras();
if (mvcc == null || mvcc.isEmpty(ver)) {
obsoleteVer = ver;
obsoleteVersionExtras(obsoleteVer);
value(null, null);
onMarkedObsolete();
}
return obsoleteVer != null;
}
else
return obsoleteVer != null;
}
/** {@inheritDoc} */
@Override public boolean markObsoleteIfEmpty(@Nullable GridCacheVersion ver) throws GridException {
boolean obsolete = false;
boolean deferred = false;
try {
synchronized (this) {
if (obsoleteVersionExtras() != null)
return false;
if (!hasValueUnlocked() || checkExpired()) {
if (ver == null)
ver = nextVersion();
if (cctx.deferredDelete() && !isStartVersion() && !detached() && !isInternal()) {
if (!deletedUnlocked()) {
update(null, null, 0L, 0L, ver);
deletedUnlocked(true);
deferred = true;
}
}
else
obsolete = markObsolete(ver);
}
}
}
finally {
if (deferred)
cctx.onDeferredDelete(this, ver);
}
return obsolete;
}
/** {@inheritDoc} */
@Override public synchronized boolean markObsoleteVersion(GridCacheVersion ver) {
assert cctx.deferredDelete();
return obsoleteVersionExtras() != null || (this.ver.equals(ver) && markObsolete(ver));
}
/**
* <p>
* Note that {@link #onMarkedObsolete()} should always be called after this method
* returns {@code true}.
*
* @param ver Version.
* @param clear {@code True} to clear.
* @return {@code True} if entry is obsolete, {@code false} if entry is still used by other threads or nodes.
*/
protected final boolean markObsolete0(GridCacheVersion ver, boolean clear) {
assert Thread.holdsLock(this);
GridCacheVersion obsoleteVer = obsoleteVersionExtras();
if (ver != null) {
// If already obsolete, then do nothing.
if (obsoleteVer != null)
return true;
GridCacheMvcc<K> mvcc = mvccExtras();
if (mvcc == null || mvcc.isEmpty(ver)) {
obsoleteVer = ver;
obsoleteVersionExtras(obsoleteVer);
if (clear)
value(null, null);
}
return obsoleteVer != null;
}
else
return obsoleteVer != null;
}
/**
* This method should be called each time entry is marked obsolete
* other than by calling {@link #markObsolete(GridCacheVersion)}.
*/
protected void onMarkedObsolete() {
// No-op.
}
/** {@inheritDoc} */
@Override public final synchronized boolean obsolete() {
return obsoleteVersionExtras() != null;
}
/** {@inheritDoc} */
@Override public final synchronized boolean obsolete(GridCacheVersion exclude) {
GridCacheVersion obsoleteVer = obsoleteVersionExtras();
return obsoleteVer != null && !obsoleteVer.equals(exclude);
}
/** {@inheritDoc} */
@Override public synchronized boolean invalidate(@Nullable GridCacheVersion curVer, GridCacheVersion newVer)
throws GridException {
assert newVer != null;
if (curVer == null || ver.equals(curVer)) {
V val = saveValueForIndexUnlocked();
value(null, null);
ver = newVer;
releaseSwap();
clearIndex(val);
}
return obsoleteVersionExtras() != null;
}
/** {@inheritDoc} */
@Override public boolean invalidate(@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridCacheEntryRemovedException, GridException {
if (F.isEmpty(filter)) {
synchronized (this) {
checkObsolete();
invalidate(null, nextVersion());
return true;
}
}
else {
// For optimistic checking.
GridCacheVersion startVer;
synchronized (this){
checkObsolete();
startVer = ver;
}
if (!cctx.isAll(this, filter))
return false;
synchronized (this) {
checkObsolete();
if (startVer.equals(ver)) {
invalidate(null, nextVersion());
return true;
}
}
// If version has changed then repeat the process.
return invalidate(filter);
}
}
/** {@inheritDoc} */
@Override public boolean compact(@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridCacheEntryRemovedException, GridException {
// For optimistic checking.
GridCacheVersion startVer;
synchronized (this) {
checkObsolete();
startVer = ver;
}
if (!cctx.isAll(this, filter))
return false;
synchronized (this) {
checkObsolete();
if (deletedUnlocked())
return false; // Cannot compact soft-deleted entries.
if (startVer.equals(ver)) {
if (hasValueUnlocked() && !checkExpired()) {
if (!isOffHeapValuesOnly()) {
if (val != null)
valBytes = null;
}
return false;
}
else
return clear(nextVersion(), cctx.isSwapOrOffheapEnabled(), false, filter);
}
}
// If version has changed do it again.
return compact(filter);
}
/**
*
* @param val New value.
* @param valBytes New value bytes.
* @param expireTime Expiration time.
* @param ttl Time to live.
* @param ver Update version.
*/
protected final void update(@Nullable V val, @Nullable byte[] valBytes, long expireTime, long ttl,
GridCacheVersion ver) {
assert ver != null;
assert Thread.holdsLock(this);
long oldExpireTime = expireTimeExtras();
if (oldExpireTime != 0 && expireTime != oldExpireTime && cctx.config().isEagerTtl())
cctx.ttl().removeTrackedEntry(this);
value(val, valBytes);
ttlAndExpireTimeExtras(ttl, expireTime);
if (expireTime != 0 && expireTime != oldExpireTime && cctx.config().isEagerTtl())
cctx.ttl().addTrackedEntry(this);
this.ver = ver;
}
/**
* @return {@code true} If value bytes should be stored.
*/
protected boolean isStoreValueBytes() {
return cctx.config().isStoreValueBytes();
}
/**
* @return {@code True} if values should be stored off-heap.
*/
protected boolean isOffHeapValuesOnly() {
return cctx.config().getMemoryMode() == GridCacheMemoryMode.OFFHEAP_VALUES;
}
/**
* @param ttl Time to live.
* @return Expiration time.
*/
protected long toExpireTime(long ttl) {
long expireTime = ttl == 0 ? 0 : U.currentTimeMillis() + ttl;
// Account for overflow.
if (expireTime < 0)
expireTime = 0;
return expireTime;
}
/**
* @throws GridCacheEntryRemovedException If entry is obsolete.
*/
protected void checkObsolete() throws GridCacheEntryRemovedException {
assert Thread.holdsLock(this);
if (obsoleteVersionExtras() != null)
throw new GridCacheEntryRemovedException();
}
/** {@inheritDoc} */
@Override public K key() {
return key;
}
/** {@inheritDoc} */
@Override public synchronized GridCacheVersion version() throws GridCacheEntryRemovedException {
checkObsolete();
return ver;
}
/**
* Gets hash value for the entry key.
*
* @return Hash value.
*/
int hash() {
return hash;
}
/**
* Gets next entry in bucket linked list within a hash map segment.
*
* @param segId Segment ID.
* @return Next entry.
*/
GridCacheMapEntry<K, V> next(int segId) {
return segId % 2 == 0 ? next0 : next1;
}
/**
* Sets next entry in bucket linked list within a hash map segment.
*
* @param segId Segment ID.
* @param next Next entry.
*/
void next(int segId, @Nullable GridCacheMapEntry<K, V> next) {
if (segId % 2 == 0)
next0 = next;
else
next1 = next;
}
/** {@inheritDoc} */
@Nullable @Override public V peek(GridCachePeekMode mode, GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridCacheEntryRemovedException {
try {
GridTuple<V> peek = peek0(false, mode, filter, cctx.tm().localTxx());
return peek != null ? peek.get() : null;
}
catch (GridCacheFilterFailedException ignore) {
assert false;
return null;
}
catch (GridException e) {
throw new GridRuntimeException("Unable to perform entry peek() operation.", e);
}
}
/** {@inheritDoc} */
@Override public V peek(Collection<GridCachePeekMode> modes, GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridCacheEntryRemovedException {
assert modes != null;
for (GridCachePeekMode mode : modes) {
try {
GridTuple<V> val = peek0(false, mode, filter, cctx.tm().localTxx());
if (val != null)
return val.get();
}
catch (GridCacheFilterFailedException ignored) {
assert false;
return null;
}
catch (GridException e) {
throw new GridRuntimeException("Unable to perform entry peek() operation.", e);
}
}
return null;
}
/** {@inheritDoc} */
@Nullable @Override public V peekFailFast(GridCachePeekMode mode,
GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridCacheEntryRemovedException, GridCacheFilterFailedException {
try {
GridTuple<V> peek = peek0(true, mode, filter, cctx.tm().localTxx());
return peek != null ? peek.get() : null;
}
catch (GridException e) {
throw new GridRuntimeException("Unable to perform entry peek() operation.", e);
}
}
/**
* @param failFast Fail-fast flag.
* @param mode Peek mode.
* @param filter Filter.
* @param tx Transaction to peek value at (if mode is TX value).
* @return Peeked value.
* @throws GridException In case of error.
* @throws GridCacheEntryRemovedException If removed.
* @throws GridCacheFilterFailedException If filter failed.
*/
@SuppressWarnings({"RedundantTypeArguments"})
@Nullable @Override public GridTuple<V> peek0(boolean failFast, GridCachePeekMode mode,
GridPredicate<GridCacheEntry<K, V>>[] filter, @Nullable GridCacheTxEx<K, V> tx)
throws GridCacheEntryRemovedException, GridCacheFilterFailedException, GridException {
assert tx == null || tx.local();
if (cctx.peekModeExcluded(mode))
return null;
switch (mode) {
case TX:
return peekTx(failFast, filter, tx);
case GLOBAL:
return peekGlobal(failFast, filter);
case NEAR_ONLY:
return peekGlobal(failFast, filter);
case PARTITIONED_ONLY:
return peekGlobal(failFast, filter);
case SMART:
/*
* If there is no ongoing transaction, or transaction is NOT in ACTIVE state,
* which means that it is either rolling back, preparing to commit, or committing,
* then we only check the global cache storage because value has already been
* validated against filter and enlisted into transaction and, therefore, second
* validation against the same enlisted value will be invalid (it will always be false).
*
* However, in ACTIVE state, we must also validate against other values that
* may have enlisted into the same transaction and that's why we pass 'true'
* to 'e.peek(true)' method in this case.
*/
return tx == null || tx.state() != ACTIVE ? peekGlobal(failFast, filter) :
peekTxThenGlobal(failFast, filter, tx);
case SWAP:
return peekSwap(failFast, filter);
case DB:
return F.t(peekDb(failFast, filter));
default: // Should never be reached.
assert false;
return null;
}
}
/** {@inheritDoc} */
@Override public V poke(V val) throws GridCacheEntryRemovedException, GridException {
assert val != null;
V old;
synchronized (this) {
checkObsolete();
if (isNew())
unswap(true);
if (deletedUnlocked())
return null;
old = rawGetOrUnmarshalUnlocked();
GridCacheVersion nextVer = nextVersion();
// Update index inside synchronization since it can be updated
// in load methods without actually holding entry lock.
long expireTime = expireTimeExtras();
updateIndex(val, null, expireTime, nextVer, old);
update(val, null, expireTime, ttlExtras(), nextVer);
}
if (log.isDebugEnabled())
log.debug("Poked cache entry [newVal=" + val + ", oldVal=" + old + ", entry=" + this + ']');
return old;
}
/**
* Checks that entries in group locks transactions are not locked during commit.
*
* @param tx Transaction to check.
* @throws GridCacheEntryRemovedException If entry is obsolete.
* @throws GridException If entry was externally locked.
*/
private void groupLockSanityCheck(GridCacheTxEx<K, V> tx) throws GridCacheEntryRemovedException, GridException {
assert tx.groupLock();
GridCacheTxEntry<K, V> txEntry = tx.entry(key);
if (txEntry.groupLockEntry()) {
if (lockedByAny())
throw new GridException("Failed to update cache entry (entry was externally locked while " +
"accessing entry within group lock transaction) [entry=" + this + ", tx=" + tx + ']');
}
}
/**
* @param failFast Fail fast flag.
* @param filter Filter.
* @param tx Transaction to peek value at (if mode is TX value).
* @return Peeked value.
* @throws GridCacheFilterFailedException If filter failed.
* @throws GridCacheEntryRemovedException If entry got removed.
* @throws GridException If unexpected cache failure occurred.
*/
@Nullable private GridTuple<V> peekTxThenGlobal(boolean failFast,
GridPredicate<GridCacheEntry<K, V>>[] filter,
GridCacheTxEx<K, V> tx) throws GridCacheFilterFailedException, GridCacheEntryRemovedException, GridException {
if (!cctx.peekModeExcluded(TX)) {
GridTuple<V> peek = peekTx(failFast, filter, tx);
// If transaction has value (possibly null, which means value is to be deleted).
if (peek != null)
return peek;
}
return !cctx.peekModeExcluded(GLOBAL) ? peekGlobal(failFast, filter) : null;
}
/**
* @param failFast Fail fast flag.
* @param filter Filter.
* @param tx Transaction to peek value at (if mode is TX value).
* @return Peeked value.
* @throws GridCacheFilterFailedException If filter failed.
*/
@Nullable private GridTuple<V> peekTx(boolean failFast,
GridPredicate<GridCacheEntry<K, V>>[] filter,
@Nullable GridCacheTxEx<K, V> tx) throws GridCacheFilterFailedException {
return tx == null ? null : tx.peek(failFast, key, filter);
}
/**
* @param failFast Fail fast flag.
* @param filter Filter.
* @return Peeked value.
* @throws GridCacheFilterFailedException If filter failed.
* @throws GridCacheEntryRemovedException If entry got removed.
* @throws GridException If unexpected cache failure occurred.
*/
@SuppressWarnings({"RedundantTypeArguments"})
@Nullable private GridTuple<V> peekGlobal(boolean failFast, GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridCacheEntryRemovedException, GridCacheFilterFailedException, GridException {
if (!valid(-1))
return null;
boolean rmv = false;
try {
while (true) {
GridCacheVersion ver;
V val;
synchronized (this) {
if (checkExpired()) {
rmv = markObsolete(cctx.versions().next(this.ver));
return null;
}
checkObsolete();
ver = this.ver;
val = rawGetOrUnmarshalUnlocked();
}
if (!cctx.isAll(wrap(false), filter))
return F.t(CU.<V>failed(failFast));
if (F.isEmpty(filter) || ver.equals(version()))
return F.t(val);
}
}
finally {
if (rmv)
cctx.cache().map().removeEntry(this);
}
}
/**
* @param failFast Fail fast flag.
* @param filter Filter.
* @return Value from swap storage.
* @throws GridException In case of any errors.
* @throws GridCacheFilterFailedException If filter failed.
*/
@SuppressWarnings({"unchecked"})
@Nullable private GridTuple<V> peekSwap(boolean failFast, GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridException, GridCacheFilterFailedException {
if (!cctx.isAll(wrap(false), filter))
return F.t((V)CU.failed(failFast));
synchronized (this) {
if (checkExpired())
return null;
}
GridCacheSwapEntry<V> e = cctx.swap().read(this);
return e != null ? F.t(e.value()) : null;
}
/**
* @param failFast Fail fast flag.
* @param filter Filter.
* @return Value from persistent store.
* @throws GridException In case of any errors.
* @throws GridCacheFilterFailedException If filter failed.
*/
@SuppressWarnings({"unchecked"})
@Nullable private V peekDb(boolean failFast, GridPredicate<GridCacheEntry<K, V>>[] filter)
throws GridException, GridCacheFilterFailedException {
if (!cctx.isAll(wrap(false), filter))
return CU.failed(failFast);
synchronized (this) {
if (checkExpired())
return null;
}
return cctx.store().loadFromStore(cctx.tm().localTxx(), key);
}
/**
* TODO: GG-4009: do we need to generate event and invalidate value?
*
* @return {@code true} if expired.
* @throws GridException In case of failure.
*/
private boolean checkExpired() throws GridException {
assert Thread.holdsLock(this);
long expireTime = expireTimeExtras();
if (expireTime > 0) {
long delta = expireTime - U.currentTimeMillis();
if (log.isDebugEnabled())
log.debug("Checked expiration time for entry [timeLeft=" + delta + ", entry=" + this + ']');
if (delta <= 0) {
releaseSwap();
clearIndex(saveValueForIndexUnlocked());
return true;
}
}
return false;
}
/**
* @return Value.
*/
@Override public synchronized V rawGet() {
return val;
}
/** {@inheritDoc} */
@Override public synchronized V rawGetOrUnmarshal() throws GridException {
return rawGetOrUnmarshalUnlocked();
}
/**
* @return Value (unmarshalled if needed).
* @throws GridException If failed.
*/
protected V rawGetOrUnmarshalUnlocked() throws GridException {
assert Thread.holdsLock(this);
V val = this.val;
if (val != null)
return val;
GridCacheValueBytes valBytes = valueBytesUnlocked();
if (!valBytes.isNull())
val = valBytes.isPlain() ? (V)valBytes.get() : cctx.marshaller().<V>unmarshal(valBytes.get(),
cctx.deploy().globalLoader());
return val;
}
/** {@inheritDoc} */
@Override public synchronized boolean hasValue() {
return hasValueUnlocked();
}
/**
* @return {@code True} if this entry has value.
*/
protected boolean hasValueUnlocked() {
assert Thread.holdsLock(this);
return val != null || valBytes != null || valPtr != 0;
}
/** {@inheritDoc} */
@Override public synchronized GridDrEntry<K, V> drEntry() throws GridException {
return new GridDrPlainEntry<>(key, isStartVersion() ? unswap(true) : rawGetOrUnmarshalUnlocked(),
ttlExtras(), expireTimeExtras(), ver.drVersion());
}
/** {@inheritDoc} */
@Override public synchronized V rawPut(V val, long ttl) {
V old = this.val;
update(val, null, toExpireTime(ttl), ttl, nextVersion());
return old;
}
/** {@inheritDoc} */
@SuppressWarnings({"RedundantTypeArguments"})
@Override public boolean initialValue(V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime,
boolean preload, GridDrType drType) throws GridException, GridCacheEntryRemovedException {
if (cctx.isUnmarshalValues() && valBytes != null && val == null && isNewLocked())
val = cctx.marshaller().<V>unmarshal(valBytes, cctx.deploy().globalLoader());
synchronized (this) {
checkObsolete();
if (isNew() || (!preload && deletedUnlocked())) {
long expTime = expireTime < 0 ? toExpireTime(ttl) : expireTime;
if (val != null || valBytes != null)
updateIndex(val, valBytes, expTime, ver, null);
// Version does not change for load ops.
update(val, valBytes, expTime, ttl, ver);
boolean skipQryNtf = false;
if (val == null && valBytes == null) {
skipQryNtf = true;
if (cctx.deferredDelete()) {
assert !deletedUnlocked();
deletedUnlocked(true);
}
}
else if (deletedUnlocked())
deletedUnlocked(false);
drReplicate(drType, val, valBytes, ver);
if (!skipQryNtf && cctx.isLocalNode(CU.primaryNode(cctx, key)))
cctx.continuousQueries().onEntryUpdate(this, key, val, valueBytesUnlocked(), true);
return true;
}
return false;
}
}
/** {@inheritDoc} */
@Override public synchronized boolean initialValue(K key, GridCacheSwapEntry <V> unswapped) throws GridException,
GridCacheEntryRemovedException {
checkObsolete();
if (isNew()) {
// Version does not change for load ops.
update(unswapped.value(),
unswapped.valueBytes(),
unswapped.expireTime(),
unswapped.ttl(),
unswapped.version()
);
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public synchronized boolean versionedValue(V val, GridCacheVersion curVer, GridCacheVersion newVer)
throws GridException, GridCacheEntryRemovedException {
checkObsolete();
if (curVer == null || curVer.equals(ver)) {
if (val != this.val) {
if (newVer == null)
newVer = nextVersion();
V old = rawGetOrUnmarshalUnlocked();
long ttl = ttlExtras();
long expTime = toExpireTime(ttl);
if (val != null) {
updateIndex(val, null, expTime, newVer, old);
if (deletedUnlocked())
deletedUnlocked(false);
}
// Version does not change for load ops.
update(val, null, expTime, ttl, newVer);
}
return true;
}
return false;
}
/**
* Gets next version for this cache entry.
*
* @return Next version.
*/
private GridCacheVersion nextVersion() {
// Do not change topology version when generating next version.
return cctx.versions().next(ver);
}
/** {@inheritDoc} */
@Override public synchronized boolean hasLockCandidate(GridCacheVersion ver) throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.hasCandidate(ver);
}
/** {@inheritDoc} */
@Override public synchronized boolean hasLockCandidate(long threadId) throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.localCandidate(threadId) != null;
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedByAny(GridCacheVersion... exclude)
throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && !mvcc.isEmpty(exclude);
}
/** {@inheritDoc} */
@Override public boolean lockedByThread() throws GridCacheEntryRemovedException {
return lockedByThread(Thread.currentThread().getId());
}
/** {@inheritDoc} */
@Override public boolean lockedByThread(GridCacheVersion exclude) throws GridCacheEntryRemovedException {
return lockedByThread(Thread.currentThread().getId(), exclude);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedLocally(GridCacheVersion lockVer) throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isLocallyOwned(lockVer);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedByThread(long threadId, GridCacheVersion exclude)
throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isLocallyOwnedByThread(threadId, exclude);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedLocallyByIdOrThread(GridCacheVersion lockVer, long threadId)
throws GridCacheEntryRemovedException {
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isLocallyOwnedByIdOrThread(lockVer, threadId);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedByThread(long threadId) throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isLocallyOwnedByThread(threadId);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedBy(GridCacheVersion ver) throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isOwnedBy(ver);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedByThreadUnsafe(long threadId) {
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isLocallyOwnedByThread(threadId);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedByUnsafe(GridCacheVersion ver) {
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isOwnedBy(ver);
}
/** {@inheritDoc} */
@Override public synchronized boolean lockedLocallyUnsafe(GridCacheVersion lockVer) {
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.isLocallyOwned(lockVer);
}
/** {@inheritDoc} */
@Override public synchronized boolean hasLockCandidateUnsafe(GridCacheVersion ver) {
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc != null && mvcc.hasCandidate(ver);
}
/** {@inheritDoc} */
@Override public synchronized Collection<GridCacheMvccCandidate<K>> localCandidates(GridCacheVersion... exclude)
throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc == null ? Collections.<GridCacheMvccCandidate<K>>emptyList() : mvcc.localCandidates(exclude);
}
/** {@inheritDoc} */
@Override public Collection<GridCacheMvccCandidate<K>> remoteMvccSnapshot(GridCacheVersion... exclude) {
return Collections.emptyList();
}
/** {@inheritDoc} */
@Nullable @Override public synchronized GridCacheMvccCandidate<K> candidate(GridCacheVersion ver)
throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc == null ? null : mvcc.candidate(ver);
}
/** {@inheritDoc} */
@Override public synchronized GridCacheMvccCandidate<K> localCandidate(long threadId)
throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc == null ? null : mvcc.localCandidate(threadId);
}
/** {@inheritDoc} */
@Override public GridCacheMvccCandidate<K> candidate(UUID nodeId, long threadId)
throws GridCacheEntryRemovedException {
boolean loc = cctx.nodeId().equals(nodeId);
synchronized (this) {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc == null ? null : loc ? mvcc.localCandidate(threadId) :
mvcc.remoteCandidate(nodeId, threadId);
}
}
/** {@inheritDoc} */
@Override public synchronized GridCacheMvccCandidate<K> localOwner() throws GridCacheEntryRemovedException {
checkObsolete();
GridCacheMvcc<K> mvcc = mvccExtras();
return mvcc == null ? null : mvcc.localOwner();
}
/** {@inheritDoc} */
@Override public synchronized long rawExpireTime() {
return expireTimeExtras();
}
/** {@inheritDoc} */
@SuppressWarnings({"IfMayBeConditional"})
@Override public long expireTime() throws GridCacheEntryRemovedException {
GridCacheTxLocalAdapter<K, V> tx;
if (cctx.isDht())
tx = cctx.dht().near().context().tm().localTx();
else
tx = cctx.tm().localTx();
if (tx != null) {
long time = tx.entryExpireTime(key);
if (time > 0)
return time;
}
synchronized (this) {
checkObsolete();
return expireTimeExtras();
}
}
/** {@inheritDoc} */
@Override public long expireTimeUnlocked() {
assert Thread.holdsLock(this);
return expireTimeExtras();
}
/** {@inheritDoc} */
@Override public boolean onTtlExpired(GridCacheVersion obsoleteVer) {
boolean obsolete = false;
boolean deferred = false;
try {
synchronized (this) {
V expiredVal = val;
boolean hasOldBytes = valBytes != null || valPtr != 0;
boolean expired = checkExpired();
if (expired) {
if (cctx.deferredDelete() && !detached() && !isInternal()) {
if (!deletedUnlocked()) {
update(null, null, 0L, 0L, ver);
deletedUnlocked(true);
deferred = true;
}
}
else {
if (markObsolete(obsoleteVer))
obsolete = true; // Success, will return "true".
}
if (cctx.events().isRecordable(EVT_CACHE_OBJECT_EXPIRED))
cctx.events().addEvent(partition(), key, cctx.localNodeId(), null, EVT_CACHE_OBJECT_EXPIRED, null,
false, expiredVal, expiredVal != null || hasOldBytes);
}
}
}
catch (GridException e) {
U.error(log, "Failed to clean up expired cache entry: " + this, e);
}
finally {
if (deferred)
cctx.onDeferredDelete(this, obsoleteVer);
}
return obsolete;
}
/** {@inheritDoc} */
@Override public synchronized long rawTtl() {
return ttlExtras();
}
/** {@inheritDoc} */
@SuppressWarnings({"IfMayBeConditional"})
@Override public long ttl() throws GridCacheEntryRemovedException {
GridCacheTxLocalAdapter<K, V> tx;
if (cctx.isDht())
tx = cctx.dht().near().context().tm().localTx();
else
tx = cctx.tm().localTx();
if (tx != null) {
long entryTtl = tx.entryTtl(key);
if (entryTtl > 0)
return entryTtl;
}
synchronized (this) {
checkObsolete();
return ttlExtras();
}
}
/** {@inheritDoc} */
@Override public synchronized void keyBytes(byte[] keyBytes) throws GridCacheEntryRemovedException {
checkObsolete();
if (keyBytes != null)
this.keyBytes = keyBytes;
}
/** {@inheritDoc} */
@Override public synchronized byte[] keyBytes() {
return keyBytes;
}
/** {@inheritDoc} */
@Override public byte[] getOrMarshalKeyBytes() throws GridException {
byte[] bytes = keyBytes();
if (bytes != null)
return bytes;
bytes = CU.marshal(cctx, key);
synchronized (this) {
keyBytes = bytes;
}
return bytes;
}
/** {@inheritDoc} */
@Override public synchronized GridCacheValueBytes valueBytes() throws GridCacheEntryRemovedException {
checkObsolete();
return valueBytesUnlocked();
}
/** {@inheritDoc} */
@Nullable @Override public GridCacheValueBytes valueBytes(@Nullable GridCacheVersion ver)
throws GridException, GridCacheEntryRemovedException {
V val = null;
GridCacheValueBytes valBytes = GridCacheValueBytes.nil();
synchronized (this) {
checkObsolete();
if (ver == null || this.ver.equals(ver)) {
val = this.val;
ver = this.ver;
valBytes = valueBytesUnlocked();
}
else
ver = null;
}
if (valBytes.isNull()) {
if (val != null)
valBytes = (val instanceof byte[]) ? GridCacheValueBytes.plain(val) :
GridCacheValueBytes.marshaled(CU.marshal(cctx, val));
if (ver != null && !isOffHeapValuesOnly()) {
synchronized (this) {
checkObsolete();
if (this.val == val)
this.valBytes = isStoreValueBytes() ? valBytes.getIfMarshaled() : null;
}
}
}
return valBytes;
}
/**
* Updates cache index.
*
* @param val Value.
* @param valBytes Value bytes.
* @param expireTime Expire time.
* @param ver New entry version.
* @param prevVal Previous value.
* @throws GridException If update failed.
*/
protected void updateIndex(@Nullable V val, @Nullable byte[] valBytes, long expireTime, GridCacheVersion ver,
@Nullable V prevVal) throws GridException {
assert Thread.holdsLock(this);
assert val != null || valBytes != null : "null values in update index for key: " + key;
try {
GridCacheQueryManager<K, V> qryMgr = cctx.queries();
if (qryMgr != null)
qryMgr.store(key, keyBytes, val, valBytes, ver, expireTime);
}
catch (GridException e) {
throw new GridCacheIndexUpdateException(e);
}
}
/**
* Clears index.
*
* @param prevVal Previous value (if needed for index update).
* @throws GridException If failed.
*/
protected void clearIndex(@Nullable V prevVal) throws GridException {
assert Thread.holdsLock(this);
try {
GridCacheQueryManager<K, V> qryMgr = cctx.queries();
if (qryMgr != null)
qryMgr.remove(key(), keyBytes());
}
catch (GridException e) {
throw new GridCacheIndexUpdateException(e);
}
}
/**
* This method will return current value only if clearIndex(V) will require previous value (this is the case
* for Mongo caches). If previous value is not required, this method will return {@code null}.
*
* @return Previous value or {@code null}.
* @throws GridException If failed to retrieve previous value.
*/
protected V saveValueForIndexUnlocked() throws GridException {
assert Thread.holdsLock(this);
if (!cctx.cache().isMongoDataCache() && !cctx.cache().isMongoMetaCache())
return null;
return rawGetOrUnmarshalUnlocked();
}
/**
* Wraps this map entry into cache entry.
*
* @param prjAware {@code true} if entry should inherit projection properties.
* @return Wrapped entry.
*/
@Override public GridCacheEntry<K, V> wrap(boolean prjAware) {
GridCacheProjectionImpl<K, V> prjPerCall = null;
if (prjAware)
prjPerCall = cctx.projectionPerCall();
return new GridCacheEntryImpl<>(prjPerCall, cctx, key, this);
}
/** {@inheritDoc} */
@Override public GridCacheEntry<K, V> wrapFilterLocked() throws GridException {
return null;
}
/** {@inheritDoc} */
@Override public GridCacheEntry<K, V> evictWrap() {
return new GridCacheEvictionEntry<>(this);
}
/** {@inheritDoc} */
@Override public boolean evictInternal(boolean swap, GridCacheVersion obsoleteVer,
@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
try {
if (F.isEmpty(filter)) {
synchronized (this) {
V prev = saveValueForIndexUnlocked();
if (!hasReaders() && markObsolete0(obsoleteVer, false)) {
if (swap) {
if (!isStartVersion()) {
try {
// Write to swap.
swap();
}
catch (GridException e) {
U.error(log, "Failed to write entry to swap storage: " + this, e);
}
}
}
else
clearIndex(prev);
// Nullify value after swap.
value(null, null);
onMarkedObsolete();
return true;
}
}
}
else {
// For optimistic check.
while (true) {
GridCacheVersion v;
synchronized (this) {
v = ver;
}
if (!cctx.isAll(this, filter))
return false;
synchronized (this) {
if (!v.equals(ver))
// Version has changed since entry passed the filter. Do it again.
continue;
V prevVal = saveValueForIndexUnlocked();
if (!hasReaders() && markObsolete0(obsoleteVer, false)) {
if (swap) {
if (!isStartVersion()) {
try {
// Write to swap.
swap();
}
catch (GridException e) {
U.error(log, "Failed to write entry to swap storage: " + this, e);
}
}
}
else
clearIndex(prevVal);
// Nullify value after swap.
value(null, null);
onMarkedObsolete();
return true;
}
else
return false;
}
}
}
}
catch (GridCacheEntryRemovedException ignore) {
if (log.isDebugEnabled())
log.debug("Got removed entry when evicting (will simply return): " + this);
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public GridCacheBatchSwapEntry<K, V> evictInBatchInternal(GridCacheVersion obsoleteVer)
throws GridException {
assert Thread.holdsLock(this);
assert cctx.isSwapOrOffheapEnabled();
GridCacheBatchSwapEntry<K, V> ret = null;
try {
if (!hasReaders() && markObsolete0(obsoleteVer, false)) {
if (!isStartVersion()) {
V val = rawGetOrUnmarshalUnlocked();
GridCacheValueBytes valBytes = valueBytesUnlocked();
if (valBytes.isNull())
valBytes = createValueBytes(val);
GridUuid valClsLdrId = null;
if (val != null)
valClsLdrId = cctx.deploy().getClassLoaderId(U.detectObjectClassLoader(val));
ret = new GridCacheBatchSwapEntry<>(key(), getOrMarshalKeyBytes(), hash, partition(),
valBytes.get(), valBytes.isPlain(), ver, ttlExtras(), expireTimeExtras(),
cctx.deploy().getClassLoaderId(U.detectObjectClassLoader(key)), valClsLdrId);
}
value(null, null);
onMarkedObsolete();
}
}
catch (GridCacheEntryRemovedException ignored) {
if (log.isDebugEnabled())
log.debug("Got removed entry when evicting (will simply return): " + this);
}
return ret;
}
/**
* Create value bytes wrapper from the given object.
*
* @param val Value.
* @return Value bytes wrapper.
* @throws GridException If failed.
*/
protected GridCacheValueBytes createValueBytes(@Nullable V val) throws GridException {
return (val != null && val instanceof byte[]) ? GridCacheValueBytes.plain(val) :
GridCacheValueBytes.marshaled(CU.marshal(cctx, val));
}
/**
* @param filter Entry filter.
* @return {@code True} if entry is visitable.
*/
public boolean visitable(GridPredicate<GridCacheEntry<K, V>>[] filter) {
try {
if (obsoleteOrDeleted() || (filter != CU.<K, V>empty() && !cctx.isAll(wrap(false), filter)))
return false;
}
catch (GridException e) {
U.error(log, "An exception was thrown while filter checking.", e);
RuntimeException ex = e.getCause(RuntimeException.class);
if (ex != null)
throw ex;
Error err = e.getCause(Error.class);
if (err != null)
throw err;
return false;
}
GridCacheTxEx<K, V> tx = cctx.tm().localTxx();
return tx == null || !tx.removed(key);
}
/**
* Ensures that internal data storage is created.
*
* @param size Amount of data to ensure.
* @return {@code true} if data storage was created.
*/
private boolean ensureData(int size) {
if (attributeDataExtras() == null) {
attributeDataExtras(new GridLeanMap<String, Object>(size));
return true;
}
else
return false;
}
/** {@inheritDoc} */
@Override public void copyMeta(GridMetadataAware from) {
A.notNull(from, "from");
synchronized (this) {
Map m = from.allMeta();
ensureData(m.size());
attributeDataExtras().putAll(from.allMeta());
}
}
/** {@inheritDoc} */
@Override public void copyMeta(Map<String, ?> attrData) {
A.notNull(attrData, "data");
synchronized (this) {
ensureData(attrData.size());
attributeDataExtras().putAll(attrData);
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Nullable @Override public <V> V addMeta(String name, V val) {
A.notNull(name, "name", val, "val");
synchronized (this) {
ensureData(1);
return (V) attributeDataExtras().put(name, val);
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Nullable @Override public <V> V meta(String name) {
A.notNull(name, "name");
synchronized (this) {
GridLeanMap<String, Object> attrData = attributeDataExtras();
return attrData == null ? null : (V)attrData.get(name);
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Nullable
@Override public <V> V removeMeta(String name) {
A.notNull(name, "name");
synchronized (this) {
GridLeanMap<String, Object> attrData = attributeDataExtras();
if (attrData == null)
return null;
V old = (V)attrData.remove(name);
if (attrData.isEmpty())
attributeDataExtras(null);
return old;
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Override public <V> boolean removeMeta(String name, V val) {
A.notNull(name, "name", val, "val");
synchronized (this) {
GridLeanMap<String, Object> attrData = attributeDataExtras();
if (attrData == null)
return false;
V old = (V)attrData.get(name);
if (old != null && old.equals(val)) {
attrData.remove(name);
if (attrData.isEmpty())
attributeDataExtras(null);
return true;
}
return false;
}
}
/** {@inheritDoc} */
@SuppressWarnings( {"unchecked", "RedundantCast"})
@Override public synchronized <V> Map<String, V> allMeta() {
GridLeanMap<String, Object> attrData = attributeDataExtras();
if (attrData == null)
return Collections.emptyMap();
if (attrData.size() <= 5)
// This is a singleton unmodifiable map.
return (Map<String, V>)attrData;
// Return a copy.
return new HashMap<>((Map<String, V>)attrData);
}
/** {@inheritDoc} */
@Override public boolean hasMeta(String name) {
return meta(name) != null;
}
/** {@inheritDoc} */
@Override public <V> boolean hasMeta(String name, V val) {
A.notNull(name, "name");
Object v = meta(name);
return v != null && v.equals(val);
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Nullable @Override public <V> V putMetaIfAbsent(String name, V val) {
A.notNull(name, "name", val, "val");
synchronized (this) {
V v = meta(name);
if (v == null)
return addMeta(name, val);
return v;
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked", "ClassReferencesSubclass"})
@Nullable @Override public <V> V putMetaIfAbsent(String name, Callable<V> c) {
A.notNull(name, "name", c, "c");
synchronized (this) {
V v = meta(name);
if (v == null)
try {
return addMeta(name, c.call());
}
catch (Exception e) {
throw F.wrap(e);
}
return v;
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Override public <V> V addMetaIfAbsent(String name, V val) {
A.notNull(name, "name", val, "val");
synchronized (this) {
V v = meta(name);
if (v == null)
addMeta(name, v = val);
return v;
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Nullable @Override public <V> V addMetaIfAbsent(String name, @Nullable Callable<V> c) {
A.notNull(name, "name", c, "c");
synchronized (this) {
V v = meta(name);
if (v == null && c != null)
try {
addMeta(name, v = c.call());
}
catch (Exception e) {
throw F.wrap(e);
}
return v;
}
}
/** {@inheritDoc} */
@SuppressWarnings({"RedundantTypeArguments"})
@Override public <V> boolean replaceMeta(String name, V curVal, V newVal) {
A.notNull(name, "name", newVal, "newVal", curVal, "curVal");
synchronized (this) {
if (hasMeta(name)) {
V val = this.<V>meta(name);
if (val != null && val.equals(curVal)) {
addMeta(name, newVal);
return true;
}
}
return false;
}
}
/**
* Convenience way for super-classes which implement {@link Externalizable} to
* serialize metadata. Super-classes must call this method explicitly from
* within {@link Externalizable#writeExternal(ObjectOutput)} methods implementation.
*
* @param out Output to write to.
* @throws IOException If I/O error occurred.
*/
@SuppressWarnings({"TooBroadScope"})
protected void writeExternalMeta(ObjectOutput out) throws IOException {
Map<String, Object> cp;
// Avoid code warning (suppressing is bad here, because we need this warning for other places).
synchronized (this) {
cp = new GridLeanMap<>(attributeDataExtras());
}
out.writeObject(cp);
}
/**
* Convenience way for super-classes which implement {@link Externalizable} to
* serialize metadata. Super-classes must call this method explicitly from
* within {@link Externalizable#readExternal(ObjectInput)} methods implementation.
*
* @param in Input to read from.
* @throws IOException If I/O error occurred.
* @throws ClassNotFoundException If some class could not be found.
*/
@SuppressWarnings({"unchecked"})
protected void readExternalMeta(ObjectInput in) throws IOException, ClassNotFoundException {
GridLeanMap<String, Object> cp = (GridLeanMap<String, Object>)in.readObject();
synchronized (this) {
attributeDataExtras(cp);
}
}
/** {@inheritDoc} */
@Override public boolean deleted() {
if (!cctx.deferredDelete())
return false;
synchronized (this) {
return deletedUnlocked();
}
}
/** {@inheritDoc} */
@Override public synchronized boolean obsoleteOrDeleted() {
return obsoleteVersionExtras() != null ||
(cctx.deferredDelete() && (deletedUnlocked() || !hasValueUnlocked()));
}
/**
* @return {@code True} if deleted.
*/
@SuppressWarnings("SimplifiableIfStatement")
protected boolean deletedUnlocked() {
assert Thread.holdsLock(this);
if (!cctx.deferredDelete())
return false;
return (flags & IS_DELETED_MASK) != 0;
}
/**
* @param deleted {@code True} if deleted.
*/
protected void deletedUnlocked(boolean deleted) {
assert Thread.holdsLock(this);
assert cctx.deferredDelete();
if (deleted) {
assert !deletedUnlocked();
flags |= IS_DELETED_MASK;
cctx.decrementPublicSize(this);
}
else {
assert deletedUnlocked();
flags &= ~IS_DELETED_MASK;
cctx.incrementPublicSize(this);
}
}
/**
* @return {@code True} if refreshing.
*/
protected boolean refreshingUnlocked() {
assert Thread.holdsLock(this);
return (flags & IS_REFRESHING_MASK) != 0;
}
/**
* @param refreshing {@code True} if refreshing.
*/
protected void refreshingLocked(boolean refreshing) {
assert Thread.holdsLock(this);
if (refreshing)
flags |= IS_REFRESHING_MASK;
else
flags &= ~IS_REFRESHING_MASK;
}
/**
* @return Attribute data.
*/
@Nullable private GridLeanMap<String, Object> attributeDataExtras() {
return extras != null ? extras.attributesData() : null;
}
/**
* @param attrData Attribute data.
*/
private void attributeDataExtras(@Nullable GridLeanMap<String, Object> attrData) {
extras = (extras != null) ? extras.attributesData(attrData) : attrData != null ?
new GridCacheAttributesEntryExtras<K>(attrData) : null;
}
/**
* @return MVCC.
*/
@Nullable protected GridCacheMvcc<K> mvccExtras() {
return extras != null ? extras.mvcc() : null;
}
/**
* @param mvcc MVCC.
*/
protected void mvccExtras(@Nullable GridCacheMvcc<K> mvcc) {
extras = (extras != null) ? extras.mvcc(mvcc) : mvcc != null ? new GridCacheMvccEntryExtras<>(mvcc) : null;
}
/**
* @return Obsolete version.
*/
@Nullable protected GridCacheVersion obsoleteVersionExtras() {
return extras != null ? extras.obsoleteVersion() : null;
}
/**
* @param obsoleteVer Obsolete version.
*/
protected void obsoleteVersionExtras(@Nullable GridCacheVersion obsoleteVer) {
extras = (extras != null) ? extras.obsoleteVersion(obsoleteVer) : obsoleteVer != null ?
new GridCacheObsoleteEntryExtras<K>(obsoleteVer) : null;
}
/**
* @return TTL.
*/
protected long ttlExtras() {
return extras != null ? extras.ttl() : 0;
}
/**
* @return Expire time.
*/
protected long expireTimeExtras() {
return extras != null ? extras.expireTime() : 0L;
}
/**
* @param ttl TTL.
* @param expireTime Expire time.
*/
protected void ttlAndExpireTimeExtras(long ttl, long expireTime) {
extras = (extras != null) ? extras.ttlAndExpireTime(ttl, expireTime) : ttl != 0 ?
new GridCacheTtlEntryExtras<K>(ttl, expireTime) : null;
}
/**
* @return Size of extras object.
*/
private int extrasSize() {
return extras != null ? extras.size() : 0;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
// Identity comparison left on purpose.
return o == this;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return hash;
}
/** {@inheritDoc} */
@Override public synchronized String toString() {
return S.toString(GridCacheMapEntry.class, this);
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package com.snakybo.torch.util;
import java.io.FileNotFoundException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.snakybo.torch.debug.Logger;
/**
* @author Snakybo
* @since 1.0
*/
public final class FileUtils
{
private FileUtils()
{
throw new AssertionError();
}
/**
* Get the name and extension of a file
* @param uri The path to the file.
* @return The file name and extension.
*/
public static String getName(URI uri)
{
return getName(Paths.get(uri));
}
/**
* Get the name and extension of a file
* @param path The path to the file.
* @return The file name and extension.
*/
public static String getName(String path)
{
return getName(Paths.get(path));
}
/**
* Get the name of a file
* @param uri The path to the file.
* @return The file name.
*/
public static String getSimpleName(URI uri)
{
return getSimpleName(Paths.get(uri));
}
/**
* Get the name of a file
* @param path The path to the file.
* @return The file name.
*/
public static String getSimpleName(String path)
{
return getSimpleName(Paths.get(path));
}
/**
* Get the extension of a file
* @param uri The path to the file.
* @return The file extension.
*/
public static String getExtension(URI uri)
{
return getExtension(Paths.get(uri));
}
/**
* Get the extension of a file
* @param path The path to the file.
* @return The file extension.
*/
public static String getExtension(String path)
{
return getExtension(Paths.get(path));
}
private static String getName(Path path)
{
Path fileName = path.getFileName();
if(fileName != null)
{
return fileName.toString();
}
Logger.logException(new FileNotFoundException(path.toString()), "FileUtils");
return null;
}
private static String getSimpleName(Path path)
{
String fileName = getName(path);
if(fileName != null)
{
return fileName.substring(0, fileName.lastIndexOf('.'));
}
return null;
}
private static String getExtension(Path path)
{
String fileName = getName(path);
if(fileName != null)
{
return fileName.substring(fileName.lastIndexOf('.') + 1);
}
return null;
}
}
|
package net.anotheria.moskito.core.util;
import net.anotheria.moskito.core.predefined.ThreadStateStats;
import net.anotheria.moskito.core.producers.IStatsProducer;
import net.anotheria.moskito.core.registry.IProducerRegistry;
import net.anotheria.moskito.core.registry.ProducerRegistryFactory;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* This builtin producer monitors the thread states and how many threads are in each state i.e. BLOCKED, RUNNABLE etc.
*
* @author lrosenberg
* @since 25.11.12 23:55
*/
public class BuiltInThreadStatesProducer extends AbstractBuiltInProducer implements IStatsProducer<ThreadStateStats>, BuiltInProducer{
/**
* Cumulated stats object.
*/
private ThreadStateStats cumulated;
/**
* Stats objects as list.
*/
private List<ThreadStateStats> statsList;
/**
* ThreadStateStats map.
*/
private Map<Thread.State, ThreadStateStats> statsMap;
/**
* Reference to the jmx bean.
*/
private ThreadMXBean threadMxBean;
/**
* Package protected constructor.
*/
BuiltInThreadStatesProducer(){
cumulated = new ThreadStateStats("cumulated");
statsMap = new HashMap<Thread.State, ThreadStateStats>();
statsList = new CopyOnWriteArrayList<ThreadStateStats>();
statsList.add(cumulated);
for (Thread.State state : Thread.State.values()){
ThreadStateStats statsObject = new ThreadStateStats(state.name());
statsMap.put(state, statsObject);
statsList.add(statsObject);
}
threadMxBean = ManagementFactory.getThreadMXBean();
IProducerRegistry reg = ProducerRegistryFactory.getProducerRegistryInstance();
reg.registerProducer(this);
BuiltinUpdater.addTask(new TimerTask() {
@Override
public void run() {
readThreads();
}
});
}
/**
* Reads and updates the thread info.
*/
private void readThreads(){
long[] ids = threadMxBean.getAllThreadIds();
HashMap<Thread.State, Long> count = new HashMap<Thread.State, Long>();
for (int i = 0; i<ids.length; i++){
long id = ids[i];
ThreadInfo info = threadMxBean.getThreadInfo(id);
if (info!=null){
Thread.State state = info.getThreadState();
Long old = count.get(state);
if (old==null) {
old = 0L;
}
count.put(state, old+1);
}
}
long total = 0;
for (Map.Entry<Thread.State, ThreadStateStats> entry : statsMap.entrySet()){
Long c = count.get(entry.getKey());
entry.getValue().updateCurrentValue(c==null ? 0 : c.longValue());
if (c!=null)
total += c.longValue();
}
cumulated.updateCurrentValue(total);
}
@Override
public String getCategory() {
return "threads";
}
@Override
public String getProducerId() {
return "ThreadStates";
}
@Override
public List<ThreadStateStats> getStats() {
return statsList;
}
@Override
public String getSubsystem() {
return SUBSYSTEM_BUILTIN;
}
}
|
package com.dgmltn.multiseekbar.internal;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.util.StateSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.DecelerateInterpolator;
import com.dgmltn.multiseekbar.R;
import com.dgmltn.multiseekbar.ThumbView;
public abstract class AbsMultiSeekBar extends ViewGroup implements ThumbView.OnValueChangedListener {
private static final int DEFAULT_TICK_COLOR = Color.BLACK;
private static final int DEFAULT_TEXT_COLOR = Color.WHITE;
@Retention(RetentionPolicy.SOURCE)
@IntDef({ STYLE_CONTINUOUS, STYLE_DISCRETE })
public @interface SliderStyle {
}
public static final int STYLE_CONTINUOUS = 0;
public static final int STYLE_DISCRETE = 1;
// Bar properties
private boolean hasTicks = false;
private
@SliderStyle
int sliderStyle = STYLE_CONTINUOUS;
protected int max = 100;
protected int thumbs = 1;
// Colors
private ColorStateList trackColor;
private ColorStateList tickColor = ColorStateList.valueOf(DEFAULT_TICK_COLOR);
// Properties for autogenerated thumbs
private ColorStateList thumbColor;
private
@ThumbView.ThumbStyle
int thumbStyle = ThumbView.STYLE_CIRCLE;
private int thumbTextColor = DEFAULT_TEXT_COLOR;
public AbsMultiSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
setClipToPadding(false);
setClipChildren(false);
setWillNotDraw(false);
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AbsMultiSeekBar, 0, 0);
max = ta.getInteger(R.styleable.AbsMultiSeekBar_max, max);
thumbs = ta.getInteger(R.styleable.AbsMultiSeekBar_thumbs, thumbs);
hasTicks = ta.getBoolean(R.styleable.AbsMultiSeekBar_hasTicks, hasTicks);
sliderStyle = validateSliderStyle(ta.getInt(R.styleable.AbsMultiSeekBar_style, sliderStyle));
if (ta.hasValue(R.styleable.AbsMultiSeekBar_trackColor)) {
trackColor = ta.getColorStateList(R.styleable.AbsMultiSeekBar_trackColor);
}
else {
trackColor = generateDefaultTrackColorStateListFromTheme(context);
}
if (ta.hasValue(R.styleable.AbsMultiSeekBar_tickColor)) {
tickColor = ta.getColorStateList(R.styleable.AbsMultiSeekBar_tickColor);
}
if (ta.hasValue(R.styleable.AbsMultiSeekBar_thumb_color)) {
thumbColor = ta.getColorStateList(R.styleable.AbsMultiSeekBar_thumb_color);
}
else {
thumbColor = ThumbView.generateDefaultColorStateListFromTheme(context);
}
thumbStyle = ThumbView.validateThumbStyle(ta.getInt(R.styleable.AbsMultiSeekBar_thumb_style, thumbStyle));
thumbTextColor = ta.getColor(R.styleable.AbsMultiSeekBar_thumb_textColor, thumbTextColor);
ta.recycle();
}
initTrack();
}
private static
@SliderStyle
int validateSliderStyle(int s) {
return s == STYLE_DISCRETE ? s : STYLE_CONTINUOUS;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// Don't create any thumbs automatically if the user created his own.
// Let's still listen to value changed.
if (getChildCount() != 0) {
thumbs = 0;
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).addOnValueChangedListener(this);
}
}
else {
for (int i = 0; i < thumbs; i++) {
ThumbView thumb = new ThumbView(getContext(), null);
thumb.setThumbStyle(thumbStyle);
thumb.setImageTintList(thumbColor);
thumb.setTextColor(thumbTextColor);
thumb.addOnValueChangedListener(this);
addView(thumb);
}
}
}
public static ColorStateList generateDefaultTrackColorStateListFromTheme(Context context) {
int[][] states = new int[][] {
SELECTED_STATE_SET,
ENABLED_STATE_SET,
StateSet.WILD_CARD
};
// This is an approximation of the track colors derived from Lollipop resources
boolean isLightTheme = Utils.isLightTheme(context);
int enabled = isLightTheme ? 0x28181818 : 0x85ffffff;
int[] colors = new int[] {
Utils.getThemeColor(context, android.R.attr.colorControlActivated),
enabled,
0x14181818 //TODO: get this from a theme attr?
};
return new ColorStateList(states, colors);
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
// Layout
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
for (int i = 0; i < getChildCount(); i++) {
ThumbView child = getChildAt(i);
getPointOnBar(mTmpPointF, child.getValue());
mTmpPointF.x -= child.getMeasuredWidth() / 2f;
mTmpPointF.y -= child.getMeasuredHeight() / 2f;
child.layout(
(int) mTmpPointF.x,
(int) mTmpPointF.y,
(int) mTmpPointF.x + child.getMeasuredWidth(),
(int) mTmpPointF.y + child.getMeasuredHeight()
);
}
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected LayoutParams generateLayoutParams(LayoutParams p) {
return new MarginLayoutParams(p);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
@Override
public ThumbView getChildAt(int index) {
return (ThumbView) super.getChildAt(index);
}
@Override
public void onValueChange(ThumbView thumb, float oldVal, float newVal) {
getPointOnBar(mTmpPointF, newVal);
float dx = mTmpPointF.x - thumb.getMeasuredWidth() / 2f - thumb.getLeft();
float dy = mTmpPointF.y - thumb.getMeasuredHeight() / 2f - thumb.getTop();
thumb.offsetLeftAndRight((int) dx);
thumb.offsetTopAndBottom((int) dy);
invalidate();
}
// Taps
private int expanded = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
// If this View is not enabled, don't allow for touch interactions.
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float dmin = Float.MAX_VALUE;
expanded = -1;
for (int i = 0; i < getChildCount(); i++) {
ThumbView thumb = getChildAt(i);
if (!thumb.isClickable()) {
continue;
}
float d = distance(thumb.getValue(), event.getX(), event.getY());
if (d < dmin) {
dmin = d;
// 48dp touch region
if (d <= getResources().getDimension(R.dimen.default_touch_radius)) {
expanded = i;
}
}
}
if (expanded > -1) {
ThumbView thumb = getChildAt(expanded);
thumb.setPressed(true);
cancelLongPress();
attemptClaimDrag();
onStartTrackingTouch();
}
break;
case MotionEvent.ACTION_MOVE:
if (expanded > -1) {
float value = getNearestBarValue(event.getX(), event.getY());
getChildAt(expanded).setValue(value);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (expanded > -1) {
ThumbView thumb = getChildAt(expanded);
thumb.setPressed(false);
onStopTrackingTouch();
expanded = -1;
if (sliderStyle == STYLE_DISCRETE) {
float value = Math.round(thumb.getValue());
ObjectAnimator anim = ObjectAnimator.ofFloat(thumb, "value", value).setDuration(100);
anim.setInterpolator(new DecelerateInterpolator());
anim.start();
}
}
break;
}
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
private float distance(float value, float x, float y) {
getPointOnBar(mTmpPointF, value);
float m = mTmpPointF.x - x;
float n = mTmpPointF.y - y;
return (float) Math.sqrt(m * m + n * n);
}
private void attemptClaimDrag() {
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
// Rendering
protected Paint mTrackOffPaint;
protected Paint mTrackOnPaint;
protected Paint mTickPaint;
PointF mTmpPointF = new PointF();
protected void initTrack() {
Resources res = getResources();
// Initialize the paint.
mTrackOffPaint = new Paint();
mTrackOffPaint.setAntiAlias(true);
mTrackOffPaint.setStyle(Paint.Style.STROKE);
mTrackOffPaint.setColor(trackColor.getColorForState(ENABLED_STATE_SET, trackColor.getDefaultColor()));
mTrackOffPaint.setStrokeWidth(res.getDimensionPixelSize(R.dimen.default_track_width));
mTickPaint = new Paint();
mTickPaint.setAntiAlias(true);
mTickPaint.setColor(tickColor.getColorForState(ENABLED_STATE_SET, tickColor.getDefaultColor()));
// Initialize the paint, set values
mTrackOnPaint = new Paint();
mTrackOnPaint.setStrokeCap(Paint.Cap.ROUND);
mTrackOnPaint.setStyle(Paint.Style.STROKE);
mTrackOnPaint.setAntiAlias(true);
mTrackOnPaint.setColor(trackColor.getColorForState(SELECTED_STATE_SET, trackColor.getDefaultColor()));
mTrackOnPaint.setStrokeWidth(res.getDimensionPixelSize(R.dimen.default_track_width));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawBar(canvas, mTrackOffPaint);
if (hasTicks) {
drawTicks(canvas);
}
if (getChildCount() == 1) {
drawConnectingLine(canvas, 0f, getChildAt(0).getValue(), mTrackOnPaint);
}
else if (getChildCount() == 2) {
float min = Math.min(getChildAt(0).getValue(), getChildAt(1).getValue());
float max = Math.max(getChildAt(0).getValue(), getChildAt(1).getValue());
drawConnectingLine(canvas, min, max, mTrackOnPaint);
}
}
/**
* Draws the tick marks on the bar.
*
* @param canvas Canvas to draw on; should be the Canvas passed into {#link
* View#onDraw()}
*/
protected void drawTicks(Canvas canvas) {
float radius = getResources().getDimension(R.dimen.default_tick_radius);
for (int i = 0; i <= max; i++) {
getPointOnBar(mTmpPointF, i);
canvas.drawCircle(mTmpPointF.x, mTmpPointF.y, radius, mTickPaint);
}
}
// OnSliderChangeListener
/**
* A callback that notifies clients when the progress level has been
* changed. This includes changes that were initiated by the user through a
* touch gesture or arrow key/trackball as well as changes that were initiated
* programmatically.
*/
public interface OnSliderChangeListener {
/**
* Notification that the user has started a touch gesture.
*
* @param slider The SeekBar in which the touch gesture began
*/
void onStartTrackingTouch(AbsMultiSeekBar slider);
/**
* Notification that the user has finished a touch gesture.
*
* @param slider The SeekBar in which the touch gesture began
*/
void onStopTrackingTouch(AbsMultiSeekBar slider);
}
private OnSliderChangeListener mOnSeekBarChangeListener;
/**
* Sets a listener to receive notifications of changes to the SeekBar's progress level. Also
* provides notifications of when the user starts and stops a touch gesture within the SeekBar.
*
* @param l The seek bar notification listener
*/
public void setOnSliderChangeListener(OnSliderChangeListener l) {
mOnSeekBarChangeListener = l;
}
void onStartTrackingTouch() {
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStartTrackingTouch(this);
}
}
void onStopTrackingTouch() {
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStopTrackingTouch(this);
}
}
// Abstract Methods
/**
* Draw the connecting line between the two thumbs in RangeBar.
*
* @param canvas the Canvas to draw on
* @param from the lower bar value of the connecting line
* @param to the upper bar value of the connecting line
*/
protected abstract void drawConnectingLine(Canvas canvas, float from, float to, Paint paint);
/**
* Gets the value of the bar nearest to the passed point.
*
* @param x the x value to snap to the bar
* @param y the y value to snap to the bar
*/
protected abstract float getNearestBarValue(float x, float y);
/**
* Gets the coordinates of the bar value.
*/
protected abstract void getPointOnBar(PointF out, float value);
/**
* Draws the bar on the given Canvas.
*
* @param canvas Canvas to draw on; should be the Canvas passed into {#link
* View#onDraw()}
*/
protected abstract void drawBar(Canvas canvas, Paint paint);
}
|
package org.ngrinder.home.controller;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ngrinder.common.controller.NGrinderBaseController;
import org.ngrinder.common.exception.NGrinderRuntimeException;
import org.ngrinder.common.util.DateUtil;
import org.ngrinder.infra.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
@Controller
@RequestMapping("/")
public class HomeController extends NGrinderBaseController {
private static final Logger LOG = LoggerFactory.getLogger(HomeController.class);
@Autowired
private Config config;
@RequestMapping(value = { "/home", "/" })
public String home(ModelMap model, HttpServletResponse response, HttpServletRequest request) {
String roles;
try {
// set local language
setLanguage(getCurrentUserInfo("userLanguage"), response, request);
setLoginPageDate(model);
roles = getCurrentUserInfo("role");
} catch (AuthenticationCredentialsNotFoundException e) {
return "login";
}
if (roles == null) {
return "login";
} else if (roles.indexOf("U") != -1) {
return "redirect:/project/list";
} else if (roles.indexOf("A") != -1 || roles.indexOf("S") != -1) {
return "redirect:/project/list";
} else {
LOG.info("Invalid user role:{}", roles);
return "login";
}
}
public void setLanguage(String lan, HttpServletResponse response, HttpServletRequest request) {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (lan != null) {
if (localeResolver == null) {
throw new NGrinderRuntimeException("No LocaleResolver found!");
}
LocaleEditor localeEditor = new LocaleEditor();
localeEditor.setAsText(lan);
localeResolver.setLocale(request, response, (Locale) localeEditor.getValue());
} else {
throw new NGrinderRuntimeException("No User Language found!");
}
}
@RequestMapping(value = "/login")
public String login(ModelMap model) {
setLoginPageDate(model);
return "login";
}
public void setLoginPageDate(ModelMap model) {
TimeZone defaultTime = TimeZone.getDefault();
model.addAttribute("version", config.getSystemProperties().getProperty("VERSION", "UNKNOWN"));
model.addAttribute("defaultTime", defaultTime.getID());
}
@RequestMapping(value = "/help")
public String openHelp(ModelMap model) {
setCurrentUserInfoForModel(model);
return "help";
}
@RequestMapping(value = "/changeTimeZone")
public @ResponseBody
String changeTimeZone(String timeZone) {
return setTimeZone(timeZone);
}
@RequestMapping(value = "/allTimeZone")
public String getAllTimeZone(ModelMap model) {
model.addAttribute("timeZones", DateUtil.getFilteredTimeZoneMap());
return "allTimeZone";
}
}
|
package com.example.albumbrazil.models;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
public class Album implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<Estampa> estampasPegadas;
private HashMap<Integer, Integer> repetidas; //id,numero de veces repetida con put lo actualizas put(id, get(id)+1)
public static HashMap<Integer, String> catalogo = new HashMap<Integer, String>(){{
put(1,"Iker Casillas");
put(2,"Bastian Schweinsteiger");
put(3,"Xavi");
put(4,"Andres Iniesta");
put(5,"Lionel Mesi");
put(6,"Javier Hernandez");
put(7,"Robin VanPersie");
put(8,"Rafael Marquez");
put(9,"Neymar");
put(10,"Wayne Rooney");
put(11,"Karim Benzama");
put(12,"Arjen Robben");
put(13,"Fran Ribery");
put(14,"Samuel Eto'o");
put(15, "Radamel Falcao");
put(16, "Didier Drogba");
put(17, "Clint Dempsey");
put(18, "Philipp Lahm");
put(19, "Mesut Özil");
put(20, "Luis Suárez");
put(21, "Segio Agüero");
put(22, "Oribe Peralta");
put(23, "Cristiano Ronaldo");
put(24, "Kaká");
put(25, "Yaya Touré");
put(26, "Mario Balotelli");
put(27, "Antonio Valencia");
put(28, "Thiago Silva");
put(29, "Wesley Sneijder");
put(30, "Mario Mandzukic");
put(31, "Alexis Sánchez");
put(32, "Nani");
put(33, "Sergio Ramos");
put(34, "Lukas Podolski");
put(35, "Theo Walcott");
put(36, "Carlos Tévez");
put(37, "Alexandre Pato");
put(38, "Steven Gerrard");
put(39, "Ángel Di María");
put(40, "Shinji Kagawa");
put(41, "Diego Costa");
put(42, "Manuel Neuer");
put(43, "Stephan El Shaarawy");
put(44, "Luka Modric");
put(45, "Hulk");
put(46, "Andrea Pirlo");
put(47, "Edinson Cavani");
put(48, "Mario Gómez");
put(49, "Rio Ferdinand");
put(50, "David Luiz");
}};
public ArrayList<Estampa> getEstampas() {
return estampasPegadas;
}
public void setEstampas(ArrayList<Estampa> estampas) {
estampasPegadas = estampas;
}
public HashMap<Integer, Integer> getRepetidas() {
return repetidas;
}
public void setRepetidas(HashMap<Integer, Integer> repetidas) {
this.repetidas = repetidas;
}
public static HashMap<Integer, String> getCatalogo() {
return catalogo;
}
public void shit(String s){
System.out.println(s);
}
}
|
package eic.beike.projectx.model;
import eic.beike.projectx.network.busdata.SimpleBusCollector;
import android.util.Log;
import eic.beike.projectx.network.busdata.BusCollector;
import eic.beike.projectx.network.busdata.Sensor;
import eic.beike.projectx.util.Constants;
/**
*@author Simon
*/
public class Count implements ScoreCountApi {
/**
* The gameModel uses this counter.
*/
private final Long epochyear = 1444800000000l;
private GameModel gameModel;
private boolean isRunning = true;
public Count(GameModel game) {
this.gameModel = game;
}
@Override
public void count(long t1) {
new Thread() {
long t1;
public void count(long t1) {
this.t1 = t1;
this.start();
}
/**
* Runs until a Stop pressed event is found.
*/
@Override
public void run() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Long startTime = System.currentTimeMillis() + Constants.ONE_SECOND_IN_MILLI * 20;
BusCollector bus = SimpleBusCollector.getInstance();
Long t2 = 0l;
boolean hasNotCalculated = true;
while((System.currentTimeMillis() < startTime) && isRunning && hasNotCalculated) {
t2 = bus.getBusData(t1, Sensor.Stop_Pressed).timestamp;
if(t2 == 0) {
} else {
calculatePercent(t1, t2);
hasNotCalculated = false;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(hasNotCalculated) {
calculatePercent(t1,t2);
}
} catch (Exception e) {
Log.e("Count", e.getMessage());
}
}
}.count(t1);
}
public void sum(Button[][] buttons) {
gameModel.addBonus(columns(buttons) + rows(buttons));
}
/**
* @return returns the score from all buttons that are "three of a kind"
* it also sets that they are counted so they can be generated again
*/
private int columns(Button[][] buttons) {
int count = 0;
for (Button[] button : buttons) {
if (button[0].color == button[1].color
&& button[0].color == button[2].color) {
count += button[0].score + button[1].score + button[2].score;
button[0].counted = true;
button[1].counted = true;
button[2].counted = true;
}
}
return count;
}
/**
* @return returns the score fomr all buttons that are "three of a kind"
* it also sets that they are counted so they can be generated again
*/
private int rows(Button[][] buttons) {
int count = 0;
for (int i = 0; i < buttons.length; i++) {
if (buttons[0][i].color == buttons[1][i].color
&& buttons[1][i].color == buttons[2][i].color) {
count += buttons[0][i].score + buttons[1][i].score + buttons[2][i].score;
buttons[0][i].counted = true;
buttons[1][i].counted = true;
buttons[2][i].counted = true;
}
}
return count;
}
public synchronized void calculatePercent(long t1, long t2) {
if (t2 == 0) {
gameModel.addScore(0.3);
} else if (t1 < t2) {
t1 -= epochyear;
t2 -= epochyear;
gameModel.addScore(Math.abs( ((double) t1 / (double) t2)));
} else {
t1 -= epochyear;
t2 -= epochyear;
gameModel.addScore(Math.abs( ( (double) t2 / (double) t1)));
}
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mtrn.data;
import cfd.DAttributeOptionCondicionesPago;
import cfd.DAttributeOptionImpuestoRetencion;
import cfd.DAttributeOptionImpuestoTraslado;
import cfd.DAttributeOptionMoneda;
import cfd.DAttributeOptionTipoComprobante;
import cfd.DElement;
import cfd.ext.bachoco.DElementLineItem;
import cfd.ext.bachoco.DElementPayment;
import cfd.ext.elektra.DElementAp;
import cfd.ext.elektra.DElementDetailItems;
import cfd.ext.elektra.DElementDetalle;
import cfd.ext.elektra.DElementImpuestos;
import cfd.ext.elektra.DElementProducto;
import cfd.ext.elektra.DElementTrasladado;
import cfd.ext.interfactura.DElementCuerpo;
import cfd.ext.interfactura.DElementFacturaInterfactura;
import cfd.ext.soriana.DElementArticulos;
import cfd.ext.soriana.DElementDSCargaRemisionProv;
import cfd.ext.soriana.DElementFolioNotaEntrada;
import erp.SClient;
import erp.cfd.SCfdConsts;
import erp.cfd.SCfdDataConcepto;
import erp.cfd.SCfdDataImpuesto;
import erp.client.SClientInterface;
import erp.data.SDataConstants;
import erp.data.SDataConstantsSys;
import erp.data.SDataReadDescriptions;
import erp.data.SDataUtilities;
import erp.gui.session.SSessionCustom;
import erp.gui.session.SSessionItem;
import erp.lib.SLibConstants;
import erp.lib.SLibTimeUtilities;
import erp.lib.SLibUtilities;
import erp.mbps.data.SDataBizPartnerBranch;
import erp.mfin.data.SDataAccountCash;
import erp.mfin.data.SDataBookkeepingNumber;
import erp.mfin.data.SDataRecord;
import erp.mfin.data.SDataRecordEntry;
import erp.mfin.data.SFinAccountConfig;
import erp.mfin.data.SFinAccountConfigEntry;
import erp.mfin.data.SFinAccountUtilities;
import erp.mfin.data.SFinAmount;
import erp.mfin.data.SFinAmountType;
import erp.mfin.data.SFinAmounts;
import erp.mfin.data.SFinDpsTaxes;
import erp.mfin.data.SFinMovement;
import erp.mod.SModSysConsts;
import erp.mod.trn.db.SDbMmsConfig;
import erp.mod.trn.db.STrnUtils;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import sa.lib.SLibConsts;
import sa.lib.SLibUtils;
import sa.lib.db.SDbConsts;
/**
*
* @author Sergio Flores
*/
public class SDataDps extends erp.lib.data.SDataRegistry implements java.io.Serializable, erp.cfd.SCfdXml {
public static final int FIELD_REF_BKR = 1;
public static final int FIELD_SAL_AGT = 2;
public static final int FIELD_SAL_AGT_SUP = 3;
public static final int FIELD_CLO_COMMS = 4;
public static final int FIELD_CLO_COMMS_USR = 5;
public static final int FIELD_USR = 6;
public static final String TXT_ADV_BILL = "facturación anticipos";
public static final String MSG_ERR_FIN_REC_USR = "No se ha especificado la póliza contable de usuario.";
public static final String MSG_ERR_ACC_UNK_ = "No se encontró la configuración de cuentas contables para el ";
public static final String MSG_ERR_ACC_EMP_ = "La configuración de cuentas contables está vacía para el ";
public static final int AUT_AUTHORN_REJ_NA = 0;
public static final int AUT_AUTHORN_REJ_LIM_USR = 1;
public static final int AUT_AUTHORN_REJ_LIM_USR_MON = 2;
public static final int AUT_AUTHORN_REJ_LIM_FUNC_MON = 3;
public static final String TXT_AUT_AUTHORN_REJ_NA = "No aplica";
public static final String TXT_AUT_AUTHORN_REJ_LIM_USR = "Tope evento usuario";
public static final String TXT_AUT_AUTHORN_REJ_LIM_USR_MON = "Tope mensual usuario";
public static final String TXT_AUT_AUTHORN_REJ_LIM_FUNC_MON = "Tope mensual área funcional";
public static final HashMap<Integer, String> AutAuthornRejMap = new HashMap<Integer, String>();
static {
AutAuthornRejMap.put(AUT_AUTHORN_REJ_NA, TXT_AUT_AUTHORN_REJ_NA);
AutAuthornRejMap.put(AUT_AUTHORN_REJ_LIM_USR, TXT_AUT_AUTHORN_REJ_LIM_USR);
AutAuthornRejMap.put(AUT_AUTHORN_REJ_LIM_USR_MON, TXT_AUT_AUTHORN_REJ_LIM_USR_MON);
AutAuthornRejMap.put(AUT_AUTHORN_REJ_LIM_FUNC_MON, TXT_AUT_AUTHORN_REJ_LIM_FUNC_MON);
}
protected int mnPkYearId;
protected int mnPkDocId;
protected java.util.Date mtDate;
protected java.util.Date mtDateDoc;
protected java.util.Date mtDateStartCredit;
protected java.util.Date mtDateShipment_n;
protected java.util.Date mtDateDelivery_n;
protected java.util.Date mtDateDocLapsing_n;
protected java.util.Date mtDateDocDelivery_n;
protected java.lang.String msNumberSeries;
protected java.lang.String msNumber;
protected java.lang.String msNumberReference;
protected java.lang.String msCommissionsReference;
protected int mnApproveYear;
protected int mnApproveNumber;
protected int mnDaysOfCredit;
protected boolean mbIsDiscountDocApplying;
protected boolean mbIsDiscountDocPercentage;
protected double mdDiscountDocPercentage;
protected double mdSubtotalProvisional_r;
protected double mdDiscountDoc_r;
protected double mdSubtotal_r;
protected double mdTaxCharged_r;
protected double mdTaxRetained_r;
protected double mdTotal_r;
protected double mdCommissions_r;
protected double mdExchangeRate;
protected double mdExchangeRateSystem;
protected double mdSubtotalProvisionalCy_r;
protected double mdDiscountDocCy_r;
protected double mdSubtotalCy_r;
protected double mdTaxChargedCy_r;
protected double mdTaxRetainedCy_r;
protected double mdTotalCy_r;
protected double mdCommissionsCy_r;
protected java.lang.String msDriver;
protected java.lang.String msPlate;
protected java.lang.String msTicket;
protected int mnShipments;
protected int mnPayments;
protected java.lang.String msPaymentMethod;
protected java.lang.String msPaymentAccount;
protected int mnAutomaticAuthorizationRejection;
protected boolean mbIsPublic;
protected boolean mbIsLinked;
protected boolean mbIsClosed;
protected boolean mbIsClosedCommissions;
protected boolean mbIsShipped;
protected boolean mbIsRebill;
protected boolean mbIsAudited;
protected boolean mbIsAuthorized;
protected boolean mbIsRecordAutomatic;
protected boolean mbIsCopy;
protected boolean mbIsCopied;
protected boolean mbIsSystem;
protected boolean mbIsDeleted;
protected int mnFkDpsCategoryId;
protected int mnFkDpsClassId;
protected int mnFkDpsTypeId;
protected int mnFkPaymentTypeId;
protected int mnFkPaymentSystemTypeId;
protected int mnFkDpsStatusId;
protected int mnFkDpsValidityStatusId;
protected int mnFkDpsAuthorizationStatusId;
protected int mnFkDpsAnnulationTypeId;
protected int mnFkDpsNatureId;
protected int mnFkCompanyBranchId;
protected int mnFkFunctionalAreaId;
protected int mnFkBizPartnerId_r;
protected int mnFkBizPartnerBranchId;
protected int mnFkBizPartnerBranchAddressId;
protected int mnFkBizPartnerAltId_r;
protected int mnFkBizPartnerBranchAltId;
protected int mnFkBizPartnerBranchAddressAltId;
protected int mnFkContactBizPartnerBranchId_n;
protected int mnFkContactContactId_n;
protected int mnFkTaxIdentityEmisorTypeId;
protected int mnFkTaxIdentityReceptorTypeId;
protected int mnFkLanguajeId;
protected int mnFkCurrencyId;
protected int mnFkSalesAgentId_n;
protected int mnFkSalesAgentBizPartnerId_n;
protected int mnFkSalesSupervisorId_n;
protected int mnFkSalesSupervisorBizPartnerId_n;
protected int mnFkIncotermId;
protected int mnFkSpotSourceId_n;
protected int mnFkSpotDestinyId_n;
protected int mnFkModeOfTransportationTypeId;
protected int mnFkCarrierTypeId;
protected int mnFkCarrierId_n;
protected int mnFkVehicleTypeId_n;
protected int mnFkVehicleId_n;
protected int mnFkSourceYearId_n;
protected int mnFkSourceDocId_n;
protected int mnFkMfgYearId_n;
protected int mnFkMfgOrderId_n;
protected int mnFkUserLinkedId;
protected int mnFkUserClosedId;
protected int mnFkUserClosedCommissionsId;
protected int mnFkUserShippedId;
protected int mnFkUserAuditedId;
protected int mnFkUserAuthorizedId;
protected int mnFkUserNewId;
protected int mnFkUserEditId;
protected int mnFkUserDeleteId;
protected java.util.Date mtUserLinkedTs;
protected java.util.Date mtUserClosedTs;
protected java.util.Date mtUserClosedCommissionsTs;
protected java.util.Date mtUserShippedTs;
protected java.util.Date mtUserAuditedTs;
protected java.util.Date mtUserAuthorizedTs;
protected java.util.Date mtUserNewTs;
protected java.util.Date mtUserEditTs;
protected java.util.Date mtUserDeleteTs;
protected java.util.Vector<SDataDpsEntry> mvDbmsDpsEntries;
protected java.util.Vector<SDataDpsNotes> mvDbmsDpsNotes;
protected java.lang.Object moDbmsRecordKey;
protected java.util.Date mtDbmsRecordDate;
protected java.lang.String msDbmsCurrency;
protected java.lang.String msDbmsCurrencyKey;
protected boolean mbAuxIsFormerRecordAutomatic;
protected java.lang.Object moAuxFormerRecordKey;
protected erp.mtrn.data.SCfdParams moAuxCfdParams;
protected boolean mbAuxIsNeedCfd;
protected boolean mbAuxIsValidate;
protected erp.mfin.data.SDataBookkeepingNumber moDbmsDataBookkeepingNumber;
protected erp.mtrn.data.SDataCfd moDbmsDataCfd;
protected erp.mtrn.data.SDataDpsAddenda moDbmsDataAddenda;
protected String msCfdExpeditionLocality;
protected String msCfdExpeditionState;
protected double mdCfdIvaPorcentaje;
public SDataDps() {
super(SDataConstants.TRN_DPS);
mlRegistryTimeout = 1000 * 60 * 60 * 2; // 2 hr
mvDbmsDpsEntries = new Vector<>();
mvDbmsDpsNotes = new Vector<>();
reset();
}
/*
* Private functions
*/
private boolean isDpsAuthorizedUser(SDataUserConfigurationTransaction oUserConfig) throws java.sql.SQLException, java.lang.Exception {
return oUserConfig.getPurchasesOrderLimit_n() == 0 || oUserConfig.getPurchasesOrderLimit_n() >= mdTotal_r;
}
private boolean isDpsAuthorizedUserMonth(java.sql.Connection connection, SDataUserConfigurationTransaction oUserConfig) throws java.sql.SQLException, java.lang.Exception {
double amtAccumUser = 0;
amtAccumUser = STrnUtils.getOrderAmountMonthUser(connection, (int[]) getPrimaryKey(), mtDate, mnFkUserNewId);
return oUserConfig.getPurchasesOrderLimitMonthly_n() == 0 || (oUserConfig.getPurchasesOrderLimitMonthly_n() >= mdTotal_r && oUserConfig.getPurchasesOrderLimitMonthly_n() >= (amtAccumUser + mdTotal_r));
}
private boolean isDpsAuthorizedFunctionalAreaMonth(java.sql.Connection connection) throws java.sql.SQLException, java.lang.Exception {
double limitFuncArea = 0;
double amtAccumFuncArea = 0;
limitFuncArea = STrnUtils.getMaxLimitMonthFunctionalArea(connection, mnFkFunctionalAreaId);
amtAccumFuncArea = STrnUtils.getOrderAmountMonthFunctionalArea(connection, (int[]) getPrimaryKey(), mtDate, mnFkFunctionalAreaId);
return limitFuncArea == 0 || (limitFuncArea >= mdTotal_r && limitFuncArea >= (amtAccumFuncArea + mdTotal_r));
}
private boolean isDpsAuthorized(java.sql.Connection connection) throws java.sql.SQLException, java.lang.Exception {
boolean autorized = false;
Statement oStatement = null;
SDataUserConfigurationTransaction oUserConfig = null;
oStatement = connection.createStatement();
oUserConfig = new SDataUserConfigurationTransaction();
if (oUserConfig.read(new int[] { mbIsRegistryNew ? mnFkUserNewId : mnFkUserEditId }, oStatement) != SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
if (mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_PUR) {
if (isOrderPur()) {
autorized = isDpsAuthorizedUser(oUserConfig);
if (!autorized) {
mnAutomaticAuthorizationRejection = AUT_AUTHORN_REJ_LIM_USR;
}
else {
autorized = isDpsAuthorizedUserMonth(connection, oUserConfig);
if (!autorized) {
mnAutomaticAuthorizationRejection = AUT_AUTHORN_REJ_LIM_USR_MON;
}
else {
autorized = isDpsAuthorizedFunctionalAreaMonth(connection);
if (!autorized) {
mnAutomaticAuthorizationRejection = AUT_AUTHORN_REJ_LIM_FUNC_MON;
}
else {
mnAutomaticAuthorizationRejection = AUT_AUTHORN_REJ_NA;
}
}
}
}
else if (isDocumentPur()) {
if (oUserConfig.getPurchasesDocLimit_n() == 0 || oUserConfig.getPurchasesDocLimit_n() >= mdTotal_r) {
autorized = true;
}
}
/*
if (isOrderPur() && (oUserConfig.getPurchasesOrderLimit_n() == 0 || oUserConfig.getPurchasesOrderLimit_n() >= mdTotal_r)) {
isAutorized = true;
}
else if (isDocumentPur() && (oUserConfig.getPurchasesDocLimit_n() == 0 || oUserConfig.getPurchasesDocLimit_n() >= mdTotal_r)) {
isAutorized = true;
}
*/
}
else if (mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_SAL) {
if (isOrderSal() && (oUserConfig.getSalesOrderLimit_n() == 0 || oUserConfig.getSalesOrderLimit_n() >= mdTotal_r)) {
autorized = true;
}
else if (isDocumentSal() && (oUserConfig.getSalesDocLimit_n() == 0 || oUserConfig.getSalesDocLimit_n() >= mdTotal_r)) {
autorized = true;
}
}
}
return autorized;
}
private void updateAuthorizationStatus(java.sql.Connection connection) throws java.sql.SQLException, java.lang.Exception {
boolean isAutPurOrd = false;
boolean isAutPurDps = false;
boolean isAutSalOrd = false;
boolean isAutSalDps = false;
String sql = "";
Statement statement = null;
ResultSet resultSet = null;
if (!mbIsDeleted && (isOrder() || isDocument())) {
statement = connection.createStatement();
// XXX It is needed a "session" object in SDataRegistry objects in order to know current company, company branch, current entities, decimal an date format objects, etc.
sql = "SELECT fid_bp FROM erp.bpsu_bpb WHERE id_bpb = " + mnFkCompanyBranchId + " ";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
sql = "SELECT b_authorn_pur_ord, b_authorn_pur_doc, b_authorn_sal_ord, b_authorn_sal_doc FROM cfg_param_co WHERE id_co = " + resultSet.getInt("fid_bp") + " ";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
isAutPurOrd = resultSet.getBoolean("b_authorn_pur_ord");
isAutPurDps = resultSet.getBoolean("b_authorn_pur_doc");
isAutSalOrd = resultSet.getBoolean("b_authorn_sal_ord");
isAutSalDps = resultSet.getBoolean("b_authorn_sal_doc");
}
}
if (isOrderPur() && isAutPurOrd || isDocumentPur() && isAutPurDps || isOrderSal() && isAutSalOrd || isDocumentSal() && isAutSalDps) {
if (isDpsAuthorized(connection)) {
mbIsAuthorized = true;
mnFkDpsAuthorizationStatusId = SDataConstantsSys.TRNS_ST_DPS_AUTHORN_AUTHORN;
}
else {
mbIsAuthorized = false;
mnFkDpsAuthorizationStatusId = SDataConstantsSys.TRNS_ST_DPS_AUTHORN_PENDING;
}
mnFkUserAuthorizedId = mbIsRegistryNew ? mnFkUserNewId : mnFkUserEditId;
}
}
}
private boolean isDebitForBizPartner() {
return isDocumentSal() || isAdjustmentPur();
}
private boolean isDebitForOperations() {
return isDocumentPur() || isAdjustmentSal();
}
private boolean isDebitForTaxes(int taxType) {
return isDocumentPur() && taxType == SModSysConsts.FINS_TP_TAX_CHARGED ||
isDocumentSal() && taxType == SModSysConsts.FINS_TP_TAX_RETAINED ||
isAdjustmentPur() && taxType == SModSysConsts.FINS_TP_TAX_RETAINED ||
isAdjustmentSal() && taxType == SModSysConsts.FINS_TP_TAX_CHARGED;
}
private boolean deleteRecord(java.lang.Object recordKey, boolean deleteWholeRecord, java.sql.Connection connection) throws java.lang.Exception {
SDataRecord record = new SDataRecord();
Statement statement = connection.createStatement();
if (record.read(recordKey, statement) != SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ);
}
else {
if (deleteWholeRecord) {
record.setIsRegistryEdited(true);
record.setIsDeleted(true);
record.setFkUserDeleteId(mnFkUserDeleteId);
for (SDataRecordEntry entry : record.getDbmsRecordEntries()) {
if (!entry.getIsDeleted()) {
// Delete aswell all non-deleted entries:
entry.setIsRegistryEdited(true);
entry.setIsDeleted(true);
entry.setFkUserDeleteId(mnFkUserDeleteId);
}
}
}
else {
for (SDataRecordEntry entry : record.getDbmsRecordEntries()) {
if (!entry.getIsDeleted()) {
// Delete aswell all non-deleted entries:
if (moDbmsDataBookkeepingNumber != null) {
if (entry.getFkBookkeepingYearId_n() == moDbmsDataBookkeepingNumber.getPkYearId() && entry.getFkBookkeepingNumberId_n() == moDbmsDataBookkeepingNumber.getPkNumberId()) {
entry.setIsRegistryEdited(true);
entry.setIsDeleted(true);
entry.setFkUserDeleteId(mnFkUserDeleteId);
}
}
else {
if (isDocument()) {
if (entry.getFkDpsYearId_n() == mnPkYearId && entry.getFkDpsDocId_n() == mnPkDocId) {
entry.setIsRegistryEdited(true);
entry.setIsDeleted(true);
entry.setFkUserDeleteId(mnFkUserDeleteId);
}
}
else {
if (entry.getFkDpsAdjustmentYearId_n() == mnPkYearId && entry.getFkDpsAdjustmentDocId_n() == mnPkDocId) {
entry.setIsRegistryEdited(true);
entry.setIsDeleted(true);
entry.setFkUserDeleteId(mnFkUserDeleteId);
}
}
}
}
}
}
if (record.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE);
}
if (moDbmsDataBookkeepingNumber != null && !moDbmsDataBookkeepingNumber.getIsDeleted()) {
moDbmsDataBookkeepingNumber.setIsDeleted(true);
moDbmsDataBookkeepingNumber.setFkUserDeleteId(mnFkUserDeleteId);
if (moDbmsDataBookkeepingNumber.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE);
}
}
}
return true;
}
private void deleteLinks(java.sql.Statement statement) throws java.sql.SQLException {
String sql = "";
sql = "DELETE FROM trn_dps_dps_supply WHERE id_src_year = " + mnPkYearId + " AND id_src_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_dps_supply WHERE id_des_year = " + mnPkYearId + " AND id_des_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_dps_adj WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_dps_adj WHERE id_adj_year = " + mnPkYearId + " AND id_adj_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_riss WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_riss WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_repl WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_repl WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_iog_chg WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dps_iog_war WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dsm_ety WHERE fid_src_dps_year_n = " + mnPkYearId + " AND fid_src_dps_doc_n = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM trn_dsm_ety WHERE fid_des_dps_year_n = " + mnPkYearId + " AND fid_des_dps_doc_n = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM mkt_comms_pay_ety WHERE fk_year = " + mnPkYearId + " AND fk_doc = " + mnPkDocId + " ";
statement.execute(sql);
sql = "DELETE FROM mkt_comms WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " ";
statement.execute(sql);
}
private void clearEntryDeliveryReferences(java.sql.Statement statement) throws java.sql.SQLException {
String sql = "UPDATE trn_dps_ety SET con_prc_year = 0, con_prc_mon = 0 WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId;
statement.execute(sql);
}
private java.lang.String getAccRecordType() {
String type = "";
int[] docClassKey = new int[] { mnFkDpsCategoryId, mnFkDpsClassId };
if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC)) {
type = SDataConstantsSys.FINU_TP_REC_PUR;
}
else if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ)) {
type = SDataConstantsSys.FINU_TP_REC_PUR;
}
else if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC)) {
type = SDataConstantsSys.FINU_TP_REC_SAL;
}
else if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ)) {
type = SDataConstantsSys.FINU_TP_REC_SAL;
}
return type;
}
private java.lang.Object createAccRecordKey(java.sql.Statement statement) throws java.lang.Exception {
int[] period = null;
Object[] key = null;
SDataBizPartnerBranch branch = new SDataBizPartnerBranch();
if (branch.read(new int[] { mnFkCompanyBranchId }, statement) != SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
period = SLibTimeUtilities.digestYearMonth(mtDate);
key = new Object[5];
key[0] = period[0];
key[1] = period[1];
key[2] = branch.getDbmsDataCompanyBranchBkc().getPkBookkepingCenterId();
key[3] = getAccRecordType();
key[4] = 0;
}
return key;
}
private erp.mfin.data.SDataRecordEntry createAccRecordEntry(java.lang.String idAccount, java.lang.String idCostCenter,
int[] keyAccMoveSubclass, int[] keySysAccountType, int[] keySysMoveType, int[] keySysMoveTypeXXX, int[] keyAuxDps_n, int[] keyCashAccount_n) {
SDataRecordEntry entry = new SDataRecordEntry();
entry.setPkYearId((Integer) ((Object[]) moDbmsRecordKey)[0]);
entry.setPkPeriodId((Integer) ((Object[]) moDbmsRecordKey)[1]);
entry.setPkBookkeepingCenterId((Integer) ((Object[]) moDbmsRecordKey)[2]);
entry.setPkRecordTypeId((String) ((Object[]) moDbmsRecordKey)[3]);
entry.setPkNumberId((Integer) ((Object[]) moDbmsRecordKey)[4]);
//entry.setPkEntryId(...); // will be set on save
entry.setConcept("");
entry.setReference("");
entry.setIsReferenceTax(false);
entry.setDebit(0.0);
entry.setCredit(0.0);
entry.setExchangeRate(mdExchangeRate);
entry.setExchangeRateSystem(mdExchangeRateSystem);
entry.setDebitCy(0.0);
entry.setCreditCy(0.0);
entry.setUnits(0.0);
entry.setSortingPosition(0);
entry.setIsSystem(true);
entry.setIsDeleted(false);
entry.setFkAccountIdXXX(idAccount);
entry.setFkAccountingMoveTypeId(keyAccMoveSubclass[0]);
entry.setFkAccountingMoveClassId(keyAccMoveSubclass[1]);
entry.setFkAccountingMoveSubclassId(keyAccMoveSubclass[2]);
entry.setFkSystemMoveClassId(keySysMoveType[0]);
entry.setFkSystemMoveTypeId(keySysMoveType[1]);
entry.setFkSystemAccountClassId(keySysAccountType[0]);
entry.setFkSystemAccountTypeId(keySysAccountType[1]);
entry.setFkSystemMoveCategoryIdXXX(keySysMoveTypeXXX[0]);
entry.setFkSystemMoveTypeIdXXX(keySysMoveTypeXXX[1]);
entry.setFkCurrencyId(mnFkCurrencyId);
entry.setFkCostCenterIdXXX_n(idCostCenter);
entry.setFkCheckWalletId_n(SLibConsts.UNDEFINED);
entry.setFkCheckId_n(SLibConsts.UNDEFINED);
entry.setFkBizPartnerId_nr(mnFkBizPartnerId_r);
entry.setFkBizPartnerBranchId_n(mnFkBizPartnerBranchId);
entry.setFkReferenceCategoryId_n(SLibConsts.UNDEFINED);
entry.setFkCompanyBranchId_n(keyCashAccount_n == null ? 0 : keyCashAccount_n[0]);
entry.setFkEntityId_n(keyCashAccount_n == null ? 0 : keyCashAccount_n[1]);
entry.setFkTaxBasicId_n(SLibConsts.UNDEFINED);
entry.setFkTaxId_n(SLibConsts.UNDEFINED);
entry.setFkYearId_n(SLibConsts.UNDEFINED);
if (isDocument()) {
entry.setFkDpsYearId_n(mnPkYearId);
entry.setFkDpsDocId_n(mnPkDocId);
entry.setFkDpsAdjustmentYearId_n(SLibConsts.UNDEFINED);
entry.setFkDpsAdjustmentDocId_n(SLibConsts.UNDEFINED);
}
else {
entry.setFkDpsYearId_n(keyAuxDps_n[0]);
entry.setFkDpsDocId_n(keyAuxDps_n[1]);
entry.setFkDpsAdjustmentYearId_n(mnPkYearId);
entry.setFkDpsAdjustmentDocId_n(mnPkDocId);
}
entry.setFkDiogYearId_n(SLibConsts.UNDEFINED);
entry.setFkDiogDocId_n(SLibConsts.UNDEFINED);
entry.setFkMfgYearId_n(SLibConsts.UNDEFINED);
entry.setFkMfgOrdId_n(SLibConsts.UNDEFINED);
entry.setFkCostGicId_n(SLibConsts.UNDEFINED);
entry.setFkPayrollFormerId_n(SLibConsts.UNDEFINED);
entry.setFkPayrollId_n(SLibConsts.UNDEFINED);
entry.setFkItemId_n(SLibConsts.UNDEFINED);
entry.setFkItemAuxId_n(SLibConsts.UNDEFINED);
entry.setFkUnitId_n(SLibConsts.UNDEFINED);
entry.setFkBookkeepingYearId_n(moDbmsDataBookkeepingNumber == null ? 0 : moDbmsDataBookkeepingNumber.getPkYearId());
entry.setFkBookkeepingNumberId_n(moDbmsDataBookkeepingNumber == null ? 0 : moDbmsDataBookkeepingNumber.getPkNumberId());
if (mbIsRegistryNew) {
entry.setFkUserNewId(mnFkUserNewId);
entry.setFkUserEditId(mnFkUserNewId);
}
else {
entry.setFkUserNewId(mnFkUserEditId);
entry.setFkUserEditId(mnFkUserEditId);
}
return entry;
}
private boolean testDeletion(java.sql.Connection poConnection, java.lang.String psMsg, int pnAction) throws java.sql.SQLException, java.lang.Exception {
int i = 0;
int[] anPeriodKey = null;
double dBalance;
double dBalanceCy;
String sSql = "";
String sMsg = psMsg;
String sMsgAux = "";
Statement oStatement = null;
ResultSet oResultSet = null;
DecimalFormat oDecimalFormat = new DecimalFormat("$ #,##0.00");
CallableStatement oCallableStatement = null;
if (pnAction == SDbConsts.ACTION_DELETE && mbIsDeleted) {
mnDbmsErrorId = 1;
msDbmsError = sMsg + "¡El documento ya está eliminado!";
throw new Exception(msDbmsError);
}
else if (pnAction == SDbConsts.ACTION_ANNUL && mnFkDpsStatusId == SDataConstantsSys.TRNS_ST_DPS_ANNULED) {
mnDbmsErrorId = 2;
msDbmsError = sMsg + "¡El documento ya está anulado!";
throw new Exception(msDbmsError);
}
else if (mbIsSystem) {
mnDbmsErrorId = 11;
msDbmsError = sMsg + "¡El documento es de sistema!";
throw new Exception(msDbmsError);
}
else if (mbIsAudited) {
mnDbmsErrorId = 12;
msDbmsError = sMsg + "¡El documento está auditado!";
throw new Exception(msDbmsError);
}
else if (mbIsAuthorized) {
mnDbmsErrorId = 13;
msDbmsError = sMsg + "¡El documento está autorizado!";
throw new Exception(msDbmsError);
}
else if (pnAction == SDbConsts.ACTION_DELETE && moDbmsDataCfd != null && moDbmsDataCfd.isStamped()) {
mnDbmsErrorId = 21;
msDbmsError = sMsg + "¡El documento está timbrado!";
throw new Exception(msDbmsError);
}
else if (moDbmsDataCfd != null && !mbAuxIsValidate && moDbmsDataCfd.getIsProcessingWebService()) {
mnDbmsErrorId = 22;
msDbmsError = sMsg + "¡" + SCfdConsts.ERR_MSG_PROCESSING_WEB_SERVICE + "!";
throw new Exception(msDbmsError);
}
else if (moDbmsDataCfd != null && !mbAuxIsValidate && pnAction != SDbConsts.ACTION_ANNUL && moDbmsDataCfd.getIsProcessingStorageXml()) {
mnDbmsErrorId = 23;
msDbmsError = sMsg + "¡" + SCfdConsts.ERR_MSG_PROCESSING_XML_STORAGE + "!";
throw new Exception(msDbmsError);
}
else if (mnFkDpsStatusId != SDataConstantsSys.TRNS_ST_DPS_EMITED) {
mnDbmsErrorId = 41;
msDbmsError = sMsg + "¡El documento debe tener estatus 'emitido'!";
throw new Exception(msDbmsError);
}
else if (mnFkDpsValidityStatusId != SDataConstantsSys.TRNS_ST_DPS_VAL_EFF) {
mnDbmsErrorId = 42;
msDbmsError = sMsg + "¡El documento debe tener estatus de validez 'efectivo'!";
throw new Exception(msDbmsError);
}
else if (mbIsShipped) {
mnDbmsErrorId = 51;
msDbmsError = sMsg + "¡El documento está embarcado!";
throw new Exception(msDbmsError);
}
else {
// Check that document's date belongs to an open period:
i = 1;
anPeriodKey = SLibTimeUtilities.digestYearMonth(mtDate);
oCallableStatement = poConnection.prepareCall("{ CALL fin_year_per_st(?, ?, ?) }");
oCallableStatement.setInt(i++, anPeriodKey[0]);
oCallableStatement.setInt(i++, anPeriodKey[1]);
oCallableStatement.registerOutParameter(i++, java.sql.Types.INTEGER);
oCallableStatement.execute();
if (oCallableStatement.getBoolean(i - 1)) {
mnDbmsErrorId = 101;
msDbmsError = sMsg + "¡El período contable de la fecha del documento está cerrado!";
throw new Exception(msDbmsError);
}
if (isDocument()) {
// Check that document's balance is equal to document's value:
i = 1;
anPeriodKey = SLibTimeUtilities.digestYearMonth(mtDate);
oCallableStatement = poConnection.prepareCall("{ CALL trn_dps_bal(?, ?, ?, ?, ?, ?) }");
oCallableStatement.setInt(i++, mnPkYearId);
oCallableStatement.setInt(i++, mnPkDocId);
oCallableStatement.setInt(i++, getAccSysTypeIdBizPartnerXXX());
oCallableStatement.registerOutParameter(i++, java.sql.Types.DECIMAL);
oCallableStatement.registerOutParameter(i++, java.sql.Types.DECIMAL);
oCallableStatement.registerOutParameter(i++, java.sql.Types.SMALLINT);
oCallableStatement.execute();
dBalance = oCallableStatement.getDouble(i - 3);
dBalanceCy = oCallableStatement.getDouble(i - 2);
if (isDocumentPur()) {
dBalance *= -1d;
dBalanceCy *= -1d;
}
if (dBalance != mdTotal_r) {
mnDbmsErrorId = 101;
msDbmsError = sMsg + "¡El saldo del documento en la moneda local, " + oDecimalFormat.format(dBalance) + ", " +
"es distinto al total del mismo, " + oDecimalFormat.format(mdTotal_r) + "!";
throw new Exception(msDbmsError);
}
if (dBalanceCy != mdTotalCy_r) {
mnDbmsErrorId = 101;
msDbmsError = sMsg + "¡El saldo del documento en la moneda del documento, " + oDecimalFormat.format(dBalanceCy) + ", " +
"es distinto al total del mismo, " + oDecimalFormat.format(mdTotalCy_r) + "!";
throw new Exception(msDbmsError);
}
}
oStatement = poConnection.createStatement();
for (i = 201; i <= 224; i++) {
switch (i) {
case 201:
sSql = "SELECT count(*) AS f_count FROM trn_dps_dps_supply WHERE id_src_year = " + mnPkYearId + " AND id_src_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento tiene vínculo(s) con otro(s) documento(s) como origen!";
break;
case 203:
sSql = "SELECT count(*) AS f_count FROM trn_dps_dps_adj WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento está asociado con otro documento de ajuste!";
break;
case 205:
sSql = "SELECT count(*) AS f_count FROM trn_diog WHERE fid_dps_year_n = " + mnPkYearId + " AND fid_dps_doc_n = " + mnPkDocId + " AND b_del = 0 ";
sMsgAux = "¡El documento está asociado con un documento de entradas y salidas de mercancías!";
break;
case 206:
sSql = "SELECT count(*) AS f_count " +
"FROM trn_diog AS d " +
"INNER JOIN trn_diog_ety AS de ON d.id_year = de.id_year AND d.id_doc = de.id_doc " +
"WHERE de.fid_dps_year_n = " + mnPkYearId + " AND de.fid_dps_doc_n = " + mnPkDocId + " AND de.fid_dps_adj_year_n IS NULL AND de.fid_dps_adj_doc_n IS NULL AND de.b_del = 0 AND d.b_del = 0 ";
sMsgAux = "¡El documento está asociado con un surtido de almacén!";
break;
case 207:
sSql = "SELECT count(*) AS f_count " +
"FROM trn_diog AS d " +
"INNER JOIN trn_diog_ety AS de ON d.id_year = de.id_year AND d.id_doc = de.id_doc " +
"WHERE de.fid_dps_year_n = " + mnPkYearId + " AND de.fid_dps_doc_n = " + mnPkDocId + " AND de.fid_dps_adj_year_n IS NOT NULL AND de.fid_dps_adj_doc_n IS NOT NULL AND de.b_del = 0 AND d.b_del = 0 ";
sMsgAux = "¡El documento está asociado con una devolución de almacén como documento!";
break;
case 208:
sSql = "SELECT count(*) AS f_count " +
"FROM trn_diog AS d " +
"INNER JOIN trn_diog_ety AS de ON d.id_year = de.id_year AND d.id_doc = de.id_doc " +
"WHERE de.fid_dps_adj_year_n = " + mnPkYearId + " AND de.fid_dps_adj_doc_n = " + mnPkDocId + " AND de.b_del = 0 AND d.b_del = 0 ";
sMsgAux = "¡El documento está asociado con una devolución de almacén como documento de ajuste!";
break;
case 209:
sSql = "SELECT count(*) AS f_count " +
"FROM mkt_comms " +
"WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " AND b_del = 0 ";
sMsgAux = "¡El documento está asociado con un documento de comisiones!";
break;
case 210:
// Not longer needed since September 2014, due to new commissions tables.
break;
case 211:
sSql = "SELECT count(*) AS f_count FROM trn_dps_riss WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento ha sido reimpreso!";
break;
case 212:
sSql = "SELECT count(*) AS f_count FROM trn_dps_riss WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento es el reemplazo de otro documento!";
break;
case 213:
sSql = "SELECT count(*) AS f_count FROM trn_dps_repl WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento ha sido sustituído!";
break;
case 214:
sSql = "SELECT count(*) AS f_count FROM trn_dps_repl WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento es la sustitución de otro documento!";
break;
case 215:
sSql = "SELECT count(*) AS f_count FROM trn_dps_iog_chg WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento está asociado con un cambio de compras-ventas!";
break;
case 216:
sSql = "SELECT count(*) AS f_count FROM trn_dps_iog_war WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
sMsgAux = "¡El documento está asociado con una garantía de compras-ventas!";
break;
case 217:
sSql = "SELECT count(*) AS f_count FROM trn_dsm_ety WHERE fid_src_dps_year_n = " + mnPkYearId + " AND fid_src_dps_doc_n = " + mnPkDocId + " AND b_del = 0 ";
sMsgAux = "¡El documento está asociado con un movimiento de asociado de negocios como origen!";
break;
case 218:
sSql = "SELECT count(*) AS f_count FROM trn_dsm_ety WHERE fid_des_dps_year_n = " + mnPkYearId + " AND fid_des_dps_doc_n = " + mnPkDocId + " AND b_del = 0 ";
sMsgAux = "¡El documento está asociado con un movimiento de asociado de negocios como destino!";
break;
case 219:
sSql = "SELECT count(*) AS f_count " +
"FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " +
"r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " +
"r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_year_n = " + mnPkYearId + " AND re.fid_dps_doc_n = " + mnPkDocId + " AND " +
"r.id_tp_rec IN ('" + SDataConstantsSys.FINU_TP_REC_FY_OPEN + "', '" + SDataConstantsSys.FINU_TP_REC_FY_END + "') ";
sMsgAux = "¡El documento está en uso por pólizas contables de cierre o apertura de ejercicio como documento!";
break;
case 220:
sSql = "SELECT count(*) AS f_count " +
"FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " +
"r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " +
"r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_adj_year_n = " + mnPkYearId + " AND re.fid_dps_adj_doc_n = " + mnPkDocId + " AND " +
"r.id_tp_rec IN ('" + SDataConstantsSys.FINU_TP_REC_FY_OPEN + "', '" + SDataConstantsSys.FINU_TP_REC_FY_END + "') ";
sMsgAux = "¡El documento está en uso por pólizas contables de cierre o apertura de ejercicio como documento de ajuste!";
break;
case 221:
if (isDocument() || isAdjustment()) {
sSql = "SELECT count(*) AS f_count " +
"FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " +
"r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " +
"r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_year_n = " + mnPkYearId + " AND re.fid_dps_doc_n = " + mnPkDocId + " AND " +
"re.fid_tp_acc_mov <> " + getAccMvtSubclassKeyBizPartner()[0] + " ";
sMsgAux = "¡El documento está en uso por pólizas contables como documento!";
}
else {
sSql = "";
}
break;
case 222:
if (isDocument() || isAdjustment()) {
sSql = "SELECT count(*) AS f_count " +
"FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " +
"r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " +
"r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_adj_year_n = " + mnPkYearId + " AND re.fid_dps_adj_doc_n = " + mnPkDocId + " AND " +
"re.fid_tp_acc_mov <> " + getAccMvtSubclassKeyBizPartner()[0] + " ";
sMsgAux = "¡El documento está en uso por pólizas contables como documento de ajuste!";
}
else {
sSql = "";
}
break;
case 223:
sSql = "SELECT count(*) AS f_count " +
"FROM log_ship " +
"WHERE b_del = 0 AND fk_ord_year_n = " + mnPkYearId + " AND fk_ord_doc_n = " + mnPkDocId + " ";
sMsgAux = "¡El documento está asociado a un documento de embarques!";
break;
case 224:
sSql = "SELECT count(*) AS f_count " +
"FROM log_ship AS d " +
"INNER JOIN log_ship_dest_ety AS de ON d.id_ship = de.id_ship " +
"WHERE d.b_del = 0 AND de.fk_dps_year_n = " + mnPkYearId + " AND de.fk_dps_doc_n = " + mnPkDocId + " ";
sMsgAux = "¡El documento está asociado a una partida de un destino de un documento de embarques!";
break;
default:
sSql = "";
sMsgAux = "";
}
if (sSql.length() > 0) {
oResultSet = oStatement.executeQuery(sSql);
if (oResultSet.next() && oResultSet.getInt("f_count") > 0) {
mnDbmsErrorId = i;
msDbmsError = sMsg + sMsgAux;
throw new Exception(msDbmsError);
}
}
}
}
return true; // if this line is reached, no errors were found
}
private boolean testRevertDeletion(java.lang.String psMsg, int pnAction) throws java.sql.SQLException, java.lang.Exception {
if (pnAction == SDbConsts.ACTION_DELETE && !mbIsDeleted) {
mnDbmsErrorId = 2;
msDbmsError = psMsg + "El documento ya está desmarcado como eliminado.";
throw new Exception(msDbmsError);
}
else if (pnAction == SDbConsts.ACTION_ANNUL && mnFkDpsStatusId != SDataConstantsSys.TRNS_ST_DPS_ANNULED) {
mnDbmsErrorId = 1;
msDbmsError = psMsg + "El documento ya está desmarcado como anulado.";
throw new Exception(msDbmsError);
}
return true; // if this line is reached, no errors were found
}
private void calculateDpsTotal(erp.client.SClientInterface piClient_n, int pnDecs) throws SQLException, Exception {
double dSubtotalProvisional = 0;
double dDiscountDoc = 0;
double dSubtotal = 0;
double dTaxCharged = 0;
double dTaxRetained = 0;
double dTotal = 0;
double dCommissions = 0;
double dDifference = 0;
SSessionItem oSessionItem = null;
mdSubtotalProvisionalCy_r = 0;
mdDiscountDocCy_r = 0;
mdSubtotalCy_r = 0;
mdTaxChargedCy_r = 0;
mdTaxRetainedCy_r = 0;
mdTotalCy_r = 0;
mdCommissionsCy_r = 0;
if (piClient_n != null) {
pnDecs = piClient_n.getSessionXXX().getParamsErp().getDecimalsValue();
}
else if (pnDecs == 0) {
pnDecs = 2;
}
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (!entry.getIsDeleted()) {
if (piClient_n != null) {
oSessionItem = ((SSessionCustom) piClient_n.getSession().getSessionCustom()).getSessionItem(entry.getFkItemId());
if (oSessionItem.getFkUnitAlternativeTypeId() != SDataConstantsSys.ITMU_TP_UNIT_NA && oSessionItem.getUnitAlternativeBaseEquivalence() == 0) {
entry.setAuxPreserveQuantity(true);
}
entry.calculateTotal(piClient_n, mtDate,
mnFkTaxIdentityEmisorTypeId, mnFkTaxIdentityReceptorTypeId,
mbIsDiscountDocPercentage, mdDiscountDocPercentage, mdExchangeRate);
}
if (entry.isAccountable()) {
mdSubtotalProvisionalCy_r += entry.getSubtotalProvisionalCy_r();
mdDiscountDocCy_r += entry.getDiscountDocCy();
mdSubtotalCy_r += entry.getSubtotalCy_r();
mdTaxChargedCy_r += entry.getTaxChargedCy_r();
mdTaxRetainedCy_r += entry.getTaxRetainedCy_r();
mdTotalCy_r += entry.getTotalCy_r();
mdCommissionsCy_r += entry.getCommissionsCy_r();
dSubtotalProvisional += entry.getSubtotalProvisional_r();
dDiscountDoc += entry.getDiscountDoc();
dSubtotal += entry.getSubtotal_r();
dTaxCharged += entry.getTaxCharged_r();
dTaxRetained += entry.getTaxRetained_r();
dTotal += entry.getTotal_r();
dCommissions += entry.getCommissions_r();
}
}
}
/*
* DOCUMENT'S DOMESTIC CURRENCY VALUE CALCULATION NOTES:
* Total value of document in domestic currency must be calculated as following,
* in order to prevent decimal differences due to exchange rate when document
* was emited in foreign currencies.
*/
// Total:
mdTotal_r = SLibUtilities.round(mdTotalCy_r * mdExchangeRate, pnDecs);
// Taxes:
mdTaxCharged_r = dTaxCharged;
mdTaxRetained_r = dTaxRetained;
// Subtotal:
mdSubtotal_r = SLibUtilities.round(mdTotal_r - mdTaxCharged_r + mdTaxRetained_r, pnDecs);
mdDiscountDoc_r = SLibUtilities.round(mdDiscountDocCy_r * mdExchangeRate, pnDecs);
mdSubtotalProvisional_r = SLibUtilities.round(mdSubtotal_r + mdDiscountDoc_r, pnDecs);
// Commissions:
mdCommissions_r = SLibUtilities.round(mdCommissionsCy_r * mdExchangeRate, pnDecs);
// Adjust any exchange rate difference:
dDifference = SLibUtilities.round(mdSubtotal_r - dSubtotal, pnDecs);
if (dDifference != 0) {
SDataDpsEntry greaterEntry = null;
// Find greater document entry:
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
if (greaterEntry == null) {
greaterEntry = entry;
}
else {
if (entry.getSubtotal_r() > greaterEntry.getSubtotal_r()) {
greaterEntry = entry;
}
}
}
}
// Adjust decimal differences in domestic currency:
if (greaterEntry != null) {
greaterEntry.setIsRegistryEdited(true);
greaterEntry.setSubtotal_r(SLibUtilities.round(greaterEntry.getSubtotal_r() + dDifference, pnDecs));
greaterEntry.setSubtotalProvisional_r(SLibUtilities.round(greaterEntry.getSubtotalProvisional_r() + dDifference, pnDecs));
}
}
}
private int getAccSysTypeIdBizPartnerXXX() {
int id = SLibConsts.UNDEFINED;
if (isDocumentPur() || isAdjustmentPur()) {
id = SDataConstantsSys.FINS_TP_ACC_SYS_SUP;
}
else if (isDocumentSal() || isAdjustmentSal()) {
id = SDataConstantsSys.FINS_TP_ACC_SYS_CUS;
}
return id;
}
private int[] getSysAccTypeKeyBizPartner() {
int[] key = null;
if (isDocumentPur() || isAdjustmentPur()) {
key = SModSysConsts.FINS_TP_SYS_ACC_BPR_SUP_BAL;
}
else if (isDocumentSal() || isAdjustmentSal()) {
key = SModSysConsts.FINS_TP_SYS_ACC_BPR_CUS_BAL;
}
else {
key = SModSysConsts.FINS_TP_SYS_ACC_NA_NA;
}
return key;
}
private int[] getSysAccTypeKeyAccountCash(SDataAccountCash cash) {
int[] key = null;
switch (cash.getFkAccountCashCategoryId()) {
case SDataConstantsSys.FINS_CT_ACC_CASH_CASH:
key = SModSysConsts.FINS_TP_SYS_ACC_ENT_CSH_CSH;
break;
case SDataConstantsSys.FINS_CT_ACC_CASH_BANK:
key = SModSysConsts.FINS_TP_SYS_ACC_ENT_CSH_BNK;
break;
default:
}
return key;
}
private int[] getSysMvtTypeKeyBizPartnerXXX() {
int[] key = SDataConstantsSys.FINS_TP_SYS_MOV_NA;
if (isDocumentPur() || isAdjustmentPur()) {
key = SDataConstantsSys.FINS_TP_SYS_MOV_BPS_SUP;
}
else if (isDocumentSal() || isAdjustmentSal()) {
key = SDataConstantsSys.FINS_TP_SYS_MOV_BPS_CUS;
}
return key;
}
private int[] getSysMvtTypeKeyBizPartner() {
int[] key = SModSysConsts.FINS_TP_SYS_MOV_JOU_DBT;
if (isDocumentPur()) {
key = SModSysConsts.FINS_TP_SYS_MOV_PUR;
}
else if (isAdjustmentPur()) {
if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_PUR_CN)) {
key = SModSysConsts.FINS_TP_SYS_MOV_PUR_DEC;
}
else {
key = SModSysConsts.FINS_TP_SYS_MOV_PUR_INC;
}
}
else if (isDocumentSal()) {
key = SModSysConsts.FINS_TP_SYS_MOV_SAL;
}
else if (isAdjustmentSal()) {
if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_SAL_CN)) {
key = SModSysConsts.FINS_TP_SYS_MOV_SAL_DEC;
}
else {
key = SModSysConsts.FINS_TP_SYS_MOV_SAL_INC;
}
}
return key;
}
private int[] getSysMvtTypeKeyAccountCashXXX(SDataAccountCash cash) {
int[] key = null;
switch (cash.getFkAccountCashCategoryId()) {
case SDataConstantsSys.FINS_CT_ACC_CASH_CASH:
key = SDataConstantsSys.FINS_TP_SYS_MOV_CASH_CASH;
break;
case SDataConstantsSys.FINS_CT_ACC_CASH_BANK:
key = SDataConstantsSys.FINS_TP_SYS_MOV_CASH_BANK;
break;
default:
}
return key;
}
private int[] getSysMvtTypeKeyAccountCash() {
int[] key = SModSysConsts.FINS_TP_SYS_MOV_JOU_DBT;
if (isDocumentPur()) {
key = SModSysConsts.FINS_TP_SYS_MOV_MO_SUP_ADV;
}
else if (isAdjustmentPur()) {
key = SModSysConsts.FINS_TP_SYS_MOV_MI_SUP_ADV;
}
else if (isDocumentSal()) {
key = SModSysConsts.FINS_TP_SYS_MOV_MI_CUS_ADV;
}
else if (isAdjustmentSal()) {
key = SModSysConsts.FINS_TP_SYS_MOV_MO_CUS_ADV;
}
return key;
}
private int[] getSysMvtTypeKeyItemXXX() {
return SDataConstantsSys.FINS_TP_SYS_MOV_NA;
}
private int[] getSysMvtTypeKeyItem(final int adjustmentType) {
int[] key = SModSysConsts.FINS_TP_SYS_MOV_JOU_DBT;
if (isDocumentPur()) {
key = SModSysConsts.FINS_TP_SYS_MOV_PUR;
}
else if (isAdjustmentPur()) {
if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_PUR_CN)) {
key = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_PUR_DEC_DIS : SModSysConsts.FINS_TP_SYS_MOV_PUR_DEC_RET;
}
else {
key = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_PUR_INC_INC : SModSysConsts.FINS_TP_SYS_MOV_PUR_INC_ADD;
}
}
else if (isDocumentSal()) {
key = SModSysConsts.FINS_TP_SYS_MOV_SAL;
}
else if (isAdjustmentSal()) {
if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_SAL_CN)) {
key = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_SAL_DEC_DIS : SModSysConsts.FINS_TP_SYS_MOV_SAL_DEC_RET;
}
else {
key = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_SAL_INC_INC : SModSysConsts.FINS_TP_SYS_MOV_SAL_INC_ADD;
}
}
return key;
}
private int[] getSysMvtTypeKeyTaxXXX(final int taxType, final int taxAppType) {
int[] key = SDataConstantsSys.FINS_TP_SYS_MOV_NA;
if (isDocumentPur() || isAdjustmentPur()) {
if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT_PEND;
}
else {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT_PEND;
}
}
else if (isDocumentSal() || isAdjustmentSal()) {
if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT_PEND;
}
else {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT_PEND;
}
}
return key;
}
private int[] getSysMvtTypeKeyTax(final int taxType, final int taxAppType) {
int[] key = SModSysConsts.FINS_TP_SYS_MOV_JOU_DBT;
if (isDocumentPur() || isAdjustmentPur()) {
if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_DBT_PAI : SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_DBT_PEN;
}
else {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_CDT_PAI : SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_CDT_PEN;
}
}
else if (isDocumentSal() || isAdjustmentSal()) {
if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_CDT_PAI : SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_CDT_PEN;
}
else {
key = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_DBT_PAI : SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_DBT_PEN;
}
}
return key;
}
private int getAccItemTypeId(erp.mtrn.data.SDataDpsEntry entry) {
int id = SDataConstantsSys.UNDEFINED;
if (isDocumentPur()) {
id = SDataConstantsSys.FINS_TP_ACC_ITEM_PUR;
}
else if (isDocumentSal()) {
id = SDataConstantsSys.FINS_TP_ACC_ITEM_SAL;
}
else if (isAdjustmentPur()) {
id = entry.getFkDpsAdjustmentTypeId() == SDataConstantsSys.TRNS_TP_DPS_ADJ_RET ? SDataConstantsSys.FINS_TP_ACC_ITEM_PUR_ADJ_DEV : SDataConstantsSys.FINS_TP_ACC_ITEM_PUR_ADJ_DISC;
}
else if (isAdjustmentSal()) {
id = entry.getFkDpsAdjustmentTypeId() == SDataConstantsSys.TRNS_TP_DPS_ADJ_RET ? SDataConstantsSys.FINS_TP_ACC_ITEM_SAL_ADJ_DEV : SDataConstantsSys.FINS_TP_ACC_ITEM_SAL_ADJ_DISC;
}
return id;
}
/*
* Public functions
*/
public int[] getAccMvtSubclassKeyBizPartner() {
int[] moveSubclassKey = null;
if (isDocumentPur()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_PUR;
}
else if (isAdjustmentPur()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_PUR_ADJ_DISC;
}
else if (isDocumentSal()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_SAL;
}
else if (isAdjustmentSal()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_SAL_ADJ_DISC;
}
return moveSubclassKey;
}
public int[] getAccMvtSubclassKeyBizPartnerAdjustment() {
int[] moveSubclassKey = null;
if (isDocumentPur()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_PUR_ADJ_DISC;
}
else if (isDocumentSal()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_SAL_ADJ_DISC;
}
return moveSubclassKey;
}
public int[] getAccMvtSubclassKeyAccountCash() {
int[] moveSubclassKey = null;
if (isDocumentPur()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_CASH_OUT_SUP_ADV;
}
else if (isAdjustmentPur()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_CASH_IN_SUP_ADV_REF;
}
else if (isDocumentSal()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_CASH_IN_CUS_ADV;
}
else if (isAdjustmentSal()) {
moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_CASH_OUT_CUS_ADV_REF;
}
return moveSubclassKey;
}
public boolean isForSales() {
return mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_SAL;
}
public boolean isForPurchases() {
return mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_PUR;
}
public boolean isDocument() {
return isDocumentPur() || isDocumentSal();
}
public boolean isDocumentPur() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_DOC);
}
public boolean isDocumentSal() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_DOC);
}
public boolean isDocumentOrAdjustment() {
return isDocument() || isAdjustment();
}
public boolean isDocumentOrAdjustmentPur() {
return isDocumentPur() || isAdjustmentPur();
}
public boolean isDocumentOrAdjustmentSal() {
return isDocumentSal() || isAdjustmentSal();
}
public boolean isAdjustment() {
return isAdjustmentPur() || isAdjustmentSal();
}
public boolean isAdjustmentPur() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ);
}
public boolean isAdjustmentSal() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ);
}
public boolean isOrder() {
return isOrderPur() || isOrderSal();
}
public boolean isOrderPur() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_ORD);
}
public boolean isOrderSal() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_ORD);
}
public boolean isEstimate() {
return isEstimatePur() || isEstimateSal();
}
public boolean isEstimatePur() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_EST);
}
public boolean isEstimateSal() {
return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_EST);
}
public int[] getDpsCategoryKey() { return new int[] { mnFkDpsCategoryId }; }
public int[] getDpsClassKey() { return new int[] { mnFkDpsCategoryId, mnFkDpsClassId }; }
public int[] getDpsTypeKey() { return new int[] { mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId }; }
public void setPkYearId(int n) { mnPkYearId = n; }
public void setPkDocId(int n) { mnPkDocId = n; }
public void setDate(java.util.Date t) { mtDate = t; }
public void setDateDoc(java.util.Date t) { mtDateDoc = t; }
public void setDateStartCredit(java.util.Date t) { mtDateStartCredit = t; }
public void setDateShipment_n(java.util.Date t) { mtDateShipment_n = t; }
public void setDateDelivery_n(java.util.Date t) { mtDateDelivery_n = t; }
public void setDateDocLapsing_n(java.util.Date t) { mtDateDocLapsing_n = t; }
public void setDateDocDelivery_n(java.util.Date t) { mtDateDocDelivery_n = t; }
public void setNumberSeries(java.lang.String s) { msNumberSeries = s; }
public void setNumber(java.lang.String s) { msNumber = s; }
public void setNumberReference(java.lang.String s) { msNumberReference = s; }
public void setCommissionsReference(java.lang.String s) { msCommissionsReference = s; }
public void setApproveYear(int n) { mnApproveYear = n; }
public void setApproveNumber(int n) { mnApproveNumber = n; }
public void setDaysOfCredit(int n) { mnDaysOfCredit = n; }
public void setIsDiscountDocApplying(boolean b) { mbIsDiscountDocApplying = b; }
public void setIsDiscountDocPercentage(boolean b) { mbIsDiscountDocPercentage = b; }
public void setDiscountDocPercentage(double d) { mdDiscountDocPercentage = d; }
public void setSubtotalProvisional_r(double d) { mdSubtotalProvisional_r = d; }
public void setDiscountDoc_r(double d) { mdDiscountDoc_r = d; }
public void setSubtotal_r(double d) { mdSubtotal_r = d; }
public void setTaxCharged_r(double d) { mdTaxCharged_r = d; }
public void setTaxRetained_r(double d) { mdTaxRetained_r = d; }
public void setTotal_r(double d) { mdTotal_r = d; }
public void setCommissions_r(double d) { mdCommissions_r = d; }
public void setExchangeRate(double d) { mdExchangeRate = d; }
public void setExchangeRateSystem(double d) { mdExchangeRateSystem = d; }
public void setSubtotalProvisionalCy_r(double d) { mdSubtotalProvisionalCy_r = d; }
public void setDiscountDocCy_r(double d) { mdDiscountDocCy_r = d; }
public void setSubtotalCy_r(double d) { mdSubtotalCy_r = d; }
public void setTaxChargedCy_r(double d) { mdTaxChargedCy_r = d; }
public void setTaxRetainedCy_r(double d) { mdTaxRetainedCy_r = d; }
public void setTotalCy_r(double d) { mdTotalCy_r = d; }
public void setCommissionsCy_r(double d) { mdCommissionsCy_r = d; }
public void setDriver(java.lang.String s) { msDriver = s; }
public void setPlate(java.lang.String s) { msPlate = s; }
public void setTicket(java.lang.String s) { msTicket = s; }
public void setShipments(int n) { mnShipments = n; }
public void setPayments(int n) { mnPayments = n; }
public void setPaymentMethod(java.lang.String s) { msPaymentMethod = s; }
public void setPaymentAccount(java.lang.String s) { msPaymentAccount = s; }
public void setAutomaticAuthorizationRejection(int n) { mnAutomaticAuthorizationRejection = n; }
public void setIsPublic(boolean b) { mbIsPublic = b; }
public void setIsLinked(boolean b) { mbIsLinked = b; }
public void setIsClosed(boolean b) { mbIsClosed = b; }
public void setIsClosedCommissions(boolean b) { mbIsClosedCommissions = b; }
public void setIsShipped(boolean b) { mbIsShipped = b; }
public void setIsRebill(boolean b) { mbIsRebill = b; }
public void setIsAudited(boolean b) { mbIsAudited = b; }
public void setIsAuthorized(boolean b) { mbIsAuthorized = b; }
public void setIsRecordAutomatic(boolean b) { mbIsRecordAutomatic = b; }
public void setIsCopy(boolean b) { mbIsCopy = b; }
public void setIsCopied(boolean b) { mbIsCopied = b; }
public void setIsSystem(boolean b) { mbIsSystem = b; }
public void setIsDeleted(boolean b) { mbIsDeleted = b; }
public void setFkDpsCategoryId(int n) { mnFkDpsCategoryId = n; }
public void setFkDpsClassId(int n) { mnFkDpsClassId = n; }
public void setFkDpsTypeId(int n) { mnFkDpsTypeId = n; }
public void setFkPaymentTypeId(int n) { mnFkPaymentTypeId = n; }
public void setFkPaymentSystemTypeId(int n) { mnFkPaymentSystemTypeId = n; }
public void setFkDpsStatusId(int n) { mnFkDpsStatusId = n; }
public void setFkDpsValidityStatusId(int n) { mnFkDpsValidityStatusId = n; }
public void setFkDpsAuthorizationStatusId(int n) { mnFkDpsAuthorizationStatusId = n; }
public void setFkDpsAnnulationTypeId(int n) { mnFkDpsAnnulationTypeId = n; }
public void setFkDpsNatureId(int n) { mnFkDpsNatureId = n; }
public void setFkCompanyBranchId(int n) { mnFkCompanyBranchId = n; }
public void setFkFunctionalAreaId(int n) { mnFkFunctionalAreaId = n; }
public void setFkBizPartnerId_r(int n) { mnFkBizPartnerId_r = n; }
public void setFkBizPartnerBranchId(int n) { mnFkBizPartnerBranchId = n; }
public void setFkBizPartnerBranchAddressId(int n) { mnFkBizPartnerBranchAddressId = n; }
public void setFkBizPartnerAltId_r(int n) { mnFkBizPartnerAltId_r = n; }
public void setFkBizPartnerBranchAltId(int n) { mnFkBizPartnerBranchAltId = n; }
public void setFkBizPartnerBranchAddressAltId(int n) { mnFkBizPartnerBranchAddressAltId = n; }
public void setFkContactBizPartnerBranchId_n(int n) { mnFkContactBizPartnerBranchId_n = n; }
public void setFkContactContactId_n(int n) { mnFkContactContactId_n = n; }
public void setFkTaxIdentityEmisorTypeId(int n) { mnFkTaxIdentityEmisorTypeId = n; }
public void setFkTaxIdentityReceptorTypeId(int n) { mnFkTaxIdentityReceptorTypeId = n; }
public void setFkLanguajeId(int n) { mnFkLanguajeId = n; }
public void setFkCurrencyId(int n) { mnFkCurrencyId = n; }
public void setFkSalesAgentId_n(int n) { mnFkSalesAgentId_n = n; }
public void setFkSalesAgentBizPartnerId_n(int n) { mnFkSalesAgentBizPartnerId_n = n; }
public void setFkSalesSupervisorId_n(int n) { mnFkSalesSupervisorId_n = n; }
public void setFkSalesSupervisorBizPartnerId_n(int n) { mnFkSalesSupervisorBizPartnerId_n = n; }
public void setFkIncotermId(int n) { mnFkIncotermId = n; }
public void setFkSpotSourceId_n(int n) { mnFkSpotSourceId_n = n; }
public void setFkSpotDestinyId_n(int n) { mnFkSpotDestinyId_n = n; }
public void setFkModeOfTransportationTypeId(int n) { mnFkModeOfTransportationTypeId = n; }
public void setFkCarrierTypeId(int n) { mnFkCarrierTypeId = n; }
public void setFkCarrierId_n(int n) { mnFkCarrierId_n = n; }
public void setFkVehicleTypeId_n(int n) { mnFkVehicleTypeId_n = n; }
public void setFkVehicleId_n(int n) { mnFkVehicleId_n = n; }
public void setFkSourceYearId_n(int n) { mnFkSourceYearId_n = n; }
public void setFkSourceDocId_n(int n) { mnFkSourceDocId_n = n; }
public void setFkMfgYearId_n(int n) { mnFkMfgYearId_n = n; }
public void setFkMfgOrderId_n(int n) { mnFkMfgOrderId_n = n; }
public void setFkUserLinkedId(int n) { mnFkUserLinkedId = n; }
public void setFkUserClosedId(int n) { mnFkUserClosedId = n; }
public void setFkUserClosedCommissionsId(int n) { mnFkUserClosedCommissionsId = n; }
public void setFkUserShippedId(int n) { mnFkUserShippedId = n; }
public void setFkUserAuditedId(int n) { mnFkUserAuditedId = n; }
public void setFkUserAuthorizedId(int n) { mnFkUserAuthorizedId = n; }
public void setFkUserNewId(int n) { mnFkUserNewId = n; }
public void setFkUserEditId(int n) { mnFkUserEditId = n; }
public void setFkUserDeleteId(int n) { mnFkUserDeleteId = n; }
public void setUserLinkedTs(java.util.Date t) { mtUserLinkedTs = t; }
public void setUserClosedTs(java.util.Date t) { mtUserClosedTs = t; }
public void setUserClosedCommissionsTs(java.util.Date t) { mtUserClosedCommissionsTs = t; }
public void setUserShippedTs(java.util.Date t) { mtUserShippedTs = t; }
public void setUserAuditedTs(java.util.Date t) { mtUserAuditedTs = t; }
public void setUserAuthorizedTs(java.util.Date t) { mtUserAuthorizedTs = t; }
public void setUserNewTs(java.util.Date t) { mtUserNewTs = t; }
public void setUserEditTs(java.util.Date t) { mtUserEditTs = t; }
public void setUserDeleteTs(java.util.Date t) { mtUserDeleteTs = t; }
public int getPkYearId() { return mnPkYearId; }
public int getPkDocId() { return mnPkDocId; }
public java.util.Date getDate() { return mtDate; }
public java.util.Date getDateDoc() { return mtDateDoc; }
public java.util.Date getDateStartCredit() { return mtDateStartCredit; }
public java.util.Date getDateShipment_n() { return mtDateShipment_n; }
public java.util.Date getDateDelivery_n() { return mtDateDelivery_n; }
public java.util.Date getDateDocLapsing_n() { return mtDateDocLapsing_n; }
public java.util.Date getDateDocDelivery_n() { return mtDateDocDelivery_n; }
public java.lang.String getNumberSeries() { return msNumberSeries; }
public java.lang.String getNumber() { return msNumber; }
public java.lang.String getNumberReference() { return msNumberReference; }
public java.lang.String getCommissionsReference() { return msCommissionsReference; }
public int getApproveYear() { return mnApproveYear; }
public int getApproveNumber() { return mnApproveNumber; }
public int getDaysOfCredit() { return mnDaysOfCredit; }
public boolean getIsDiscountDocApplying() { return mbIsDiscountDocApplying; }
public boolean getIsDiscountDocPercentage() { return mbIsDiscountDocPercentage; }
public double getDiscountDocPercentage() { return mdDiscountDocPercentage; }
public double getSubtotalProvisional_r() { return mdSubtotalProvisional_r; }
public double getDiscountDoc_r() { return mdDiscountDoc_r; }
public double getSubtotal_r() { return mdSubtotal_r; }
public double getTaxCharged_r() { return mdTaxCharged_r; }
public double getTaxRetained_r() { return mdTaxRetained_r; }
public double getTotal_r() { return mdTotal_r; }
public double getCommissions_r() { return mdCommissions_r; }
public double getExchangeRate() { return mdExchangeRate; }
public double getExchangeRateSystem() { return mdExchangeRateSystem; }
public double getSubtotalProvisionalCy_r() { return mdSubtotalProvisionalCy_r; }
public double getDiscountDocCy_r() { return mdDiscountDocCy_r; }
public double getSubtotalCy_r() { return mdSubtotalCy_r; }
public double getTaxChargedCy_r() { return mdTaxChargedCy_r; }
public double getTaxRetainedCy_r() { return mdTaxRetainedCy_r; }
public double getTotalCy_r() { return mdTotalCy_r; }
public double getCommissionsCy_r() { return mdCommissionsCy_r; }
public java.lang.String getDriver() { return msDriver; }
public java.lang.String getPlate() { return msPlate; }
public java.lang.String getTicket() { return msTicket; }
public int getShipments() { return mnShipments; }
public int getPayments() { return mnPayments; }
public java.lang.String getPaymentMethod() { return msPaymentMethod; }
public java.lang.String getPaymentAccount() { return msPaymentAccount; }
public int getAutomaticAuthorizationRejection() { return mnAutomaticAuthorizationRejection; }
public boolean getIsPublic() { return mbIsPublic; }
public boolean getIsLinked() { return mbIsLinked; }
public boolean getIsClosed() { return mbIsClosed; }
public boolean getIsClosedCommissions() { return mbIsClosedCommissions; }
public boolean getIsShipped() { return mbIsShipped; }
public boolean getIsRebill() { return mbIsRebill; }
public boolean getIsAudited() { return mbIsAudited; }
public boolean getIsAuthorized() { return mbIsAuthorized; }
public boolean getIsRecordAutomatic() { return mbIsRecordAutomatic; }
public boolean getIsCopy() { return mbIsCopy; }
public boolean getIsCopied() { return mbIsCopied; }
public boolean getIsSystem() { return mbIsSystem; }
public boolean getIsDeleted() { return mbIsDeleted; }
public int getFkDpsCategoryId() { return mnFkDpsCategoryId; }
public int getFkDpsClassId() { return mnFkDpsClassId; }
public int getFkDpsTypeId() { return mnFkDpsTypeId; }
public int getFkPaymentTypeId() { return mnFkPaymentTypeId; }
public int getFkPaymentSystemTypeId() { return mnFkPaymentSystemTypeId; }
public int getFkDpsStatusId() { return mnFkDpsStatusId; }
public int getFkDpsValidityStatusId() { return mnFkDpsValidityStatusId; }
public int getFkDpsAuthorizationStatusId() { return mnFkDpsAuthorizationStatusId; }
public int getFkDpsAnnulationTypeId() { return mnFkDpsAnnulationTypeId; }
public int getFkDpsNatureId() { return mnFkDpsNatureId; }
public int getFkCompanyBranchId() { return mnFkCompanyBranchId; }
public int getFkFunctionalAreaId() { return mnFkFunctionalAreaId; }
public int getFkBizPartnerId_r() { return mnFkBizPartnerId_r; }
public int getFkBizPartnerBranchId() { return mnFkBizPartnerBranchId; }
public int getFkBizPartnerBranchAddressId() { return mnFkBizPartnerBranchAddressId; }
public int getFkBizPartnerAltId_r() { return mnFkBizPartnerAltId_r; }
public int getFkBizPartnerBranchAltId() { return mnFkBizPartnerBranchAltId; }
public int getFkBizPartnerBranchAddressAltId() { return mnFkBizPartnerBranchAddressAltId; }
public int getFkContactBizPartnerBranchId_n() { return mnFkContactBizPartnerBranchId_n; }
public int getFkContactContactId_n() { return mnFkContactContactId_n; }
public int getFkTaxIdentityEmisorTypeId() { return mnFkTaxIdentityEmisorTypeId; }
public int getFkTaxIdentityReceptorTypeId() { return mnFkTaxIdentityReceptorTypeId; }
public int getFkLanguajeId() { return mnFkLanguajeId; }
public int getFkCurrencyId() { return mnFkCurrencyId; }
public int getFkSalesAgentId_n() { return mnFkSalesAgentId_n; }
public int getFkSalesAgentBizPartnerId_n() { return mnFkSalesAgentBizPartnerId_n; }
public int getFkSalesSupervisorId_n() { return mnFkSalesSupervisorId_n; }
public int getFkSalesSupervisorBizPartnerId_n() { return mnFkSalesSupervisorBizPartnerId_n; }
public int getFkIncotermId() { return mnFkIncotermId; }
public int getFkSpotSourceId_n() { return mnFkSpotSourceId_n; }
public int getFkSpotDestinyId_n() { return mnFkSpotDestinyId_n; }
public int getFkModeOfTransportationTypeId() { return mnFkModeOfTransportationTypeId; }
public int getFkCarrierTypeId() { return mnFkCarrierTypeId; }
public int getFkCarrierId_n() { return mnFkCarrierId_n; }
public int getFkVehicleTypeId_n() { return mnFkVehicleTypeId_n; }
public int getFkVehicleId_n() { return mnFkVehicleId_n; }
public int getFkSourceYearId_n() { return mnFkSourceYearId_n; }
public int getFkSourceDocId_n() { return mnFkSourceDocId_n; }
public int getFkMfgYearId_n() { return mnFkMfgYearId_n; }
public int getFkMfgOrderId_n() { return mnFkMfgOrderId_n; }
public int getFkUserLinkedId() { return mnFkUserLinkedId; }
public int getFkUserClosedId() { return mnFkUserClosedId; }
public int getFkUserClosedCommissionsId() { return mnFkUserClosedCommissionsId; }
public int getFkUserShippedId() { return mnFkUserShippedId; }
public int getFkUserAuditedId() { return mnFkUserAuditedId; }
public int getFkUserAuthorizedId() { return mnFkUserAuthorizedId; }
public int getFkUserNewId() { return mnFkUserNewId; }
public int getFkUserEditId() { return mnFkUserEditId; }
public int getFkUserDeleteId() { return mnFkUserDeleteId; }
public java.util.Date getUserLinkedTs() { return mtUserLinkedTs; }
public java.util.Date getUserClosedTs() { return mtUserClosedTs; }
public java.util.Date getUserClosedCommissionsTs() { return mtUserClosedCommissionsTs; }
public java.util.Date getUserShippedTs() { return mtUserShippedTs; }
public java.util.Date getUserAuditedTs() { return mtUserAuditedTs; }
public java.util.Date getUserAuthorizedTs() { return mtUserAuthorizedTs; }
public java.util.Date getUserNewTs() { return mtUserNewTs; }
public java.util.Date getUserEditTs() { return mtUserEditTs; }
public java.util.Date getUserDeleteTs() { return mtUserDeleteTs; }
public java.util.Vector<erp.mtrn.data.SDataDpsEntry> getDbmsDpsEntries() { return mvDbmsDpsEntries; }
public java.util.Vector<erp.mtrn.data.SDataDpsNotes> getDbmsDpsNotes() { return mvDbmsDpsNotes; }
public void setDbmsRecordKey(java.lang.Object o) { moDbmsRecordKey = o; }
public void setDbmsRecordDate(java.util.Date t) { mtDbmsRecordDate = t; }
public void setDbmsCurrency(java.lang.String s) { msDbmsCurrency = s; }
public void setDbmsCurrencyKey(java.lang.String s) { msDbmsCurrencyKey = s; }
public void setAuxIsFormerRecordAutomatic(boolean b) { mbAuxIsFormerRecordAutomatic = b; }
public void setAuxFormerRecordKey(java.lang.Object o) { moAuxFormerRecordKey = o; }
public void setAuxCfdParams(erp.mtrn.data.SCfdParams o) { moAuxCfdParams = o; }
public void setAuxIsNeedCfd(boolean b) { mbAuxIsNeedCfd = b; }
public void setAuxIsValidate(boolean b) { mbAuxIsValidate = b; }
public void setDbmsDataBookkeepingNumber(erp.mfin.data.SDataBookkeepingNumber o) { moDbmsDataBookkeepingNumber = o; }
public void setDbmsDataCfd(erp.mtrn.data.SDataCfd o) { moDbmsDataCfd = o; }
public void setDbmsDataAddenda(erp.mtrn.data.SDataDpsAddenda o) { moDbmsDataAddenda = o; }
public java.lang.Object getDbmsRecordKey() { return moDbmsRecordKey; }
public java.util.Date getDbmsRecordDate() { return mtDbmsRecordDate; }
public java.lang.String getDbmsCurrency() { return msDbmsCurrency; }
public java.lang.String getDbmsCurrencyKey() { return msDbmsCurrencyKey; }
public boolean getAuxIsFormerRecordAutomatic() { return mbAuxIsFormerRecordAutomatic; }
public java.lang.Object getAuxFormerRecordKey() { return moAuxFormerRecordKey; }
public erp.mtrn.data.SCfdParams getAuxCfdParams() { return moAuxCfdParams; }
public boolean getAuxIsNeedCfd() { return mbAuxIsNeedCfd; }
public boolean getAuxIsValidate() { return mbAuxIsValidate; }
public erp.mfin.data.SDataBookkeepingNumber getDbmsDataBookkeepingNumber() { return moDbmsDataBookkeepingNumber; }
public erp.mtrn.data.SDataCfd getDbmsDataCfd() { return moDbmsDataCfd; }
public erp.mtrn.data.SDataDpsAddenda getDbmsDataAddenda() { return moDbmsDataAddenda; }
public erp.mtrn.data.SDataDpsEntry getDbmsDpsEntry(int[] pk) {
SDataDpsEntry entry = null;
for (SDataDpsEntry e : mvDbmsDpsEntries) {
if (SLibUtilities.compareKeys(pk, e.getPrimaryKey())) {
entry = e;
break;
}
}
return entry;
}
public erp.mtrn.data.SDataDpsNotes getDbmsDpsNotes(int[] pk) {
SDataDpsNotes notes = null;
for (SDataDpsNotes n : mvDbmsDpsNotes) {
if (SLibUtilities.compareKeys(pk, n.getPrimaryKey())) {
notes = n;
break;
}
}
return notes;
}
public java.lang.String getDpsNumber() {
return STrnUtils.formatDocNumber(msNumberSeries, msNumber);
}
@Override
public void setPrimaryKey(java.lang.Object pk) {
mnPkYearId = ((int[]) pk)[0];
mnPkDocId = ((int[]) pk)[1];
}
@Override
public java.lang.Object getPrimaryKey() {
return new int[] { mnPkYearId, mnPkDocId };
}
@Override
public final void reset() {
super.resetRegistry();
mnPkYearId = 0;
mnPkDocId = 0;
mtDate = null;
mtDateDoc = null;
mtDateStartCredit = null;
mtDateShipment_n = null;
mtDateDelivery_n = null;
mtDateDocLapsing_n = null;
mtDateDocDelivery_n = null;
msNumberSeries = "";
msNumber = "";
msNumberReference = "";
msCommissionsReference = "";
mnApproveYear = 0;
mnApproveNumber = 0;
mnDaysOfCredit = 0;
mbIsDiscountDocApplying = false;
mbIsDiscountDocPercentage = false;
mdDiscountDocPercentage = 0;
mdSubtotalProvisional_r = 0;
mdDiscountDoc_r = 0;
mdSubtotal_r = 0;
mdTaxCharged_r = 0;
mdTaxRetained_r = 0;
mdTotal_r = 0;
mdCommissions_r = 0;
mdExchangeRate = 0;
mdExchangeRateSystem = 0;
mdSubtotalProvisionalCy_r = 0;
mdDiscountDocCy_r = 0;
mdSubtotalCy_r = 0;
mdTaxChargedCy_r = 0;
mdTaxRetainedCy_r = 0;
mdTotalCy_r = 0;
mdCommissionsCy_r = 0;
msDriver = "";
msPlate = "";
msTicket = "";
mnShipments = 0;
mnPayments = 0;
msPaymentMethod = "";
msPaymentAccount = "";
mnAutomaticAuthorizationRejection = 0;
mbIsPublic = false;
mbIsLinked = false;
mbIsClosed = false;
mbIsClosedCommissions = false;
mbIsShipped = false;
mbIsRebill = false;
mbIsAudited = false;
mbIsAuthorized = false;
mbIsRecordAutomatic = false;
mbIsCopy = false;
mbIsCopied = false;
mbIsSystem = false;
mbIsDeleted = false;
mnFkDpsCategoryId = 0;
mnFkDpsClassId = 0;
mnFkDpsTypeId = 0;
mnFkPaymentTypeId = 0;
mnFkPaymentSystemTypeId = 0;
mnFkDpsStatusId = 0;
mnFkDpsValidityStatusId = 0;
mnFkDpsAuthorizationStatusId = 0;
mnFkDpsAnnulationTypeId = 0;
mnFkDpsNatureId = 0;
mnFkCompanyBranchId = 0;
mnFkFunctionalAreaId = 0;
mnFkBizPartnerId_r = 0;
mnFkBizPartnerBranchId = 0;
mnFkBizPartnerBranchAddressId = 0;
mnFkBizPartnerAltId_r = 0;
mnFkBizPartnerBranchAltId = 0;
mnFkBizPartnerBranchAddressAltId = 0;
mnFkContactBizPartnerBranchId_n = 0;
mnFkContactContactId_n = 0;
mnFkTaxIdentityEmisorTypeId = 0;
mnFkTaxIdentityReceptorTypeId = 0;
mnFkLanguajeId = 0;
mnFkCurrencyId = 0;
mnFkSalesAgentId_n = 0;
mnFkSalesAgentBizPartnerId_n = 0;
mnFkSalesSupervisorId_n = 0;
mnFkSalesSupervisorBizPartnerId_n = 0;
mnFkIncotermId = 0;
mnFkSpotSourceId_n = 0;
mnFkSpotDestinyId_n = 0;
mnFkModeOfTransportationTypeId = 0;
mnFkCarrierTypeId = 0;
mnFkCarrierId_n = 0;
mnFkVehicleTypeId_n = 0;
mnFkVehicleId_n = 0;
mnFkSourceYearId_n = 0;
mnFkSourceDocId_n = 0;
mnFkMfgYearId_n = 0;
mnFkMfgOrderId_n = 0;
mnFkUserLinkedId = 0;
mnFkUserClosedId = 0;
mnFkUserClosedCommissionsId = 0;
mnFkUserShippedId = 0;
mnFkUserAuditedId = 0;
mnFkUserAuthorizedId = 0;
mnFkUserNewId = 0;
mnFkUserEditId = 0;
mnFkUserDeleteId = 0;
mtUserLinkedTs = null;
mtUserClosedTs = null;
mtUserClosedCommissionsTs = null;
mtUserShippedTs = null;
mtUserAuditedTs = null;
mtUserAuthorizedTs = null;
mtUserNewTs = null;
mtUserEditTs = null;
mtUserDeleteTs = null;
mvDbmsDpsEntries.clear();
mvDbmsDpsNotes.clear();
moDbmsRecordKey = null;
mtDbmsRecordDate = null;
msDbmsCurrency = "";
msDbmsCurrencyKey = "";
mbAuxIsFormerRecordAutomatic = false;
moAuxFormerRecordKey = null;
moAuxCfdParams = null;
mbAuxIsNeedCfd = false;
moDbmsDataBookkeepingNumber = null;
moDbmsDataCfd = null;
moDbmsDataAddenda = null;
msCfdExpeditionLocality = "";
msCfdExpeditionState = "";
}
@Override
public int read(java.lang.Object pk, java.sql.Statement statement) {
int[] anKey = (int[]) pk;
int[] anMoveSubclassKey = null;
String sSql = "";
String[] asSql = null;
ResultSet oResultSet = null;
Statement oStatementAux = null;
mnLastDbActionResult = SLibConsts.UNDEFINED;
reset();
try {
sSql = "SELECT d.*, c.cur, c.cur_key FROM trn_dps AS d INNER JOIN erp.cfgu_cur AS c ON d.fid_cur = c.id_cur " +
"WHERE d.id_year = " + anKey[0] + " AND d.id_doc = " + anKey[1] + " ";
oResultSet = statement.executeQuery(sSql);
if (!oResultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_REG_FOUND_NOT);
}
else {
mnPkYearId = oResultSet.getInt("d.id_year");
mnPkDocId = oResultSet.getInt("d.id_doc");
mtDate = oResultSet.getDate("d.dt");
mtDateDoc = oResultSet.getDate("d.dt_doc");
mtDateStartCredit = oResultSet.getDate("d.dt_start_cred");
mtDateShipment_n = oResultSet.getDate("d.dt_shipment_n");
mtDateDelivery_n = oResultSet.getDate("d.dt_delivery_n");
mtDateDocLapsing_n = oResultSet.getDate("d.dt_doc_lapsing_n");
mtDateDocDelivery_n = oResultSet.getDate("d.dt_doc_delivery_n");
msNumberSeries = oResultSet.getString("d.num_ser");
msNumber = oResultSet.getString("d.num");
msNumberReference = oResultSet.getString("d.num_ref");
msCommissionsReference = oResultSet.getString("d.comms_ref");
mnApproveYear = oResultSet.getInt("d.approve_year");
mnApproveNumber = oResultSet.getInt("d.approve_num");
mnDaysOfCredit = oResultSet.getInt("d.days_cred");
mbIsDiscountDocApplying = oResultSet.getBoolean("d.b_disc_doc");
mbIsDiscountDocPercentage = oResultSet.getBoolean("d.b_disc_doc_per");
mdDiscountDocPercentage = oResultSet.getDouble("d.disc_doc_per");
mdSubtotalProvisional_r = oResultSet.getDouble("d.stot_prov_r");
mdDiscountDoc_r = oResultSet.getDouble("d.disc_doc_r");
mdSubtotal_r = oResultSet.getDouble("d.stot_r");
mdTaxCharged_r = oResultSet.getDouble("d.tax_charged_r");
mdTaxRetained_r = oResultSet.getDouble("d.tax_retained_r");
mdTotal_r = oResultSet.getDouble("d.tot_r");
mdCommissions_r = oResultSet.getDouble("d.comms_r");
mdExchangeRate = oResultSet.getDouble("d.exc_rate");
mdExchangeRateSystem = oResultSet.getDouble("d.exc_rate_sys");
mdSubtotalProvisionalCy_r = oResultSet.getDouble("d.stot_prov_cur_r");
mdDiscountDocCy_r = oResultSet.getDouble("d.disc_doc_cur_r");
mdSubtotalCy_r = oResultSet.getDouble("d.stot_cur_r");
mdTaxChargedCy_r = oResultSet.getDouble("d.tax_charged_cur_r");
mdTaxRetainedCy_r = oResultSet.getDouble("d.tax_retained_cur_r");
mdTotalCy_r = oResultSet.getDouble("d.tot_cur_r");
mdCommissionsCy_r = oResultSet.getDouble("d.comms_cur_r");
msDriver = oResultSet.getString("d.driver");
msPlate = oResultSet.getString("d.plate");
msTicket = oResultSet.getString("d.ticket");
mnShipments = oResultSet.getInt("d.shipments");
mnPayments = oResultSet.getInt("d.payments");
msPaymentMethod = oResultSet.getString("d.pay_method");
msPaymentAccount = oResultSet.getString("d.pay_account");
mnAutomaticAuthorizationRejection = oResultSet.getInt("d.aut_authorn_rej");
mbIsPublic = oResultSet.getBoolean("d.b_pub");
mbIsLinked = oResultSet.getBoolean("d.b_link");
mbIsClosed = oResultSet.getBoolean("d.b_close");
mbIsClosedCommissions = oResultSet.getBoolean("d.b_close_comms");
mbIsShipped = oResultSet.getBoolean("d.b_ship");
mbIsRebill = oResultSet.getBoolean("b_rebill");
mbIsAudited = oResultSet.getBoolean("d.b_audit");
mbIsAuthorized = oResultSet.getBoolean("d.b_authorn");
mbIsRecordAutomatic = oResultSet.getBoolean("d.b_rec_aut");
mbIsCopy = oResultSet.getBoolean("d.b_copy");
mbIsCopied = oResultSet.getBoolean("d.b_copied");
mbIsSystem = oResultSet.getBoolean("d.b_sys");
mbIsDeleted = oResultSet.getBoolean("d.b_del");
mnFkDpsCategoryId = oResultSet.getInt("d.fid_ct_dps");
mnFkDpsClassId = oResultSet.getInt("d.fid_cl_dps");
mnFkDpsTypeId = oResultSet.getInt("d.fid_tp_dps");
mnFkPaymentTypeId = oResultSet.getInt("d.fid_tp_pay");
mnFkPaymentSystemTypeId = oResultSet.getInt("d.fid_tp_pay_sys");
mnFkDpsStatusId = oResultSet.getInt("d.fid_st_dps");
mnFkDpsValidityStatusId = oResultSet.getInt("d.fid_st_dps_val");
mnFkDpsAuthorizationStatusId = oResultSet.getInt("d.fid_st_dps_authorn");
mnFkDpsAnnulationTypeId = oResultSet.getInt("fid_tp_dps_ann");
mnFkDpsNatureId = oResultSet.getInt("d.fid_dps_nat");
mnFkCompanyBranchId = oResultSet.getInt("d.fid_cob");
mnFkFunctionalAreaId = oResultSet.getInt("d.fid_func");
mnFkBizPartnerId_r = oResultSet.getInt("d.fid_bp_r");
mnFkBizPartnerBranchId = oResultSet.getInt("d.fid_bpb");
mnFkBizPartnerBranchAddressId = oResultSet.getInt("d.fid_add");
mnFkBizPartnerAltId_r = oResultSet.getInt("d.fid_bp_alt_r");
mnFkBizPartnerBranchAltId = oResultSet.getInt("d.fid_bpb_alt");
mnFkBizPartnerBranchAddressAltId = oResultSet.getInt("d.fid_add_alt");
mnFkContactBizPartnerBranchId_n = oResultSet.getInt("d.fid_con_bpb_n");
mnFkContactContactId_n = oResultSet.getInt("d.fid_con_con_n");
mnFkTaxIdentityEmisorTypeId = oResultSet.getInt("d.fid_tp_tax_idy_emir");
mnFkTaxIdentityReceptorTypeId = oResultSet.getInt("d.fid_tp_tax_idy_recr");
mnFkLanguajeId = oResultSet.getInt("d.fid_lan");
mnFkCurrencyId = oResultSet.getInt("d.fid_cur");
mnFkSalesAgentId_n = oResultSet.getInt("d.fid_sal_agt_n");
mnFkSalesAgentBizPartnerId_n = oResultSet.getInt("d.fid_sal_agt_bp_n");
mnFkSalesSupervisorId_n = oResultSet.getInt("d.fid_sal_sup_n");
mnFkSalesSupervisorBizPartnerId_n = oResultSet.getInt("d.fid_sal_sup_bp_n");
mnFkIncotermId = oResultSet.getInt("d.fid_inc");
mnFkSpotSourceId_n = oResultSet.getInt("d.fid_spot_src_n");
mnFkSpotDestinyId_n = oResultSet.getInt("d.fid_spot_des_n");
mnFkModeOfTransportationTypeId = oResultSet.getInt("d.fid_tp_mot");
mnFkCarrierTypeId = oResultSet.getInt("d.fid_tp_car");
mnFkCarrierId_n = oResultSet.getInt("d.fid_car_n");
mnFkVehicleTypeId_n = oResultSet.getInt("d.fid_tp_veh_n");
mnFkVehicleId_n = oResultSet.getInt("d.fid_veh_n");
mnFkSourceYearId_n = oResultSet.getInt("d.fid_src_year_n");
mnFkSourceDocId_n = oResultSet.getInt("d.fid_src_doc_n");
mnFkMfgYearId_n = oResultSet.getInt("d.fid_mfg_year_n");
mnFkMfgOrderId_n = oResultSet.getInt("d.fid_mfg_ord_n");
mnFkUserLinkedId = oResultSet.getInt("d.fid_usr_link");
mnFkUserClosedId = oResultSet.getInt("d.fid_usr_close");
mnFkUserClosedCommissionsId = oResultSet.getInt("d.fid_usr_close_comms");
mnFkUserShippedId = oResultSet.getInt("d.fid_usr_ship");
mnFkUserAuditedId = oResultSet.getInt("d.fid_usr_audit");
mnFkUserAuthorizedId = oResultSet.getInt("d.fid_usr_authorn");
mnFkUserNewId = oResultSet.getInt("d.fid_usr_new");
mnFkUserEditId = oResultSet.getInt("d.fid_usr_edit");
mnFkUserDeleteId = oResultSet.getInt("d.fid_usr_del");
mtUserLinkedTs = oResultSet.getTimestamp("d.ts_link");
mtUserClosedTs = oResultSet.getTimestamp("d.ts_close");
mtUserClosedCommissionsTs = oResultSet.getTimestamp("d.ts_close_comms");
mtUserShippedTs = oResultSet.getTimestamp("d.ts_ship");
mtUserAuditedTs = oResultSet.getTimestamp("d.ts_audit");
mtUserAuthorizedTs = oResultSet.getTimestamp("d.ts_authorn");
mtUserNewTs = oResultSet.getTimestamp("d.ts_new");
mtUserEditTs = oResultSet.getTimestamp("d.ts_edit");
mtUserDeleteTs = oResultSet.getTimestamp("d.ts_del");
msDbmsCurrency = oResultSet.getString("c.cur");
msDbmsCurrencyKey = oResultSet.getString("c.cur_key");
oStatementAux = statement.getConnection().createStatement();
// Read aswell document notes:
sSql = "SELECT id_year, id_doc, id_nts FROM trn_dps_nts " +
"WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " " +
"ORDER BY id_year, id_doc, id_nts ";
oResultSet = statement.executeQuery(sSql);
while (oResultSet.next()) {
SDataDpsNotes note = new SDataDpsNotes();
if (note.read(new int[] { oResultSet.getInt("id_year"), oResultSet.getInt("id_doc"), oResultSet.getInt("id_nts") }, oStatementAux) != SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
mvDbmsDpsNotes.add(note);
}
}
// Read aswell document entries:
sSql = "SELECT id_year, id_doc, id_ety FROM trn_dps_ety " +
"WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " " +
"ORDER BY fid_tp_dps_ety = " + SDataConstantsSys.TRNS_TP_DPS_ETY_VIRT + ", sort_pos, id_ety ";
oResultSet = statement.executeQuery(sSql);
while (oResultSet.next()) {
SDataDpsEntry entry = new SDataDpsEntry();
if (entry.read(new int[] { oResultSet.getInt("id_year"), oResultSet.getInt("id_doc"), oResultSet.getInt("id_ety") }, oStatementAux) != SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
mvDbmsDpsEntries.add(entry);
}
}
// Check if document class requires an accounting record:
anMoveSubclassKey = getAccMvtSubclassKeyBizPartner();
if (anMoveSubclassKey != null) {
// Read aswell accounting record:
/*
* Attempt 1: try to find accounting record directly.
* Attempt 2: try to find accounting record only in non-deleted records.
* Attempt 3: if needed, try to find accounting record in all records.
*/
asSql = new String[3];
// Query for attempt 1:
asSql[0] = "SELECT fid_rec_year AS f_year, fid_rec_per AS f_per, fid_rec_bkc AS f_bkc, fid_rec_tp_rec AS f_tp_rec, fid_rec_num AS f_num " +
"FROM trn_dps_rec WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
// Query for attempts 2 and 3:
sSql = "SELECT DISTINCT id_year AS f_year, id_per AS f_per, id_bkc AS f_bkc, id_tp_rec AS f_tp_rec, id_num AS f_num FROM fin_rec_ety WHERE " +
"fid_tp_acc_mov = " + anMoveSubclassKey[0] + " AND fid_cl_acc_mov = " + anMoveSubclassKey[1] + " AND fid_cls_acc_mov = " + anMoveSubclassKey[2] + " AND " +
(isDocument() ? "fid_dps_year_n = " + mnPkYearId + " AND fid_dps_doc_n = " + mnPkDocId + " " : "fid_dps_adj_year_n = " + mnPkYearId + " AND fid_dps_adj_doc_n = " + mnPkDocId + " ");
asSql[1] = sSql + "AND b_del = 0 ORDER BY id_ety DESC ";
asSql[2] = sSql + "ORDER BY id_ety DESC ";
for (int i = 0; i < asSql.length; i++) {
oResultSet = statement.executeQuery(asSql[i]);
if (oResultSet.next()) {
moDbmsRecordKey = new Object[5];
((Object[]) moDbmsRecordKey)[0] = oResultSet.getInt("f_year");
((Object[]) moDbmsRecordKey)[1] = oResultSet.getInt("f_per");
((Object[]) moDbmsRecordKey)[2] = oResultSet.getInt("f_bkc");
((Object[]) moDbmsRecordKey)[3] = oResultSet.getString("f_tp_rec");
((Object[]) moDbmsRecordKey)[4] = oResultSet.getInt("f_num");
sSql = "SELECT dt FROM fin_rec WHERE id_year = " + ((Object[]) moDbmsRecordKey)[0] + " AND id_per = " + ((Object[]) moDbmsRecordKey)[1] + " AND " +
"id_bkc = " + ((Object[]) moDbmsRecordKey)[2] + " AND id_tp_rec = '" + ((Object[]) moDbmsRecordKey)[3] + "' AND id_num = " + ((Object[]) moDbmsRecordKey)[4] + " ";
oResultSet = statement.executeQuery(sSql);
if (!oResultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
mtDbmsRecordDate = oResultSet.getDate("dt");
mbAuxIsFormerRecordAutomatic = mbIsRecordAutomatic;
moAuxFormerRecordKey = new Object[5];
((Object[]) moAuxFormerRecordKey)[0] = ((Object[]) moDbmsRecordKey)[0];
((Object[]) moAuxFormerRecordKey)[1] = ((Object[]) moDbmsRecordKey)[1];
((Object[]) moAuxFormerRecordKey)[2] = ((Object[]) moDbmsRecordKey)[2];
((Object[]) moAuxFormerRecordKey)[3] = ((Object[]) moDbmsRecordKey)[3];
((Object[]) moAuxFormerRecordKey)[4] = ((Object[]) moDbmsRecordKey)[4];
}
break; // accounting record was found!
}
}
// Read aswell Bookkeeping Number, if any (Bookkeeping Numbers implemented from SIIE release 3.2 050.03):
sSql = "SELECT DISTINCT fid_bkk_year_n, fid_bkk_num_n "
+ "FROM fin_rec AS r "
+ "INNER JOIN fin_rec_ety AS re ON r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num "
+ "INNER JOIN fin_bkk_num AS b ON re.fid_bkk_year_n = b.id_year AND re.fid_bkk_num_n = b.id_num "
+ "WHERE NOT r.b_del AND NOT re.b_del AND re.fid_tp_acc_mov = " + anMoveSubclassKey[0] + " AND NOT b.b_del AND ";
if (isDocument()) {
sSql += "re.fid_dps_year_n = " + mnPkYearId + " AND re.fid_dps_doc_n = " + mnPkDocId + " ";
}
else {
sSql += "re.fid_dps_adj_year_n = " + mnPkYearId + " AND re.fid_dps_adj_doc_n = " + mnPkDocId + " ";
}
oResultSet = statement.executeQuery(sSql);
if (oResultSet.next()) {
moDbmsDataBookkeepingNumber = new SDataBookkeepingNumber();
if (moDbmsDataBookkeepingNumber.read(new int[] { oResultSet.getInt("fid_bkk_year_n"), oResultSet.getInt("fid_bkk_num_n") }, oStatementAux) != SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
}
}
// Read aswell CFD:
sSql = "SELECT id_cfd FROM trn_cfd WHERE fid_dps_year_n = " + mnPkYearId + " AND fid_dps_doc_n = " + mnPkDocId + " ";
oResultSet = statement.executeQuery(sSql);
if (oResultSet.next()) {
moDbmsDataCfd = new SDataCfd();
if (moDbmsDataCfd.read(new int[] { oResultSet.getInt("id_cfd") }, oStatementAux)!= SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
}
// Read aswell CFD's Addenda:
sSql = "SELECT COUNT(*) FROM trn_dps_add WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " ";
oResultSet = statement.executeQuery(sSql);
if (oResultSet.next()) {
if (oResultSet.getInt(1) > 0) {
moDbmsDataAddenda = new SDataDpsAddenda();
if (moDbmsDataAddenda.read(anKey, oStatementAux)!= SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
}
}
mbIsRegistryNew = false;
mnLastDbActionResult = SLibConstants.DB_ACTION_READ_OK;
}
}
catch (java.sql.SQLException e) {
mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR;
SLibUtilities.printOutException(this, e);
}
catch (java.lang.Exception e) {
mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR;
SLibUtilities.printOutException(this, e);
}
return mnLastDbActionResult;
}
@Override
public int save(java.sql.Connection connection) {
int i = 0;
int nParam = 0;
int nSortingPosition = 0;
int nDecimals = SLibUtils.getDecimalFormatAmount().getMaximumFractionDigits();
int nTaxTypeId = SLibConsts.UNDEFINED;
int nTaxAppTypeId = SLibConsts.UNDEFINED;
int nTaxAccTypeId = SLibConsts.UNDEFINED;
int nPositionToAdjust = 0;
double dDebit = 0;
double dCredit = 0;
double dDebitCy = 0;
double dCreditCy = 0;
double dGreatestAmount = 0;
boolean isNewRecord = false;
boolean appliesPrepayment = false;
boolean appliesAdvanceBilled = false;
int[] anAccMvtSubclassKey = null;
int[] anSysAccTypeKeyBpr = null;
int[] anSysMvtTypeKeyBpr = null;
int[] anSysMvtTypeKeyBprXXX = null;
int[] anSysAccTypeKeyItem = null;
int[] anSysMvtTypeKeyItem = null;
int[] anSysMvtTypeKeyItemXXX = null;
int[] anSysAccTypeKeyTax = null;
int[] anSysMvtTypeKeyTax = null;
int[] anSysMvtTypeKeyTaxXXX = null;
String sSql = "";
String sConcept = "";
String sConceptAux = "";
String sConceptEntry = "";
String sConceptEntryAux = "";
String sAccountId = "";
Statement oStatement = null;
ResultSet oResultSet = null;
CallableStatement oCallableStatement = null;
SDataRecord oRecord = null;
SDataRecordEntry oRecordEntry = null;
SFinDpsTaxes oDpsTaxes = null;
SDataAccountCash oAccountCash = null;
SFinAccountConfig oConfigBprOp = null;
SFinAccountConfig oConfigBprAdvBill = null;
SFinAccountConfig oConfigItem = null;
SFinAmount oAmount = null;
SFinAmount oAmountBprBal = null;
SFinAmount oAmountBprPay = null;
SFinAmounts oAmounts = new SFinAmounts();
ArrayList<SFinAmount> aAmountEntries = null;
mnLastDbActionResult = SLibConsts.UNDEFINED;
try {
updateAuthorizationStatus(connection); // applys only for orders and documents
nParam = 1;
oCallableStatement = connection.prepareCall(
"{ CALL trn_dps_save(" +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?) }");
oCallableStatement.setInt(nParam++, mnPkYearId);
oCallableStatement.setInt(nParam++, mnPkDocId);
oCallableStatement.setDate(nParam++, new java.sql.Date(mtDate.getTime()));
oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDoc.getTime()));
oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateStartCredit.getTime()));
if (mtDateShipment_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateShipment_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE);
if (mtDateDelivery_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDelivery_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE);
if (mtDateDocLapsing_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDocLapsing_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE);
if (mtDateDocDelivery_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDocDelivery_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE);
oCallableStatement.setString(nParam++, msNumberSeries);
oCallableStatement.setString(nParam++, msNumber);
oCallableStatement.setString(nParam++, msNumberReference);
oCallableStatement.setString(nParam++, msCommissionsReference);
oCallableStatement.setInt(nParam++, mnApproveYear);
oCallableStatement.setInt(nParam++, mnApproveNumber);
oCallableStatement.setInt(nParam++, mnDaysOfCredit);
oCallableStatement.setBoolean(nParam++, mbIsDiscountDocApplying);
oCallableStatement.setBoolean(nParam++, mbIsDiscountDocPercentage);
oCallableStatement.setDouble(nParam++, mdDiscountDocPercentage);
oCallableStatement.setDouble(nParam++, mdSubtotalProvisional_r);
oCallableStatement.setDouble(nParam++, mdDiscountDoc_r);
oCallableStatement.setDouble(nParam++, mdSubtotal_r);
oCallableStatement.setDouble(nParam++, mdTaxCharged_r);
oCallableStatement.setDouble(nParam++, mdTaxRetained_r);
oCallableStatement.setDouble(nParam++, mdTotal_r);
oCallableStatement.setDouble(nParam++, mdCommissions_r);
oCallableStatement.setDouble(nParam++, mdExchangeRate);
oCallableStatement.setDouble(nParam++, mdExchangeRateSystem);
oCallableStatement.setDouble(nParam++, mdSubtotalProvisionalCy_r);
oCallableStatement.setDouble(nParam++, mdDiscountDocCy_r);
oCallableStatement.setDouble(nParam++, mdSubtotalCy_r);
oCallableStatement.setDouble(nParam++, mdTaxChargedCy_r);
oCallableStatement.setDouble(nParam++, mdTaxRetainedCy_r);
oCallableStatement.setDouble(nParam++, mdTotalCy_r);
oCallableStatement.setDouble(nParam++, mdCommissionsCy_r);
oCallableStatement.setString(nParam++, msDriver);
oCallableStatement.setString(nParam++, msPlate);
oCallableStatement.setString(nParam++, msTicket);
oCallableStatement.setInt(nParam++, mnShipments);
oCallableStatement.setInt(nParam++, mnPayments);
oCallableStatement.setString(nParam++, msPaymentMethod);
oCallableStatement.setString(nParam++, msPaymentAccount);
oCallableStatement.setInt(nParam++, mnAutomaticAuthorizationRejection);
oCallableStatement.setBoolean(nParam++, mbIsPublic);
oCallableStatement.setBoolean(nParam++, mbIsLinked);
oCallableStatement.setBoolean(nParam++, mbIsClosed);
oCallableStatement.setBoolean(nParam++, mbIsClosedCommissions);
oCallableStatement.setBoolean(nParam++, mbIsShipped);
oCallableStatement.setBoolean(nParam++, mbIsRebill);
oCallableStatement.setBoolean(nParam++, mbIsAudited);
oCallableStatement.setBoolean(nParam++, mbIsAuthorized);
oCallableStatement.setBoolean(nParam++, mbIsRecordAutomatic);
oCallableStatement.setBoolean(nParam++, mbIsCopy);
oCallableStatement.setBoolean(nParam++, mbIsCopied);
oCallableStatement.setBoolean(nParam++, mbIsSystem);
oCallableStatement.setBoolean(nParam++, mbIsDeleted);
oCallableStatement.setInt(nParam++, mnFkDpsCategoryId);
oCallableStatement.setInt(nParam++, mnFkDpsClassId);
oCallableStatement.setInt(nParam++, mnFkDpsTypeId);
oCallableStatement.setInt(nParam++, mnFkPaymentTypeId);
oCallableStatement.setInt(nParam++, mnFkPaymentSystemTypeId);
oCallableStatement.setInt(nParam++, mnFkDpsStatusId);
oCallableStatement.setInt(nParam++, mnFkDpsValidityStatusId);
oCallableStatement.setInt(nParam++, mnFkDpsAuthorizationStatusId);
oCallableStatement.setInt(nParam++, mnFkDpsAnnulationTypeId);
oCallableStatement.setInt(nParam++, mnFkDpsNatureId);
oCallableStatement.setInt(nParam++, mnFkCompanyBranchId);
oCallableStatement.setInt(nParam++, mnFkFunctionalAreaId);
oCallableStatement.setInt(nParam++, mnFkBizPartnerId_r);
oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchId);
oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchAddressId);
oCallableStatement.setInt(nParam++, mnFkBizPartnerAltId_r);
oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchAltId);
oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchAddressAltId);
if (mnFkContactBizPartnerBranchId_n > 0) oCallableStatement.setInt(nParam++, mnFkContactBizPartnerBranchId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
if (mnFkContactContactId_n > 0) oCallableStatement.setInt(nParam++, mnFkContactContactId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT);
oCallableStatement.setInt(nParam++, mnFkTaxIdentityEmisorTypeId);
oCallableStatement.setInt(nParam++, mnFkTaxIdentityReceptorTypeId);
oCallableStatement.setInt(nParam++, mnFkLanguajeId);
oCallableStatement.setInt(nParam++, mnFkCurrencyId);
if (mnFkSalesAgentId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesAgentId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
if (mnFkSalesAgentBizPartnerId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesAgentBizPartnerId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
if (mnFkSalesSupervisorId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesSupervisorId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
if (mnFkSalesSupervisorBizPartnerId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesSupervisorBizPartnerId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
oCallableStatement.setInt(nParam++, mnFkIncotermId);
if (mnFkSpotSourceId_n > 0) oCallableStatement.setInt(nParam++, mnFkSpotSourceId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT);
if (mnFkSpotDestinyId_n > 0) oCallableStatement.setInt(nParam++, mnFkSpotDestinyId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT);
oCallableStatement.setInt(nParam++, mnFkModeOfTransportationTypeId);
oCallableStatement.setInt(nParam++, mnFkCarrierTypeId);
if (mnFkCarrierId_n > 0) oCallableStatement.setInt(nParam++, mnFkCarrierId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
if (mnFkVehicleTypeId_n > 0) oCallableStatement.setInt(nParam++, mnFkVehicleTypeId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT);
if (mnFkVehicleId_n > 0) oCallableStatement.setInt(nParam++, mnFkVehicleId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT);
if (mnFkSourceYearId_n > 0) oCallableStatement.setInt(nParam++, mnFkSourceYearId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
if (mnFkSourceDocId_n > 0) oCallableStatement.setInt(nParam++, mnFkSourceDocId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
if (mnFkMfgYearId_n > 0) oCallableStatement.setInt(nParam++, mnFkMfgYearId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT);
if (mnFkMfgOrderId_n > 0) oCallableStatement.setInt(nParam++, mnFkMfgOrderId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER);
oCallableStatement.setInt(nParam++, mnFkUserLinkedId);
oCallableStatement.setInt(nParam++, mnFkUserClosedId);
oCallableStatement.setInt(nParam++, mnFkUserClosedCommissionsId);
oCallableStatement.setInt(nParam++, mnFkUserShippedId);
oCallableStatement.setInt(nParam++, mnFkUserAuditedId);
oCallableStatement.setInt(nParam++, mnFkUserAuthorizedId);
oCallableStatement.setInt(nParam++, mbIsRegistryNew ? mnFkUserNewId : mnFkUserEditId);
oCallableStatement.registerOutParameter(nParam++, java.sql.Types.INTEGER);
oCallableStatement.registerOutParameter(nParam++, java.sql.Types.SMALLINT);
oCallableStatement.registerOutParameter(nParam++, java.sql.Types.VARCHAR);
oCallableStatement.execute();
mnPkDocId = oCallableStatement.getInt(nParam - 3);
mnDbmsErrorId = oCallableStatement.getInt(nParam - 2);
msDbmsError = oCallableStatement.getString(nParam - 1);
if (mnDbmsErrorId != 0) {
throw new Exception(msDbmsError);
}
else {
oStatement = connection.createStatement();
oDpsTaxes = new SFinDpsTaxes(oStatement);
// 1. Obtain decimals for calculations:
sSql = "SELECT decs_val FROM erp.cfg_param_erp WHERE id_erp = 1 ";
oResultSet = oStatement.executeQuery(sSql);
if (oResultSet.next()) {
nDecimals = oResultSet.getInt("decs_val");
}
// 2. Save aswell document entries:
nSortingPosition = 0;
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.getIsRegistryNew() || entry.getIsRegistryEdited()) {
entry.setPkYearId(mnPkYearId);
entry.setPkDocId(mnPkDocId);
if (entry.getIsDeleted() || entry.getFkDpsEntryTypeId() == SDataConstantsSys.TRNS_TP_DPS_ETY_VIRT) {
entry.setSortingPosition(0);
}
else {
entry.setSortingPosition(++nSortingPosition);
}
if (entry.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP);
}
}
}
// 3. Save aswell document notes:
for (SDataDpsNotes notes : mvDbmsDpsNotes) {
if (notes.getIsRegistryNew() || notes.getIsRegistryEdited()) {
notes.setPkYearId(mnPkYearId);
notes.setPkDocId(mnPkDocId);
if (notes.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP);
}
}
}
// 4. Save aswell journal voucher if this document class requires it:
anAccMvtSubclassKey = getAccMvtSubclassKeyBizPartner();
if (anAccMvtSubclassKey != null) {
// 4.1 Prepare journal voucher (accounting record):
if (mbIsDeleted) {
// Delete aswell former journal voucher:
if (moAuxFormerRecordKey != null) {
// If document had automatic journal voucher, delete it including its header:
deleteRecord(moAuxFormerRecordKey, mbAuxIsFormerRecordAutomatic, connection);
}
}
else {
// Save aswell journal voucher:
if (moDbmsRecordKey == null) {
if (!mbIsRecordAutomatic) {
// Journal voucher is not automatic:
throw new Exception(MSG_ERR_FIN_REC_USR);
}
else {
// Journal voucher is automatic:
if (moAuxFormerRecordKey == null || !mbAuxIsFormerRecordAutomatic) {
isNewRecord = true;
moDbmsRecordKey = (Object[]) createAccRecordKey(oStatement);
}
else {
if (SLibTimeUtilities.isBelongingToPeriod(mtDate, (Integer) ((Object[]) moAuxFormerRecordKey)[0], (Integer) ((Object[]) moAuxFormerRecordKey)[1])) {
moDbmsRecordKey = moAuxFormerRecordKey;
}
else {
isNewRecord = true;
moDbmsRecordKey = (Object[]) createAccRecordKey(oStatement);
}
}
}
}
if (moAuxFormerRecordKey != null) {
// If document was previously saved, delete former accounting moves, if needed, including its header:
deleteRecord(moAuxFormerRecordKey, (mbAuxIsFormerRecordAutomatic && !mbIsRecordAutomatic) || (mbAuxIsFormerRecordAutomatic && isNewRecord), connection);
}
// 4.2 Save document's journal voucher (accounting record):
// 4.2.1 Define journal voucher's concept:
sSql = "SELECT code FROM erp.trnu_tp_dps WHERE " +
"id_ct_dps = " + mnFkDpsCategoryId + " AND id_cl_dps = " + mnFkDpsClassId + " AND id_tp_dps = " + mnFkDpsTypeId + " ";
oResultSet = oStatement.executeQuery(sSql);
if (oResultSet.next()) {
sConcept += oResultSet.getString("code") + " " + getDpsNumber() + "; ";
}
else {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
sSql = "SELECT bp_comm FROM erp.bpsu_bp WHERE id_bp = " + mnFkBizPartnerId_r + " ";
oResultSet = oStatement.executeQuery(sSql);
if (oResultSet.next()) {
sConcept += oResultSet.getString("bp_comm");
}
else {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (!entry.getIsDeleted()) {
sConceptEntry = entry.getConcept();
break;
}
}
sConceptAux = sConcept;
if (!sConceptEntry.isEmpty()) {
sConcept += "; " + sConceptEntry;
}
if (sConcept.length() > 100) {
sConcept = sConcept.substring(0, 100 - 3).trim() + "...";
}
// 4.2.2 Save journal voucher:
nSortingPosition = 0;
oRecord = new SDataRecord();
if (!isNewRecord) {
if (oRecord.read(moDbmsRecordKey, oStatement) != SLibConstants.DB_ACTION_READ_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
if (oRecord.getIsDeleted()) {
oRecord.setIsDeleted(false);
}
if (mbIsRecordAutomatic) {
oRecord.setDate(mtDate);
oRecord.setConcept(sConcept);
}
for (SDataRecordEntry entry : oRecord.getDbmsRecordEntries()) {
if (!entry.getIsDeleted()) {
nSortingPosition = entry.getSortingPosition();
}
}
}
else {
oRecord.setPrimaryKey(moDbmsRecordKey);
oRecord.setDate(mtDate);
oRecord.setConcept(sConcept);
oRecord.setIsAudited(false);
oRecord.setIsAuthorized(false);
oRecord.setIsSystem(true);
oRecord.setIsDeleted(false);
oRecord.setFkCompanyBranchId(mnFkCompanyBranchId);
oRecord.setFkCompanyBranchId_n(SLibConsts.UNDEFINED);
oRecord.setFkAccountCashId_n(SLibConsts.UNDEFINED);
if (mbIsRegistryNew) {
oRecord.setFkUserNewId(mnFkUserNewId);
oRecord.setFkUserEditId(mnFkUserNewId);
}
else {
oRecord.setFkUserNewId(mnFkUserEditId);
oRecord.setFkUserEditId(mnFkUserEditId);
}
}
if (moDbmsDataBookkeepingNumber == null || moDbmsDataBookkeepingNumber.getIsDeleted()) {
moDbmsDataBookkeepingNumber = new SDataBookkeepingNumber();
moDbmsDataBookkeepingNumber.setPkYearId(mnPkYearId);
//moDbmsDataBookkeepingNumber.setPkNumberId(...); will be set on save
moDbmsDataBookkeepingNumber.setFkUserNewId(mnFkUserNewId);
moDbmsDataBookkeepingNumber.save(connection);
}
// 4.3 Business partner's asset or liability:
// Add values:
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
if (isDocument()) { // document is an invoice
if (entry.getIsPrepayment()) {
appliesPrepayment = true;
if (entry.getQuantity() >= 0) {
if (entry.getKeyCashAccount_n() != null) {
// Increment cash account's balance:
oAmounts.addAmountForCashAccount(entry.getKeyCashAccount_n(), new SFinAmount(entry.getTotal_r(), entry.getTotalCy_r(), true, SFinAmountType.CASH_ACCOUNT, SFinMovement.INCREMENT)); // add grouping by referenced cash account
}
else {
// Increment advance billed's balance:
appliesAdvanceBilled = true;
oAmounts.addAmountForAdvanceBilled(new SFinAmount(entry.getTotal_r(), entry.getTotalCy_r(), true, SFinAmountType.ADVANCE_BILLED, SFinMovement.INCREMENT)); // add into lonely group
}
}
else {
// Decrement business partner's balance:
if (oAmountBprPay == null) {
oAmounts.getAmounts().add(oAmountBprPay = new SFinAmount(0, 0, true, SFinAmountType.UNDEFINED, SFinMovement.DECREMENT)); // in-line instantiation!
}
oAmountBprPay.addAmount(-entry.getTotal_r(), -entry.getTotalCy_r()); // only one amount per business partner
}
}
else {
// Increment business partner's balance:
if (oAmountBprBal == null) {
oAmounts.getAmounts().add(oAmountBprBal = new SFinAmount(0, 0)); // in-line instantiation!
}
oAmountBprBal.addAmount(entry.getTotal_r(), entry.getTotalCy_r()); // only one amount per business partner
}
}
else { // document is a credit note
// Decrement a business partner document's balance:
oAmounts.addAmountForDocument(entry.getKeyAuxDps(), new SFinAmount(entry.getTotal_r(), entry.getTotalCy_r())); // add grouping by referenced invoice
}
}
}
// Validate final sum of added values, adjust difference if necessary:
oAmounts.checkAmount(mdTotal_r);
// Create journal voucher entries:
oConfigBprOp = new SFinAccountConfig(SFinAccountUtilities.obtainBizPartnerAccountConfigs(
mnFkBizPartnerId_r, STrnUtils.getBizPartnerCategoryId(mnFkDpsCategoryId), oRecord.getPkBookkeepingCenterId(),
mtDate, SDataConstantsSys.FINS_TP_ACC_BP_OP, isDebitForBizPartner(), oStatement));
if (appliesAdvanceBilled) {
oConfigBprAdvBill = new SFinAccountConfig(SFinAccountUtilities.obtainBizPartnerAccountConfigs(
mnFkBizPartnerId_r, STrnUtils.getBizPartnerCategoryId(mnFkDpsCategoryId), oRecord.getPkBookkeepingCenterId(),
mtDate, SDataConstantsSys.FINS_TP_ACC_BP_ADV_BILL, isDebitForBizPartner(), oStatement));
}
anSysAccTypeKeyBpr = getSysAccTypeKeyBizPartner();
anSysMvtTypeKeyBpr = getSysMvtTypeKeyBizPartner();
anSysMvtTypeKeyBprXXX = getSysMvtTypeKeyBizPartnerXXX();
for (SFinAmount amount : oAmounts.getAmounts()) {
if (amount.IsPrepayment && amount.Movement == SFinMovement.INCREMENT) {
switch (amount.AmountType) {
case CASH_ACCOUNT: // user requested prepayment accounting into a cash account
oAccountCash = new SDataAccountCash();
oAccountCash.read(amount.KeyRefCashAccount, oStatement);
oRecordEntry = createAccRecordEntry(
oAccountCash.getFkAccountId(),
"",
getAccMvtSubclassKeyAccountCash(), getSysAccTypeKeyAccountCash(oAccountCash), getSysMvtTypeKeyAccountCash(), getSysMvtTypeKeyAccountCashXXX(oAccountCash),
null, amount.KeyRefCashAccount);
if (isDebitForBizPartner()) {
oRecordEntry.setDebit(amount.Amount);
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(amount.AmountCy);
oRecordEntry.setCreditCy(0);
}
else {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(amount.Amount);
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(amount.AmountCy);
}
oRecordEntry.setConcept(sConcept);
oRecordEntry.setSortingPosition(++nSortingPosition);
oRecord.getDbmsRecordEntries().add(oRecordEntry);
break;
case ADVANCE_BILLED: // user requested prepayment accounting into business partner pending advance payments
aAmountEntries = oConfigBprAdvBill.prorateAmount(amount);
for (i = 0; i < oConfigBprAdvBill.getAccountConfigEntries().size(); i++) {
oRecordEntry = createAccRecordEntry(
oConfigBprAdvBill.getAccountConfigEntries().get(i).getAccountId(),
oConfigBprAdvBill.getAccountConfigEntries().get(i).getCostCenterId(),
anAccMvtSubclassKey, SModSysConsts.FINS_TP_SYS_ACC_NA_NA, anSysMvtTypeKeyBpr, SDataConstantsSys.FINS_TP_SYS_MOV_NA,
null, null);
if (isDebitForBizPartner()) {
oRecordEntry.setDebit(aAmountEntries.get(i).Amount);
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(aAmountEntries.get(i).AmountCy);
oRecordEntry.setCreditCy(0);
}
else {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(aAmountEntries.get(i).Amount);
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(aAmountEntries.get(i).AmountCy);
}
oRecordEntry.setConcept(sConcept);
oRecordEntry.setSortingPosition(++nSortingPosition);
oRecord.getDbmsRecordEntries().add(oRecordEntry);
}
break;
default:
throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN + "\n(" + TXT_ADV_BILL + ")");
}
}
else {
aAmountEntries = oConfigBprOp.prorateAmount(amount);
for (i = 0; i < oConfigBprOp.getAccountConfigEntries().size(); i++) {
oRecordEntry = createAccRecordEntry(
oConfigBprOp.getAccountConfigEntries().get(i).getAccountId(),
oConfigBprOp.getAccountConfigEntries().get(i).getCostCenterId(),
anAccMvtSubclassKey, anSysAccTypeKeyBpr, anSysMvtTypeKeyBpr, anSysMvtTypeKeyBprXXX,
isAdjustment() ? amount.KeyRefDocument : null, null);
if (amount.IsPrepayment) { // decrementing prepayment entry:
if (isDebitForBizPartner()) {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(aAmountEntries.get(i).Amount);
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(aAmountEntries.get(i).AmountCy);
}
else {
oRecordEntry.setDebit(aAmountEntries.get(i).Amount);
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(aAmountEntries.get(i).AmountCy);
oRecordEntry.setCreditCy(0);
}
}
else { // ordinary entry:
if (isDebitForBizPartner()) {
oRecordEntry.setDebit(aAmountEntries.get(i).Amount);
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(aAmountEntries.get(i).AmountCy);
oRecordEntry.setCreditCy(0);
}
else {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(aAmountEntries.get(i).Amount);
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(aAmountEntries.get(i).AmountCy);
}
}
oRecordEntry.setConcept(sConcept);
oRecordEntry.setSortingPosition(++nSortingPosition);
oRecord.getDbmsRecordEntries().add(oRecordEntry);
}
}
}
// 4.4 Purchases or sales:
if (appliesPrepayment) { // prevent from reading prepayment configuration when not needed!
oConfigBprOp = new SFinAccountConfig(SFinAccountUtilities.obtainBizPartnerAccountConfigs(
mnFkBizPartnerId_r, STrnUtils.getBizPartnerCategoryId(mnFkDpsCategoryId), oRecord.getPkBookkeepingCenterId(),
mtDate, SDataConstantsSys.FINS_TP_ACC_BP_PAY, isDebitForBizPartner(), oStatement));
}
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
if (entry.getIsPrepayment()) {
// Document entry for prepayment:
if (entry.getQuantity() >= 0) {
oAmount = new SFinAmount(entry.getSubtotal_r(), entry.getSubtotalCy_r());
}
else {
oAmount = new SFinAmount(-entry.getSubtotal_r(), -entry.getSubtotalCy_r());
}
aAmountEntries = oConfigBprOp.prorateAmount(oAmount);
for (i = 0; i < oConfigBprOp.getAccountConfigEntries().size(); i++) {
oRecordEntry = createAccRecordEntry(
oConfigBprOp.getAccountConfigEntries().get(i).getAccountId(),
oConfigBprOp.getAccountConfigEntries().get(i).getCostCenterId(),
anAccMvtSubclassKey, anSysAccTypeKeyBpr, anSysMvtTypeKeyBpr, anSysMvtTypeKeyBprXXX,
null, null);
oRecordEntry.setFkDpsYearId_n(SLibConsts.UNDEFINED);
oRecordEntry.setFkDpsDocId_n(SLibConsts.UNDEFINED);
if (entry.getQuantity() >= 0) {
if (isDebitForOperations()) {
oRecordEntry.setDebit(aAmountEntries.get(i).Amount);
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(aAmountEntries.get(i).AmountCy);
oRecordEntry.setCreditCy(0);
}
else {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(aAmountEntries.get(i).Amount);
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(aAmountEntries.get(i).AmountCy);
}
}
else {
if (isDebitForOperations()) {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(aAmountEntries.get(i).Amount);
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(aAmountEntries.get(i).AmountCy);
}
else {
oRecordEntry.setDebit(aAmountEntries.get(i).Amount);
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(aAmountEntries.get(i).AmountCy);
oRecordEntry.setCreditCy(0);
}
}
oRecordEntry.setConcept(sConcept);
oRecordEntry.setSortingPosition(++nSortingPosition);
oRecord.getDbmsRecordEntries().add(oRecordEntry);
}
}
else {
// Standard document entry:
oConfigItem = new SFinAccountConfig(SFinAccountUtilities.obtainItemAccountConfigs(
entry.getFkItemRefId_n() != SLibConsts.UNDEFINED ? entry.getFkItemRefId_n() : entry.getFkItemId(), oRecord.getPkBookkeepingCenterId(),
mtDate, getAccItemTypeId(entry), isDebitForOperations(), oStatement));
sConceptEntryAux = sConceptAux;
anSysAccTypeKeyItem = SModSysConsts.FINS_TP_SYS_ACC_NA_NA;
anSysMvtTypeKeyItem = getSysMvtTypeKeyItem(entry.getFkDpsAdjustmentTypeId());
anSysMvtTypeKeyItemXXX = getSysMvtTypeKeyItemXXX();
aAmountEntries = oConfigItem.prorateAmount(new SFinAmount(entry.getSubtotal_r(), entry.getSubtotalCy_r()));
for (i = 0; i < oConfigItem.getAccountConfigEntries().size(); i++) {
oRecordEntry = createAccRecordEntry(
oConfigItem.getAccountConfigEntries().get(i).getAccountId(),
!entry.getFkCostCenterId_n().isEmpty() ? entry.getFkCostCenterId_n() : oConfigItem.getAccountConfigEntries().get(i).getCostCenterId(),
anAccMvtSubclassKey, anSysAccTypeKeyItem, anSysMvtTypeKeyItem, anSysMvtTypeKeyItemXXX,
isAdjustment() ? entry.getKeyAuxDps() : null, null);
if (isDebitForOperations()) {
oRecordEntry.setDebit(aAmountEntries.get(i).Amount);
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(aAmountEntries.get(i).AmountCy);
oRecordEntry.setCreditCy(0);
}
else {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(aAmountEntries.get(i).Amount);
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(aAmountEntries.get(i).AmountCy);
}
sConceptEntryAux += (entry.getConcept().length() <= 0 ? "" : "; " + entry.getConcept());
if (sConceptEntryAux.length() > 100) {
sConceptEntryAux = sConceptEntryAux.substring(0, 100 - 3).trim() + "...";
}
oRecordEntry.setConcept(sConceptEntryAux);
oRecordEntry.setSortingPosition(++nSortingPosition);
if (entry.getFkItemRefId_n() == SLibConsts.UNDEFINED) {
oRecordEntry.setUnits(entry.getOriginalQuantity());
oRecordEntry.setFkItemId_n(entry.getFkItemId());
oRecordEntry.setFkUnitId_n(entry.getFkOriginalUnitId());
oRecordEntry.setFkItemAuxId_n(SLibConsts.UNDEFINED);
}
else {
oRecordEntry.setUnits(0);
oRecordEntry.setFkItemId_n(entry.getFkItemRefId_n());
oRecordEntry.setFkUnitId_n(SModSysConsts.ITMU_UNIT_NA);
oRecordEntry.setFkItemAuxId_n(entry.getFkItemId());
}
oRecord.getDbmsRecordEntries().add(oRecordEntry);
}
}
for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) {
if (entry.getQuantity() >= 0) {
oAmount = new SFinAmount(tax.getTax(), tax.getTaxCy(), entry.getIsPrepayment(), SFinAmountType.UNDEFINED, SFinMovement.INCREMENT);
}
else {
oAmount = new SFinAmount(-tax.getTax(), -tax.getTaxCy(), entry.getIsPrepayment(), SFinAmountType.UNDEFINED, SFinMovement.DECREMENT);
}
oDpsTaxes.addTax(isDocument() ? (int[]) getPrimaryKey() : entry.getKeyAuxDps(), tax.getKeyTax(), oAmount);
}
}
}
// 4.5 Purchases or sales taxes:
for (SFinDpsTaxes.STax tax : oDpsTaxes.getTaxes()) {
if (tax.getMovement() == SFinMovement.DECREMENT) {
nTaxAccTypeId = SDataConstantsSys.FINX_ACC_PAY_PEND; // decrement occurs when prepayment applied into invoice
}
else {
nTaxAccTypeId = tax.isPrepayment() || tax.getFkTaxApplicationTypeId() == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINX_ACC_PAY : SDataConstantsSys.FINX_ACC_PAY_PEND;
}
sAccountId = SFinAccountUtilities.obtainTaxAccountId(tax.getKeyTax(), mnFkDpsCategoryId, mtDate, nTaxAccTypeId, oStatement);
sSql = "SELECT fid_tp_tax, fid_tp_tax_app FROM erp.finu_tax " +
"WHERE id_tax_bas = " + tax.getPkTaxBasicId() + " AND id_tax = " + tax.getPkTaxId() + " ";
oResultSet = oStatement.executeQuery(sSql);
if (!oResultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
nTaxTypeId = oResultSet.getInt("fid_tp_tax");
nTaxAppTypeId = tax.isPrepayment() && tax.getMovement() == SFinMovement.INCREMENT ? SModSysConsts.FINS_TP_TAX_APP_ACCR : oResultSet.getInt("fid_tp_tax_app");
}
anSysAccTypeKeyTax = SModSysConsts.FINS_TP_SYS_ACC_NA_NA;
anSysMvtTypeKeyTax = getSysMvtTypeKeyTax(nTaxTypeId, nTaxAppTypeId);
anSysMvtTypeKeyTaxXXX = getSysMvtTypeKeyTaxXXX(nTaxTypeId, nTaxAppTypeId);
oRecordEntry = createAccRecordEntry(
sAccountId, "", anAccMvtSubclassKey, anSysAccTypeKeyTax, anSysMvtTypeKeyTax, anSysMvtTypeKeyTaxXXX,
isAdjustment() ? tax.getKeyDps() : null, null);
if (tax.getMovement() == SFinMovement.INCREMENT) {
if (isDebitForTaxes(tax.getFkTaxTypeId())) {
oRecordEntry.setDebit(tax.getValue());
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(tax.getValueCy());
oRecordEntry.setCreditCy(0);
}
else {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(tax.getValue());
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(tax.getValueCy());
}
}
else { // prepayment applied into invoice
if (isDebitForTaxes(tax.getFkTaxTypeId())) {
oRecordEntry.setDebit(0);
oRecordEntry.setCredit(tax.getValue());
oRecordEntry.setDebitCy(0);
oRecordEntry.setCreditCy(tax.getValueCy());
}
else {
oRecordEntry.setDebit(tax.getValue());
oRecordEntry.setCredit(0);
oRecordEntry.setDebitCy(tax.getValueCy());
oRecordEntry.setCreditCy(0);
}
}
oRecordEntry.setConcept(sConcept);
oRecordEntry.setSortingPosition(++nSortingPosition);
oRecordEntry.setFkTaxBasicId_n(tax.getPkTaxBasicId());
oRecordEntry.setFkTaxId_n(tax.getPkTaxId());
oRecord.getDbmsRecordEntries().add(oRecordEntry);
}
// 4.6 Validate accounting record:
dDebit = 0;
dCredit = 0;
dDebitCy = 0;
dCreditCy = 0;
nPositionToAdjust = 0;
dGreatestAmount = 0;
for (i = 0; i < oRecord.getDbmsRecordEntries().size(); i++) {
oRecordEntry = oRecord.getDbmsRecordEntries().get(i);
if (!oRecordEntry.getIsDeleted()) {
dDebit += oRecordEntry.getDebit();
dCredit += oRecordEntry.getCredit();
dDebitCy += oRecordEntry.getDebitCy();
dCreditCy += oRecordEntry.getCreditCy();
if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC) ||
SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ)) {
if (oRecordEntry.getDebit() > dGreatestAmount) {
dGreatestAmount = oRecordEntry.getDebit();
nPositionToAdjust = i;
}
}
else if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ) ||
SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC)) {
if (oRecordEntry.getCredit() > dGreatestAmount) {
dGreatestAmount = oRecordEntry.getCredit();
nPositionToAdjust = i;
}
}
}
}
if (dDebit != dCredit) {
oRecordEntry = oRecord.getDbmsRecordEntries().get(nPositionToAdjust);
if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC) ||
SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ)) {
if (dDebit > dCredit) {
oRecordEntry.setDebit(SLibUtilities.round(oRecordEntry.getDebit() - (dDebit - dCredit), nDecimals));
}
else {
oRecordEntry.setDebit(SLibUtilities.round(oRecordEntry.getDebit() + (dCredit - dDebit), nDecimals));
}
}
else if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ) ||
SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC)) {
if (dDebit < dCredit) {
oRecordEntry.setCredit(SLibUtilities.round(oRecordEntry.getCredit() - (dCredit - dDebit), nDecimals));
}
else {
oRecordEntry.setCredit(SLibUtilities.round(oRecordEntry.getCredit() + (dDebit - dCredit), nDecimals));
}
}
oRecord.getDbmsRecordEntries().set(nPositionToAdjust, oRecordEntry);
}
// 4.7 Finally, save journal voucher (acounting record):
if (oRecord.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP);
}
else {
sSql = "DELETE FROM trn_dps_rec WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " ";
oStatement.execute(sSql);
sSql = "INSERT INTO trn_dps_rec VALUES (" + mnPkYearId + ", " + mnPkDocId + ", " +
oRecord.getPkYearId() + ", " + oRecord.getPkPeriodId() + ", " + oRecord.getPkBookkeepingCenterId() + ", " +
"'" + oRecord.getPkRecordTypeId() + "', " + oRecord.getPkNumberId() + ") ";
oStatement.execute(sSql);
moDbmsRecordKey = oRecord.getPrimaryKey();
mtDbmsRecordDate = oRecord.getDate();
}
}
}
// 5. If document is deleted, delete aswell its links:
if (mbIsDeleted) {
deleteLinks(oStatement);
}
// Save addenda:
if (moAuxCfdParams != null) {
moDbmsDataAddenda = new SDataDpsAddenda();
moDbmsDataAddenda.setPkYearId(mnPkYearId);
moDbmsDataAddenda.setPkDocId(mnPkDocId);
moDbmsDataAddenda.setLorealFolioNotaRecepcion(moAuxCfdParams.getLorealFolioNotaRecepcion());
moDbmsDataAddenda.setBachocoSociedad(moAuxCfdParams.getBachocoSociedad());
moDbmsDataAddenda.setBachocoOrganizacionCompra(moAuxCfdParams.getBachocoOrganizacionCompra());
moDbmsDataAddenda.setBachocoDivision(moAuxCfdParams.getBachocoDivision());
moDbmsDataAddenda.setModeloDpsDescripcion(moAuxCfdParams.getModeloDpsDescripcion());
moDbmsDataAddenda.setSorianaTienda(moAuxCfdParams.getSorianaTienda());
moDbmsDataAddenda.setSorianaEntregaMercancia(moAuxCfdParams.getSorianaEntregaMercancia());
moDbmsDataAddenda.setSorianaRemisionFecha(moAuxCfdParams.getSorianaFechaRemision() == null ? mtDate : moAuxCfdParams.getSorianaFechaRemision());
moDbmsDataAddenda.setSorianaRemisionFolio(moAuxCfdParams.getSorianaFolioRemision());
moDbmsDataAddenda.setSorianaPedidoFolio(moAuxCfdParams.getSorianaFolioPedido());
moDbmsDataAddenda.setSorianaBultoTipo(moAuxCfdParams.getSorianaTipoBulto());
moDbmsDataAddenda.setSorianaBultoCantidad(moAuxCfdParams.getSorianaCantidadBulto());
moDbmsDataAddenda.setSorianaNotaEntradaFolio(moAuxCfdParams.getSorianaNotaEntradaFolio());
moDbmsDataAddenda.setCfdAddendaSubtype(moAuxCfdParams.getCfdAddendaSubtype());
moDbmsDataAddenda.setFkCfdAddendaTypeId(moAuxCfdParams.getTipoAddenda());
moDbmsDataAddenda.getDbmsDpsAddEntries().clear();
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
SDataDpsAddendaEntry addendaEntry = new SDataDpsAddendaEntry();
addendaEntry.setPkYearId(entry.getPkYearId());
addendaEntry.setPkDocId(entry.getPkDocId());
addendaEntry.setPkEntryId(entry.getPkEntryId());
addendaEntry.setBachocoNumeroPosicion(entry.getDbmsDpsAddBachocoNumberPosition());
addendaEntry.setBachocoCentro(entry.getDbmsDpsAddBachocoCenter());
addendaEntry.setLorealEntryNumber(entry.getDbmsDpsAddLorealEntryNumber());
addendaEntry.setSorianaCodigo(entry.getDbmsDpsAddSorianaBarCode());
addendaEntry.setElektraOrder(entry.getDbmsDpsAddElektraOrder());
addendaEntry.setElektraBarcode(entry.getDbmsDpsAddElektraBarcode());
addendaEntry.setElektraCages(entry.getDbmsDpsAddElektraCages());
addendaEntry.setElektraCagePriceUnitary(entry.getDbmsDpsAddElektraCagePriceUnitary());
addendaEntry.setElektraParts(entry.getDbmsDpsAddElektraParts());
addendaEntry.setElektraPartPriceUnitary(entry.getDbmsDpsAddElektraPartPriceUnitary());
moDbmsDataAddenda.getDbmsDpsAddEntries().add(addendaEntry);
}
if (moAuxCfdParams.getTipoAddenda() != SDataConstantsSys.BPSS_TP_CFD_ADD_NA) {
if (moDbmsDataAddenda.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP);
}
}
else {
if (moDbmsDataAddenda.delete(connection) != SLibConstants.DB_ACTION_DELETE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_DELETE_DEP);
}
}
}
// Save XML of purchases when provided:
if (moDbmsDataCfd != null && mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_PUR) {
moDbmsDataCfd.setFkDpsYearId_n(mnPkYearId);
moDbmsDataCfd.setFkDpsDocId_n(mnPkDocId);
moDbmsDataCfd.setTimestamp(mtDate);
if (moDbmsDataCfd.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP);
}
}
mbIsRegistryNew = false;
mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_OK;
}
}
catch (SQLException e) {
mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_ERROR;
SLibUtilities.printOutException(this, e);
}
catch (Exception e) {
mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_ERROR;
SLibUtilities.printOutException(this, e);
}
return mnLastDbActionResult;
}
@Override
public java.util.Date getLastDbUpdate() {
return mtUserEditTs;
}
@Override
public int canSave(java.sql.Connection connection) {
int[] keyMoveSubclass = null;
Object[] keyRecord = null;
String sql = "";
String name = "";
String idAccount = "";
Statement statement = null;
ResultSet resultSet = null;
Vector<SFinAccountConfigEntry> accountConfigs = null;
SFinDpsTaxes finDpsTaxes = null;
mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_YES;
// Check if all elements of this DPS have an account for automatic accounting:
try {
keyMoveSubclass = getAccMvtSubclassKeyBizPartner();
if (keyMoveSubclass != null) {
// Current document needs an accounting record:
statement = connection.createStatement();
finDpsTaxes = new SFinDpsTaxes(statement);
keyRecord = (Object[]) createAccRecordKey(statement);
// 1. Check business partner's liability or asset:
try {
accountConfigs = SFinAccountUtilities.obtainBizPartnerAccountConfigs(
mnFkBizPartnerId_r, STrnUtils.getBizPartnerCategoryId(mnFkDpsCategoryId), (Integer) keyRecord[2], mtDate,
SDataConstantsSys.FINS_TP_ACC_BP_OP, isDebitForBizPartner(), statement);
}
catch (Exception e) {
msDbmsError = MSG_ERR_ACC_UNK_ + "asociado de negocios.\n[" + e + "]";
throw new Exception(msDbmsError);
}
// 2. Check purchases or sales:
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
try {
if (entry.getFkItemRefId_n() == 0) {
name = entry.getConcept();
}
else {
sql = "SELECT item FROM erp.itmu_item WHERE id_item = " + entry.getFkItemRefId_n() + " ";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
name = resultSet.getString("item");
}
}
accountConfigs = SFinAccountUtilities.obtainItemAccountConfigs(
entry.getFkItemRefId_n() != 0 ? entry.getFkItemRefId_n() : entry.getFkItemId(), (Integer) keyRecord[2], mtDate,
getAccItemTypeId(entry), isDebitForOperations(), statement);
for (SFinAccountConfigEntry config : accountConfigs) {
idAccount = config.getAccountId();
idAccount = idAccount.replaceAll("0", "");
idAccount = idAccount.replaceAll("-", "");
if (idAccount.length() == 0) {
msDbmsError = MSG_ERR_ACC_EMP_ + "ítem:\n'" + name + "'.";
throw new Exception(msDbmsError);
}
}
}
catch (Exception e) {
msDbmsError = MSG_ERR_ACC_UNK_ + "ítem:\n'" + name + "'.\n[" + e + "]";
throw new Exception(msDbmsError);
}
for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) {
finDpsTaxes.addTax(isDocument() ? (int[]) getPrimaryKey() : entry.getKeyAuxDps(), tax.getKeyTax(), new SFinAmount(tax.getTax(), tax.getTaxCy()));
}
}
}
// 3. Check purchases or sales taxes:
for (SFinDpsTaxes.STax tax : finDpsTaxes.getTaxes()) {
try {
idAccount = SFinAccountUtilities.obtainTaxAccountId(tax.getKeyTax(), mnFkDpsCategoryId, mtDate,
tax.getFkTaxApplicationTypeId() == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINX_ACC_PAY : SDataConstantsSys.FINX_ACC_PAY_PEND,
statement);
}
catch (Exception e) {
// Read tax name:
sql = "SELECT tax FROM erp.finu_tax WHERE id_tax_bas = " + tax.getPkTaxBasicId() + " AND id_tax = " + tax.getPkTaxId() + " ";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
}
else {
name = resultSet.getString("tax");
}
msDbmsError = MSG_ERR_ACC_UNK_ + "impuesto:\n'" + name + "'.\n[" + e + "]";
throw new Exception(msDbmsError);
}
}
}
}
catch (SQLException exception) {
mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_SAVE;
}
SLibUtilities.printOutException(this, exception);
}
catch (Exception exception) {
mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_SAVE;
}
SLibUtilities.printOutException(this, exception);
}
return mnLastDbActionResult;
}
@Override
public int canAnnul(java.sql.Connection connection) {
mnLastDbActionResult = SLibConsts.UNDEFINED;
try {
if (testDeletion(connection, "No se puede anular el documento: ", SDbConsts.ACTION_ANNUL)) {
mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_YES;
}
}
catch (SQLException exception) {
mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_ANNUL;
}
SLibUtilities.printOutException(this, exception);
}
catch (Exception exception) {
mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_ANNUL;
}
SLibUtilities.printOutException(this, exception);
}
return mnLastDbActionResult;
}
@Override
public int canDelete(java.sql.Connection connection) {
mnLastDbActionResult = SLibConsts.UNDEFINED;
try {
if (testDeletion(connection, "No se puede eliminar el documento: ", SDbConsts.ACTION_DELETE)) {
mnLastDbActionResult = SLibConstants.DB_CAN_DELETE_YES;
}
}
catch (SQLException exception) {
mnLastDbActionResult = SLibConstants.DB_CAN_DELETE_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_DELETE;
}
SLibUtilities.printOutException(this, exception);
}
catch (Exception exception) {
mnLastDbActionResult = SLibConstants.DB_CAN_DELETE_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_DELETE;
}
SLibUtilities.printOutException(this, exception);
}
return mnLastDbActionResult;
}
@Override
public int annul(java.sql.Connection connection) {
int nDecs = 2;
String sSql = "";
String sMsg = "No se puede anular el documento: ";
Statement oStatement = null;
ResultSet oResultSet = null;
mnLastDbActionResult = SLibConsts.UNDEFINED;
try {
oStatement = connection.createStatement();
if (mbIsRegistryRequestAnnul) {
// Set DPS as annuled:
if (testDeletion(connection, sMsg, SDbConsts.ACTION_ANNUL)) {
mnFkDpsStatusId = SDataConstantsSys.TRNS_ST_DPS_ANNULED;
sSql = "UPDATE trn_dps SET fid_st_dps = " + SDataConstantsSys.TRNS_ST_DPS_ANNULED + ", " + "fid_tp_dps_ann=" + mnFkDpsAnnulationTypeId + ", " +
"stot_prov_r = 0, disc_doc_r = 0, stot_r = 0, tax_charged_r = 0, tax_retained_r = 0, tot_r = 0, " +
"stot_prov_cur_r = 0, disc_doc_cur_r = 0, stot_cur_r = 0, tax_charged_cur_r = 0, tax_retained_cur_r = 0, tot_cur_r = 0, " +
"fid_usr_edit = " + mnFkUserEditId + ", ts_edit = NOW() " +
"WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " ";
oStatement.execute(sSql);
if (moAuxFormerRecordKey != null) {
// If document had automatic accounting record, delete it including its header:
deleteRecord(moAuxFormerRecordKey, mbAuxIsFormerRecordAutomatic, connection);
}
deleteLinks(oStatement);
if (moDbmsDataCfd != null) {
moDbmsDataCfd.annul(connection);
}
mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_OK;
}
}
else {
// Revert DPS annulation:
if (testRevertDeletion(sMsg, SDbConsts.ACTION_ANNUL)) {
// 1. Set DPS fields:
mnFkDpsStatusId = SDataConstantsSys.TRNS_ST_DPS_EMITED;
// 2. Obtain decimals for calculations:
sSql = "SELECT decs_val FROM erp.cfg_param_erp WHERE id_erp = 1 ";
oResultSet = oStatement.executeQuery(sSql);
if (oResultSet.next()) {
nDecs = oResultSet.getInt("decs_val");
}
// 3. Recalculate DPS value:
calculateDpsTotal(null, nDecs);
// 4. Save DPS again (this will re-create accounting record again):
if (save(connection) == SLibConstants.DB_ACTION_SAVE_OK) {
mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_OK;
}
}
}
}
catch (SQLException exception) {
mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_ERROR;
SLibUtilities.printOutException(this, exception);
}
catch (Exception exception) {
mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_ERROR;
SLibUtilities.printOutException(this, exception);
}
return mnLastDbActionResult;
}
@Override
public int delete(java.sql.Connection connection) {
String sSql = "";
String sMsg = "No se puede eliminar el documento: ";
Statement oStatement = null;
mnLastDbActionResult = SLibConsts.UNDEFINED;
try {
oStatement = connection.createStatement();
if (mbIsRegistryRequestDelete) {
// Set DPS as deleted:
if (testDeletion(connection, sMsg, SDbConsts.ACTION_DELETE)) {
mbIsDeleted = true;
sSql = "UPDATE trn_dps SET b_del = 1, fid_usr_del = " + mnFkUserDeleteId + ", ts_del = NOW() " +
"WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " ";
oStatement.execute(sSql);
if (moAuxFormerRecordKey != null) {
// If document had automatic accounting record, delete it including its header:
deleteRecord(moAuxFormerRecordKey, mbAuxIsFormerRecordAutomatic, connection);
}
deleteLinks(oStatement);
clearEntryDeliveryReferences(oStatement);
mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_OK;
}
}
else {
// Revert DPS deletion:
if (testRevertDeletion(sMsg, SDbConsts.ACTION_DELETE)) {
// 1. Set DPS fields:
mbIsDeleted = false;
// 4. Save DPS again (this will re-create accounting record again):
if (save(connection) == SLibConstants.DB_ACTION_SAVE_OK) {
mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_OK;
}
else {
throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE);
}
}
}
}
catch (SQLException exception) {
mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_ERROR;
SLibUtilities.printOutException(this, exception);
}
catch (Exception exception) {
mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_ERROR;
SLibUtilities.printOutException(this, exception);
}
return mnLastDbActionResult;
}
/**
* Calculates DPS value.
* @param client ERP Client. Can be null, and each DPS entry is not calculated, original values remains as the original ones.
*/
public void calculateTotal(erp.client.SClientInterface client) throws SQLException, Exception {
calculateDpsTotal(client, 0);
}
/**
* Resets all members related to accounting record.
*/
public void resetRecord() {
moDbmsRecordKey = null;
mtDbmsRecordDate = null;
mbAuxIsFormerRecordAutomatic = false;
moAuxFormerRecordKey = null;
moDbmsDataBookkeepingNumber = null;
}
/**
* Create addenda for Soriana
* @return Addenda
* @throws java.lang.Exception
*/
private DElementDSCargaRemisionProv computeAddendaSoriana() throws java.lang.Exception {
int totalItems = 0;
Date tDate = null;
GregorianCalendar oGregorianCalendar = null;
SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
int[] anDateDps = SLibTimeUtilities.digestDate(mtDate);
int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs);
Vector<DElementArticulos> vArticulos = new Vector<>();
DElementDSCargaRemisionProv addendaSoriana = new DElementDSCargaRemisionProv();
if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) {
tDate = mtUserEditTs;
}
else {
oGregorianCalendar = new GregorianCalendar();
oGregorianCalendar.setTime(mtUserEditTs);
oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]);
oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0
oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]);
tDate = oGregorianCalendar.getTime();
oSimpleDateFormat.format(tDate);
}
// Create addenda:
totalItems = 0;
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
DElementArticulos vItem = new DElementArticulos();
vItem.getEltProveedor().setValue(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey());
vItem.getEltRemision().setValue("" + moAuxCfdParams.getSorianaFolioRemision()); // Serie - Folio del XML (Factura)
vItem.getEltFolio().setValue(moAuxCfdParams.getSorianaFolioPedido()); // Folio del pedido
vItem.getEltTienda().setValue("" + moAuxCfdParams.getSorianaTienda());
vItem.getEltCodigoBarras().setValue(entry.getDbmsDpsAddSorianaBarCode());
vItem.getEltCantCompra().setValue("" + entry.getOriginalQuantity());
vItem.getEltCostoNeto().setValue("" + entry.getPriceUnitary());
vItem.getEltIeps().setValue("0.00");
vItem.getEltIva().setValue("0.00");
vArticulos.add(vItem);
totalItems += entry.getOriginalQuantity();
}
}
addendaSoriana.getEltRemision().getEltProveedor().setValue(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey());
addendaSoriana.getEltRemision().getEltRemision().setValue("" + moAuxCfdParams.getSorianaFolioRemision()); // Serie - Folio del XML (Factura)
addendaSoriana.getEltRemision().getEltConsecutivo().setValue("0"); // Si se entrega en parcialidades
addendaSoriana.getEltRemision().getEltFechaRemision().setValue("" + moAuxCfdParams.getSorianaFechaRemision() + "T00:00:00");
addendaSoriana.getEltRemision().getEltTienda().setValue("" + moAuxCfdParams.getSorianaTienda());
addendaSoriana.getEltRemision().getEltTipoMoneda().setValue("" + mnFkCurrencyId);
addendaSoriana.getEltRemision().getEltTipoBulto().setValue("" + moAuxCfdParams.getSorianaTipoBulto());
addendaSoriana.getEltRemision().getEltEntregaMercancia().setValue("" + moAuxCfdParams.getSorianaEntregaMercancia());
addendaSoriana.getEltRemision().getEltCumpleFiscal().setValue("true");
addendaSoriana.getEltRemision().getEltCantidadBultos().setValue("" + moAuxCfdParams.getSorianaCantidadBulto());
addendaSoriana.getEltRemision().getEltSubTotal().setValue("" + mdSubtotal_r);
addendaSoriana.getEltRemision().getEltDescuentos().setValue("" + mdDiscountDoc_r);
addendaSoriana.getEltRemision().getEltIeps().setValue("0.00"); // Si no aplica indicar 0
addendaSoriana.getEltRemision().getEltIva().setValue("0.00"); // Si no aplica indicar 0
addendaSoriana.getEltRemision().getEltOtrosImpuestos().setValue("0.00"); // Otros imptos ej. retenciones
addendaSoriana.getEltRemision().getEltTotal().setValue("" + mdTotal_r);
addendaSoriana.getEltRemision().getEltCantidadPedidos().setValue("1");
addendaSoriana.getEltRemision().getEltFechaEntrega().setValue("" + (mtDateDocDelivery_n == null ? mtDate : mtDateDocDelivery_n) + "T00:00:00");
addendaSoriana.getEltPedido().getEltProveedor().setValue(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey());
addendaSoriana.getEltPedido().getEltRemision().setValue("" + moAuxCfdParams.getSorianaFolioRemision()); // Serie - Folio del XML (Factura)
addendaSoriana.getEltPedido().getEltFolio().setValue(moAuxCfdParams.getSorianaFolioPedido()); // Folio del pedido
addendaSoriana.getEltPedido().getEltTienda().setValue("" + moAuxCfdParams.getSorianaTienda());
addendaSoriana.getEltPedido().getEltCantArticulos().setValue("" + totalItems);
if (moAuxCfdParams.getCfdAddendaSubtype() == SDataConstantsSys.BPSS_STP_CFD_ADD_SORIANA_EXT) {
cfd.ext.soriana.DElementPedidoEmitidoProveedor pedidoEmitidoProveedor = new cfd.ext.soriana.DElementPedidoEmitidoProveedor("SI");
cfd.ext.soriana.DElementFolioNotaEntrada folioNotaEntrada = new DElementFolioNotaEntrada(moAuxCfdParams.getSorianaNotaEntradaFolio());
addendaSoriana.getEltRemision().setEltOpcFolioNotaEntrada(folioNotaEntrada);
addendaSoriana.getEltPedido().setEltOpcPedidoEmitidoProveedor(pedidoEmitidoProveedor);
}
addendaSoriana.getEltArticulos().getEltHijosArticulos().addAll(vArticulos);
//addendaSoriana.getEltCajas().getEltRemision().setValue("A-00047");
//addendaSoriana.getEltArticulosCajas().getEltRemision().setValue("A-00047");
return addendaSoriana;
}
/**
* Create addenda for L'Oreal
* @param dIvaPct Tax rate applied to DPS
* @return Addenda
* @throws java.lang.Exception
*/
private DElementFacturaInterfactura computeAddendaLoreal(double dIvapct) throws java.lang.Exception {
int nMoneda = 0;
int nCondigoPago = 0;
double dIvaPctCuerpo = 0;
java.util.Date tDate = null;
GregorianCalendar oGregorianCalendar = null;
int[] anDateDps = SLibTimeUtilities.digestDate(mtDate);
int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs);
Vector<DElementCuerpo> vCuerpo = new Vector<>();
DElementFacturaInterfactura addendaLoreal = new DElementFacturaInterfactura();
if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) {
tDate = mtUserEditTs;
}
else {
oGregorianCalendar = new GregorianCalendar();
oGregorianCalendar.setTime(mtUserEditTs);
oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]);
oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0
oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]);
tDate = oGregorianCalendar.getTime();
}
nCondigoPago = moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getEffectiveDaysOfCredit();
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
DElementCuerpo cuerpo = new DElementCuerpo();
dIvaPctCuerpo = entry.getDbmsEntryTaxes().get(0).getPercentage() * 100;
if (dIvapct == dIvaPctCuerpo) {
cuerpo.getAttPartida().setInteger(entry.getDbmsDpsAddLorealEntryNumber());
cuerpo.getAttCantidad().setDouble(entry.getOriginalQuantity());
cuerpo.getAttConcepto().setString(entry.getConcept());
cuerpo.getAttPUnitario().setDouble(entry.getPriceUnitary());
cuerpo.getAttImporte().setDouble(entry.getSubtotal_r());
cuerpo.getAttUnidadMedida().setString(entry.getDbmsUnitSymbol().toUpperCase());
}
else {
cuerpo.getAttPartida().setInteger(entry.getDbmsDpsAddLorealEntryNumber());
cuerpo.getAttCantidad().setDouble(entry.getOriginalQuantity());
cuerpo.getAttConcepto().setString(entry.getConcept());
cuerpo.getAttPUnitario().setDouble(entry.getPriceUnitary());
cuerpo.getAttImporte().setDouble(entry.getSubtotal_r());
cuerpo.getAttUnidadMedida().setString(entry.getDbmsUnitSymbol().toUpperCase());
cuerpo.getAttIva().setDouble(entry.getTaxCharged_r());
cuerpo.getAttIVAPCT().setDouble(dIvaPctCuerpo);
}
vCuerpo.add(cuerpo);
}
}
switch (mnFkCurrencyId) {
case 1: // MXN
nMoneda = DAttributeOptionMoneda.CFD_MXN;
break;
case 2: // USD
nMoneda = DAttributeOptionMoneda.CFD_USD;
break;
case 3: // EUR
nMoneda = DAttributeOptionMoneda.CFD_EUR;
break;
default:
throw new Exception("La moneda debe ser conocida (" + mnFkCurrencyId + ").");
}
// Create addenda:
addendaLoreal.getAttxmlns().setString("https:
addendaLoreal.getAttTipoDocumento().setString("Factura");
addendaLoreal.getAttschemaLocation().setString("https:
addendaLoreal.getEltEmisor().getAttRefEmisor().setString("0103399");
addendaLoreal.getEltReceptor().getAttRefReceptor().setString("0101427");
addendaLoreal.getEltEncabezado().getAttMoneda().setOption(nMoneda);
addendaLoreal.getEltEncabezado().getAttFolioOrdenCompra().setString(msNumberReference);
addendaLoreal.getEltEncabezado().getAttFolioNotaRecepcion().setString(moAuxCfdParams.getLorealFolioNotaRecepcion());
addendaLoreal.getEltEncabezado().getAttFecha().setDatetime(tDate);
addendaLoreal.getEltEncabezado().getAttCondicionPago().setString("" + nCondigoPago);
addendaLoreal.getEltEncabezado().getAttIVAPCT().setDouble(dIvapct);
addendaLoreal.getEltEncabezado().getAttNumProveedor().setString(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey());
addendaLoreal.getEltEncabezado().getAttCargoTipo().setString("");
addendaLoreal.getEltEncabezado().getAttSubTotal().setDouble(mdSubtotal_r);
addendaLoreal.getEltEncabezado().getAttSerie().setString(msNumberSeries);
addendaLoreal.getEltEncabezado().getAttFolio().setString(msNumber);
addendaLoreal.getEltEncabezado().getAttIva().setDouble(mdTaxCharged_r);
addendaLoreal.getEltEncabezado().getAttTotal().setDouble(mdTotal_r);
addendaLoreal.getEltEncabezado().getAttObservaciones().setString("");
addendaLoreal.getEltEncabezado().getEltHijosEncabezado().addAll(vCuerpo);
return addendaLoreal;
}
/**
* Create addenda for Bachoco
* @param dIvaPct Tax rate applied to DPS
* @return Addenda
* @throws java.lang.Exception
*/
private DElementPayment computeAddendaBachoco(double dIvapct) throws java.lang.Exception {
int nMoneda = 0;
String sStatusDoc = "";
String sEntityType = "";
String sReceptorNumber = "";
java.util.Date tDate = null;
GregorianCalendar oGregorianCalendar = null;
SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
int[] anDateDps = SLibTimeUtilities.digestDate(mtDate);
int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs);
int[] anTypeDoc = {mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId};
Vector<DElementLineItem> vLineItem = new Vector<>();
DElementPayment addendaBachoco = new DElementPayment();
if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) {
tDate = mtUserEditTs;
}
else {
oGregorianCalendar = new GregorianCalendar();
oGregorianCalendar.setTime(mtUserEditTs);
oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]);
oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0
oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]);
tDate = oGregorianCalendar.getTime();
oSimpleDateFormat.format(tDate);
}
switch (mnFkDpsStatusId) {
case SDataConstantsSys.TRNS_ST_DPS_EMITED:
sStatusDoc = "ORIGINAL";
break;
case SDataConstantsSys.TRNS_ST_DPS_ANNULED:
sStatusDoc = "DELETE";
break;
default:
break;
}
if (SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_INV)) {
sEntityType = "INVOICE";
}
else if (SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_CN)) {
sEntityType = "CREDIT_NOTE";
}
for (int i = 0; i < (10 - moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey().length()); i++) {
sReceptorNumber += "0";
}
sReceptorNumber += moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey();
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
DElementLineItem vItem = new DElementLineItem();
vItem.getAttType().setString("SimpleinvoiceLineItemType");
vItem.getAttNumber().setInteger(entry.getDbmsDpsAddBachocoNumberPosition());
vItem.getEltTradeItemIdentification().getEltGtin().setValue(entry.getDbmsDpsAddBachocoCenter());
vItem.getEltAditionalQuantity().getAttQuantityType().setString("NUM_CONSUMER_UNITS"); // XXX UNIDAD CONSUMO
vItem.getEltAditionalQuantity().setValue("" + entry.getOriginalQuantity());
vItem.getEltNetPrice().getEltAmount().setValue("" + entry.getPriceUnitary());
vItem.getEltAdditionalInformation().getEltReferenceIdentification().getAttType().setString("ON");
vItem.getEltAdditionalInformation().getEltReferenceIdentification().setValue("X"); // ORDEN DE INVERSION
vLineItem.add(vItem);
}
}
switch (mnFkCurrencyId) {
case 1: // MXN
nMoneda = DAttributeOptionMoneda.CFD_MXN;
break;
case 2: // USD
nMoneda = DAttributeOptionMoneda.CFD_USD;
break;
case 3: // EUR
nMoneda = DAttributeOptionMoneda.CFD_EUR;
break;
default:
throw new Exception("La moneda debe ser conocida (" + mnFkCurrencyId + ").");
}
// Create addenda:
addendaBachoco.getAttType().setString("SimpleInvoiceType");
addendaBachoco.getAttContentVersion().setString("1.3.1");
addendaBachoco.getAttDocStructureVersion().setString("AMC7.1");
addendaBachoco.getAttDocStatus().setString(sStatusDoc);
addendaBachoco.getAttDeliveryDate().setDate(tDate);
addendaBachoco.getEltPaymentIdentification().getEltEntityType().setValue(sEntityType);
addendaBachoco.getEltPaymentIdentification().getEltCreatorIdentification().setValue(msNumberSeries + msNumber);
addendaBachoco.getEltSpecialInstruction().getAttCode().setString("PUR");
addendaBachoco.getEltSpecialInstruction().getEltText().setValue("X");
addendaBachoco.getEltOrderIdentification().getEltReferenceIdentification().getAttType().setString("ON");
addendaBachoco.getEltOrderIdentification().getEltReferenceIdentification().setValue(msNumberReference);
addendaBachoco.getEltDeliveryNote().getEltReferenceIdentification().setValue(moAuxCfdParams.getBachocoDivision());
addendaBachoco.getEltBuyer().getEltGln().setValue("X");
addendaBachoco.getEltBuyer().getEltContactInformation().getEltPersonOrDepartmentName().getEltText().setValue(moAuxCfdParams.getBachocoOrganizacionCompra());
addendaBachoco.getEltSeller().getEltGln().setValue(sReceptorNumber);
addendaBachoco.getEltShipTo().getEltGln().setValue(moAuxCfdParams.getBachocoSociedad());
addendaBachoco.getEltInvoiceCreator().getEltAlternatePartyIdentification().getAttType().setString("IA");
addendaBachoco.getEltInvoiceCreator().getEltAlternatePartyIdentification().setValue(sReceptorNumber);
addendaBachoco.getEltCustoms().getEltAlternatePartyIdentification().getAttType().setString("TN");
addendaBachoco.getEltCustoms().getEltAlternatePartyIdentification().setValue("X"); // XXX No. PEDIMENTO
addendaBachoco.getEltCurrency().getAttCurrencyISOCode().setOption(nMoneda);
addendaBachoco.getEltCurrency().getEltCurrencyFunction().setValue("BILLING_CURRENCY"); // DIVISA DE FACTURACION
addendaBachoco.getEltItem().getEltHijosLineItem().addAll(vLineItem);
addendaBachoco.getEltTotalAmount().getEltAmount().setValue("" + mdSubtotalCy_r);
addendaBachoco.getEltTax().getAttType().setString("VAT"); // XXX IMPUESTO
addendaBachoco.getEltTax().getEltTaxPercentage().setValue("" + dIvapct);
addendaBachoco.getEltTax().getEltTaxAmount().setValue("" + mdTaxCharged_r);
addendaBachoco.getEltTax().getEltTaxCategory().setValue("TRANSFERIDO"); // XXX TIPO IMPUESTO
addendaBachoco.getEltPayableAmount().getEltAmount().setValue("" + mdTotal_r);
return addendaBachoco;
}
/**
* Create addenda for Grupo Modelo
* @param dIvaPct Tax rate applied to DPS
* @return Addenda
* @throws java.lang.Exception
*/
@SuppressWarnings("empty-statement")
private cfd.ext.grupomodelo.DElementAddendaModelo computeAddendaGrupoModelo(double dIvapct) throws java.lang.Exception {
int nMoneda = 0;
int nQty = 0;
int nIvaPercentage = 0;
String sStatusDoc = "";
String sEntityType = "";
String sReceptorNumber = "";
java.util.Date tDate = null;
GregorianCalendar oGregorianCalendar = null;
SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
DecimalFormat oDecimalFormat = new DecimalFormat("#0.00");
int[] anDateDps = SLibTimeUtilities.digestDate(mtDate);
int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs);
int[] anTypeDoc = {mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId};
Vector<cfd.ext.grupomodelo.DElementLineItem> vLineItem = new Vector<>();
cfd.ext.grupomodelo.DElementAddendaModelo addendaGrupoModelo = new cfd.ext.grupomodelo.DElementAddendaModelo();
if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) {
tDate = mtUserEditTs;
}
else {
oGregorianCalendar = new GregorianCalendar();
oGregorianCalendar.setTime(mtUserEditTs);
oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]);
oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0
oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]);
tDate = oGregorianCalendar.getTime();
oSimpleDateFormat.format(tDate);
}
switch (mnFkDpsStatusId) {
case SDataConstantsSys.TRNS_ST_DPS_EMITED:
sStatusDoc = "ORIGINAL";
break;
case SDataConstantsSys.TRNS_ST_DPS_ANNULED:
sStatusDoc = "DELETE";
break;
}
if (SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_INV)) {
sEntityType = "FA";
}
sReceptorNumber += moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey();
nIvaPercentage = (int) dIvapct;
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
nQty = (int) entry.getOriginalQuantity();
int[] anSubTypeDoc = { entry.getFkDpsAdjustmentTypeId(), entry.getFkDpsAdjustmentSubtypeId() };
cfd.ext.grupomodelo.DElementLineItem vItem = new cfd.ext.grupomodelo.DElementLineItem();
vItem.getAttType().setString("SimpleinvoiceLineItemType");
vItem.getAttNumber().setInteger(entry.getSortingPosition() * 10);
vItem.getEltTradeItemIdentification().getEltGtin().setValue(entry.getConceptKey());
vItem.getEltAlternateTradeItemIdentification().getAttType().setString("BUYER_ASSIGNED");
vItem.getEltAlternateTradeItemIdentification().setValue(sReceptorNumber);
vItem.getEltTradeItemDescriptionInformation().getAttLanguage().setString("ES");
vItem.getEltTradeItemDescriptionInformation().getEltLongText().setValue(entry.msConcept.length() > 35 ? entry.msConcept.substring(0, 34) : entry.msConcept);
vItem.getEltInvoicedQuantity().getAttUnit().setString(entry.getDbmsOriginalUnitSymbol());
vItem.getEltInvoicedQuantity().setValue("" + nQty);
vItem.getEltGrossPrice().getEltAmount().setValue("" + oDecimalFormat.format(entry.getPriceUnitaryCy()));
vItem.getEltNetPrice().getEltAmount().setValue("" + oDecimalFormat.format(entry.getTotalCy_r() / entry.getOriginalQuantity()));
vItem.getEltAdditionalInformation().getEltReferenceIdentification().getAttType().setString("DQ");
vItem.getEltAdditionalInformation().getEltReferenceIdentification().setValue(msNumberSeries + msNumber);
vItem.getEltTradeItemTaxInformation().getEltTaxTypeDescription().setValue("VAT");
vItem.getEltTradeItemTaxInformation().getEltTaxCategory().setValue("TRANSFERIDO");
vItem.getEltTradeItemTaxInformation().getEltItemTaxAmount().getEltTaxPercentage().setValue("" + nIvaPercentage);
vItem.getEltTradeItemTaxInformation().getEltItemTaxAmount().getEltTaxAmount().setValue("" + oDecimalFormat.format(entry.getPriceUnitaryCy() * (dIvapct / 100)));
vItem.getEltTotalLineAmount().getEltGrossAmount().getEltAmount().setValue("" + oDecimalFormat.format(entry.getSubtotalCy_r()));
vItem.getEltTotalLineAmount().getEltNetAmount().getEltAmount().setValue("" + oDecimalFormat.format(entry.getTotalCy_r()));
vLineItem.add(vItem);
if (SLibUtilities.compareKeys(anSubTypeDoc, SDataConstantsSys.TRNS_STP_DPS_ADJ_RET_RET)) {
sEntityType = "ND";
}
else if (SLibUtilities.compareKeys(anSubTypeDoc, SDataConstantsSys.TRNS_STP_DPS_ADJ_DISC_PRICE)) {
sEntityType = "NA";
}
else if (SLibUtilities.compareKeys(anSubTypeDoc, SDataConstantsSys.TRNS_STP_DPS_ADJ_DISC_DISC)) {
sEntityType = "NE";
}
}
}
switch (mnFkCurrencyId) {
case 1: // MXN
nMoneda = DAttributeOptionMoneda.CFD_MXN;
break;
case 2: // USD
nMoneda = DAttributeOptionMoneda.CFD_USD;
break;
case 3: // EUR
nMoneda = DAttributeOptionMoneda.CFD_EUR;
break;
default:
throw new Exception("La moneda debe ser conocida (" + mnFkCurrencyId + ").");
}
// Create addenda:
addendaGrupoModelo.getAttXmlns().setString("http:
addendaGrupoModelo.getAttSchemaLocation().setString("http:
addendaGrupoModelo.getEltPayment().getAttType().setString("SimpleInvoiceType");
addendaGrupoModelo.getEltPayment().getAttContentVersion().setString("1.3.1");
addendaGrupoModelo.getEltPayment().getAttDocStructureVersion().setString("AMC7.1");
addendaGrupoModelo.getEltPayment().getAttDocStatus().setString(sStatusDoc);
addendaGrupoModelo.getEltPayment().getEltPaymentIdentification().getEltEntityType().setValue(sEntityType);
addendaGrupoModelo.getEltPayment().getEltPaymentIdentification().getEltCreatorIdentification().setValue(msNumberSeries + msNumber);
addendaGrupoModelo.getEltPayment().getEltSpecialInstruction().getAttCode().setString("PUR");
addendaGrupoModelo.getEltPayment().getEltSpecialInstruction().getEltText().setValue(moAuxCfdParams.getModeloDpsDescripcion());
addendaGrupoModelo.getEltPayment().getEltOrderIdentification().getEltReferenceIdentification().getAttType().setString("ON");
addendaGrupoModelo.getEltPayment().getEltOrderIdentification().getEltReferenceIdentification().setValue(msNumberReference);
addendaGrupoModelo.getEltPayment().getEltOrderIdentification().getEltReferenceDate().setValue(oSimpleDateFormat.format(tDate));
addendaGrupoModelo.getEltPayment().getEltBuyer().getEltGln().setValue("7504001186019");
addendaGrupoModelo.getEltPayment().getEltBuyer().getEltContactInformation().getEltPersonOrDepartmentName().getEltText().setValue(moAuxCfdParams.getBachocoSociedad());
addendaGrupoModelo.getEltPayment().getEltInvoiceCreator().getEltGln().setValue("7500000000000");
addendaGrupoModelo.getEltPayment().getEltInvoiceCreator().getEltAlternatePartyIdentification().getAttType().setString("IA");
addendaGrupoModelo.getEltPayment().getEltInvoiceCreator().getEltAlternatePartyIdentification().setValue(sReceptorNumber);
addendaGrupoModelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltName().setValue(moAuxCfdParams.getEmisor().getProperName().length() > 35 ? moAuxCfdParams.getEmisor().getProperName().substring(0, 34) : moAuxCfdParams.getEmisor().getProperName());
addendaGrupoModelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltStreetAddressOne().setValue(moAuxCfdParams.getEmisor().getDbmsHqBranch().getDbmsBizPartnerBranchAddressOfficial().getStreet());
addendaGrupoModelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltCity().setValue(moAuxCfdParams.getEmisor().getDbmsHqBranch().getDbmsBizPartnerBranchAddressOfficial().getState());
addendaGrupoModelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltPostalCode().setValue(moAuxCfdParams.getEmisor().getDbmsHqBranch().getDbmsBizPartnerBranchAddressOfficial().getZipCode());
addendaGrupoModelo.getEltPayment().getEltCurrency().getAttCurrencyISOCode().setOption(nMoneda);
addendaGrupoModelo.getEltPayment().getEltCurrency().getEltCurrencyFunction().setValue("BILLING_CURRENCY");
addendaGrupoModelo.getEltPayment().getEltCurrency().getEltCurrencyRate().setValue("" + oDecimalFormat.format(mdExchangeRate));
addendaGrupoModelo.getEltPayment().getEltTotalAmount().getEltAmount().setValue("" + oDecimalFormat.format(mdTotalCy_r));
addendaGrupoModelo.getEltPayment().getEltBaseAmount().getEltAmount().setValue("" + oDecimalFormat.format(mdSubtotalCy_r));
addendaGrupoModelo.getEltPayment().getEltTax().getAttType().setString("VAT");
addendaGrupoModelo.getEltPayment().getEltTax().getEltTaxPercentage().setValue("" + oDecimalFormat.format(dIvapct));
addendaGrupoModelo.getEltPayment().getEltTax().getEltTaxAmount().setValue("" + oDecimalFormat.format(mdTaxCharged_r));
addendaGrupoModelo.getEltPayment().getEltTax().getEltTaxCategory().setValue("TRANSFERIDO");
addendaGrupoModelo.getEltPayment().getEltPayableAmount().getEltAmount().setValue("" + oDecimalFormat.format(mdTotal_r));
addendaGrupoModelo.getEltPayment().getEltItem().getEltHijosLineItem().addAll(vLineItem);
return addendaGrupoModelo;
}
/**
* Create addenda for Elektra
* @param dIvaPct Tax rate applied to DPS
* @return Addenda
* @throws java.lang.Exception
*/
@SuppressWarnings("empty-statement")
private cfd.ext.elektra.DElementAp computeAddendaElektra() throws java.lang.Exception {
double dImpuestosTrasladados = 0;
int[] anTypeDoc = {mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId};
String sNotes = "";
DElementAp addendaElektra = new DElementAp();
cfd.ext.elektra.DElementDetailItems oDetailItems = new DElementDetailItems();
cfd.ext.elektra.DElementDetalle oDetalle = null;
cfd.ext.elektra.DElementProducto oProducto = null;
cfd.ext.elektra.DElementTrasladado oTrasladado = null;
cfd.ext.elektra.DElementImpuestos oImpuestos = null;
for (SDataDpsNotes notes : mvDbmsDpsNotes) {
sNotes += notes.getNotes() + "\n";
}
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
oDetalle = new DElementDetalle();
oDetalle.getAttFolio().setString(entry.getDbmsDpsAddElektraOrder());
oProducto = new DElementProducto();
oProducto.getAttCodigoBarras().setString(entry.getDbmsDpsAddElektraBarcode());
oProducto.getAttCajasEntregadas().setInteger(entry.getDbmsDpsAddElektraCages());
oProducto.getAttPrecioUnitarioCaja().setDouble(entry.getDbmsDpsAddElektraCagePriceUnitary());
oProducto.getAttPiezasEntregadas().setInteger(entry.getDbmsDpsAddElektraParts());
oProducto.getAttPrecioUnitarioPieza().setDouble(entry.getDbmsDpsAddElektraPartPriceUnitary());
oImpuestos = new DElementImpuestos();
dImpuestosTrasladados = 0;
for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) {
oTrasladado = new DElementTrasladado();
switch (tax.getFkTaxTypeId()) {
case SModSysConsts.FINS_TP_TAX_RETAINED:
switch (tax.getPkTaxBasicId()) {
case 1: // IVA
break;
case 2: // ISR
break;
default:
}
break;
case SModSysConsts.FINS_TP_TAX_CHARGED:
switch (tax.getPkTaxBasicId()) {
case 1: // IVA
oTrasladado.getAttImpuesto().setString("IVA");
break;
case 3: // IEPS
oTrasladado.getAttImpuesto().setString("IEPS");
break;
default:
}
oTrasladado.getAttImporte().setDouble(tax.getTaxCy());
oTrasladado.getAttTasa().setDouble(tax.getPercentage());
dImpuestosTrasladados += tax.getValue();
break;
default:
}
oImpuestos.getEltImpuestosTrasladados().getEltTrasladado().add(oTrasladado);
}
oDetalle.getEltProducto().getEltImpuestos().getAttTotalImpuestosTrasladados().setDouble(dImpuestosTrasladados);
oDetalle.getEltProducto().getEltImpuestos().getEltImpuestosTrasladados().getEltTrasladado().addAll(oImpuestos.getEltImpuestosTrasladados().getEltTrasladado());
oDetalle.getEltProducto().getAttCodigoBarras().setString(oProducto.getAttCodigoBarras().getString());
oDetalle.getEltProducto().getAttCajasEntregadas().setInteger(oProducto.getAttCajasEntregadas().getInteger());
oDetalle.getEltProducto().getAttPrecioUnitarioCaja().setDouble(oProducto.getAttPrecioUnitarioCaja().getDouble());
oDetalle.getEltProducto().getAttPiezasEntregadas().setInteger(oProducto.getAttPiezasEntregadas().getInteger());
oDetalle.getEltProducto().getAttPrecioUnitarioPieza().setDouble(oProducto.getAttPrecioUnitarioPieza().getDouble());
oDetailItems.getEltDetalle().add(oDetalle);
}
}
// Create addenda:
addendaElektra.getAttXmlns().setString("http:
addendaElektra.getAttSchemaLocation().setString("http:
addendaElektra.getAttTipoComprobante().setString(
SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_INV) ? "FE" :
SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_CN) ? "NC" :
SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_REC) ? "ND" : "?");
addendaElektra.getAttPlazoPago().setString(mnDaysOfCredit + " DIAS"); // XXX: Validate is 'DIAS' is declared like a constant
addendaElektra.getAttObservaciones().setString(sNotes);
addendaElektra.getEltDetalleProductos().getEltDetalle().addAll(oDetailItems.getEltDetalle());
return addendaElektra;
}
@Override
public int getCfdTipoCfdXml() {
return SCfdConsts.CFD_TYPE_DPS;
}
@Override
public String getCfdSerie() {
return msNumberSeries;
}
@Override
public String getCfdFolio() {
return msNumber;
}
@Override
public String getCfdReferencia() {
return msNumberReference;
}
@Override
public Date getCfdFecha() {
int[] anDateDps = SLibTimeUtilities.digestDate(mtDate);
int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs);
java.util.Date tDate = null;
GregorianCalendar oGregorianCalendar = null;
if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) {
tDate = mtUserEditTs;
}
else {
oGregorianCalendar = new GregorianCalendar();
oGregorianCalendar.setTime(mtUserEditTs);
oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]);
oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0
oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]);
tDate = oGregorianCalendar.getTime();
}
return tDate;
}
@Override
public int getCfdFormaDePago() {
return mnPayments;
}
@Override
public int getCfdCondicionesDePago() {
return mnFkPaymentTypeId == SDataConstantsSys.TRNS_TP_PAY_CASH ? DAttributeOptionCondicionesPago.CFD_CONTADO : DAttributeOptionCondicionesPago.CFD_CREDITO;
}
@Override
public double getCfdSubTotal() {
return mdSubtotalProvisionalCy_r;
}
@Override
public double getCfdDescuento() {
return 0;
}
@Override
public String getCfdMotivoDescuento() {
return "";
}
@Override
public double getCfdTipoCambio() {
return mdExchangeRate;
}
@Override
public String getCfdMoneda() {
return msDbmsCurrencyKey;
}
@Override
public double getCfdTotal() {
return mdTotalCy_r;
}
@Override
public int getCfdTipoDeComprobante() {
return isDocument() ? DAttributeOptionTipoComprobante.CFD_INGRESO : DAttributeOptionTipoComprobante.CFD_EGRESO;
}
@Override
public String getCfdMetodoDePago() {
return msPaymentMethod;
}
@Override
public String getCfdNumCtaPago() {
return msPaymentAccount;
}
@Override
public int getEmisor() {
return moAuxCfdParams.getEmisor().getPkBizPartnerId();
}
@Override
public int getSucursalEmisor() {
return mnFkCompanyBranchId;
}
@Override
public int getReceptor() {
return mnFkBizPartnerId_r;
}
@Override
public int getSucursalReceptor() {
return mnFkBizPartnerBranchId;
}
@Override
public ArrayList<DElement> getCfdElementRegimenFiscal() {
ArrayList<DElement> regimes = null;
DElement regimen = null;
for (int i = 0; i < moAuxCfdParams.getRegimenFiscal().length; i++) {
regimes = new ArrayList<DElement>();
regimen = new cfd.ver3.DElementRegimenFiscal();
((cfd.ver3.DElementRegimenFiscal) regimen).getAttRegimen().setString(moAuxCfdParams.getRegimenFiscal()[i]);
regimes.add(regimen);
}
return regimes;
}
@Override
public DElement getCfdElementAddenda() {
DElement addenda = null;
// Create custom addendas when needed:
try {
if (moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getFkCfdAddendaTypeId() != SDataConstantsSys.BPSS_TP_CFD_ADD_NA) {
addenda = new cfd.ver3.DElementAddenda();
if (isDocumentSal() || isAdjustmentSal()) {
switch (moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getFkCfdAddendaTypeId()) {
case SDataConstantsSys.BPSS_TP_CFD_ADD_SORIANA:
((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaSoriana());
break;
case SDataConstantsSys.BPSS_TP_CFD_ADD_LOREAL:
((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaLoreal(mdCfdIvaPorcentaje));
break;
case SDataConstantsSys.BPSS_TP_CFD_ADD_BACHOCO:
((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaBachoco(mdCfdIvaPorcentaje));
break;
case SDataConstantsSys.BPSS_TP_CFD_ADD_MODELO:
((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaGrupoModelo(mdCfdIvaPorcentaje));
break;
case SDataConstantsSys.BPSS_TP_CFD_ADD_ELEKTRA:
((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaElektra());
break;
default:
throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN);
}
}
}
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
return addenda;
}
@Override
public DElement getCfdElementComplemento() {
return null;
}
@Override
public ArrayList<SCfdDataConcepto> getCfdConceptos() {
String descripcion = "";
SCfdDataConcepto conceptoXml = null;
ArrayList<SCfdDataConcepto> conceptosXml = new ArrayList<SCfdDataConcepto>();
for (SDataDpsEntry dpsEntry : mvDbmsDpsEntries) {
if (dpsEntry.isAccountable()) {
descripcion = dpsEntry.getConcept();
for (SDataDpsEntryNotes dpsEntryNotes : dpsEntry.getDbmsEntryNotes()) {
if (dpsEntryNotes.getIsCfd()) {
descripcion += "\n- " + dpsEntryNotes.getNotes();
}
}
conceptoXml = new SCfdDataConcepto();
conceptoXml.setNoIdentificacion(dpsEntry.getConceptKey());
conceptoXml.setUnidad(dpsEntry.getDbmsOriginalUnitSymbol());
conceptoXml.setCantidad(dpsEntry.getOriginalQuantity());
conceptoXml.setDescripcion(descripcion);
conceptoXml.setValorUnitario(dpsEntry.getSubtotalCy_r() / dpsEntry.getOriginalQuantity());
conceptoXml.setImporte(dpsEntry.getSubtotalCy_r());
conceptosXml.add(conceptoXml);
}
}
return conceptosXml;
}
@Override
public ArrayList<SCfdDataImpuesto> getCfdImpuestos() {
double dImptoTasa = 0;
double dImpto = 0;
Double oValue = null;
Set<Double> setKeyImptos = null;
HashMap<Double, Double> hmImpto = null;
HashMap<Double, Double> hmRetenidoIva = new HashMap<Double, Double>();
HashMap<Double, Double> hmRetenidoIsr = new HashMap<Double, Double>();
HashMap<Double, Double> hmTrasladadoIva = new HashMap<Double, Double>();
HashMap<Double, Double> hmTrasladadoIeps = new HashMap<Double, Double>();
ArrayList<SCfdDataImpuesto> impuestosXml = null;
SCfdDataImpuesto impuestoXml = null;
impuestosXml = new ArrayList<SCfdDataImpuesto>();
try {
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
if (entry.isAccountable()) {
for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) {
if (tax.getFkTaxCalculationTypeId() != SModSysConsts.FINS_TP_TAX_CAL_RATE) {
throw new Exception("Todos los impuestos deben ser en base a una tasa (" + tax.getFkTaxCalculationTypeId() + ").");
}
else {
hmImpto = null;
dImptoTasa = 0;
switch (tax.getFkTaxTypeId()) {
case SModSysConsts.FINS_TP_TAX_RETAINED:
switch (tax.getPkTaxBasicId()) {
case 1: // IVA
dImptoTasa = 1; // on CFDI's XML retained taxes have no rate
hmImpto = hmRetenidoIva;
break;
case 2: // ISR
dImptoTasa = 1; // on CFDI's XML retained taxes have no rate
hmImpto = hmRetenidoIsr;
break;
default:
throw new Exception("Todos los impuestos retenidos deben ser conocidos (" + tax.getPkTaxBasicId() + ").");
}
break;
case SModSysConsts.FINS_TP_TAX_CHARGED:
switch (tax.getPkTaxBasicId()) {
case 1: // IVA
hmImpto = hmTrasladadoIva;
break;
case 3: // IEPS
hmImpto = hmTrasladadoIeps;
break;
default:
throw new Exception("Todos los impuestos trasladados deben ser conocidos (" + tax.getPkTaxBasicId() + ").");
}
break;
default:
throw new Exception("Todos los tipos de impuestos deben ser conocidos (" + tax.getFkTaxTypeId() + ").");
}
if (dImptoTasa == 0) {
dImptoTasa = tax.getPercentage();
}
oValue = hmImpto.get(dImptoTasa);
dImpto = oValue == null ? 0 : oValue.doubleValue();
hmImpto.put(dImptoTasa, dImpto + tax.getTaxCy());
}
}
}
}
// Retained taxes:
hmImpto = hmRetenidoIva;
if (!hmImpto.isEmpty()) {
setKeyImptos = hmImpto.keySet();
for (Double key : setKeyImptos) {
dImpto = hmImpto.get(key);
if (dImpto != 0) {
impuestoXml = new SCfdDataImpuesto();
impuestoXml.setImpuesto(DAttributeOptionImpuestoRetencion.CFD_IVA);
impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_RETAINED);
impuestoXml.setTasa(1);
impuestoXml.setImporte(dImpto);
impuestosXml.add(impuestoXml);
}
}
}
hmImpto = hmRetenidoIsr;
if (!hmImpto.isEmpty()) {
setKeyImptos = hmImpto.keySet();
for (Double key : setKeyImptos) {
dImpto = hmImpto.get(key);
if (dImpto != 0) {
impuestoXml = new SCfdDataImpuesto();
impuestoXml.setImpuesto(DAttributeOptionImpuestoRetencion.CFD_ISR);
impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_RETAINED);
impuestoXml.setTasa(1);
impuestoXml.setImporte(dImpto);
impuestosXml.add(impuestoXml);
}
}
}
// Charged taxes:
hmImpto = hmTrasladadoIva;
if (!hmImpto.isEmpty()) {
setKeyImptos = hmImpto.keySet();
for (Double key : setKeyImptos) {
dImpto = hmImpto.get(key);
impuestoXml = new SCfdDataImpuesto();
impuestoXml.setImpuesto(DAttributeOptionImpuestoTraslado.CFD_IVA);
impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_CHARGED);
impuestoXml.setTasa(key * 100.0);
impuestoXml.setImporte(dImpto);
mdCfdIvaPorcentaje = (key * 100.0);
impuestosXml.add(impuestoXml);
}
}
hmImpto = hmTrasladadoIeps;
if (!hmImpto.isEmpty()) {
setKeyImptos = hmImpto.keySet();
for (Double key : setKeyImptos) {
dImpto = hmImpto.get(key);
impuestoXml = new SCfdDataImpuesto();
impuestoXml.setImpuesto(DAttributeOptionImpuestoTraslado.CFD_IEPS);
impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_CHARGED);
impuestoXml.setTasa(key * 100.0);
impuestoXml.setImporte(dImpto);
impuestosXml.add(impuestoXml);
}
}
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
return impuestosXml;
}
public void saveField(java.sql.Connection connection, final int[] pk, final int field, final Object value) throws Exception {
String sSql = "";
mnLastDbActionResult = SLibConsts.UNDEFINED;
sSql = "UPDATE trn_dps SET ";
switch (field) {
case FIELD_REF_BKR:
sSql += "comms_ref = '" + value + "' ";
break;
case FIELD_SAL_AGT:
sSql += "fid_sal_agt_n = " + value + " ";
break;
case FIELD_SAL_AGT_SUP:
sSql += "fid_sal_sup_n = " + value + " ";
break;
case FIELD_CLO_COMMS:
sSql += "b_close_comms = " + value + " ";
break;
case FIELD_CLO_COMMS_USR:
sSql += "fid_usr_close_comms = " + value + ", ts_close_comms = NOW() ";
case FIELD_USR:
sSql += "fid_usr_edit = " + value + ", ts_edit = NOW() ";
break;
default:
throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN);
}
sSql += "WHERE id_year = " + pk[0] + " AND id_doc = " + pk[1];
connection.createStatement().execute(sSql);
mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_OK;
}
public void sendMail(SClientInterface client, Object dpsKey, int mmsType) {
int[] mmsConfigKey = null;
String msg = "";
String companyName = "";
String bpName = "";
String dpsDestNumber = "";
String dpsReference = "";
ArrayList<String> toRecipients = null;
HashSet<String> setCfgEmail = new HashSet<>();
SDbMmsConfig mmsConfig = null;
SDataDpsType moDpsType = null;
SDataDps dpsDest = null;
boolean isEdited = false;
boolean send = true;
read(dpsKey, client.getSession().getStatement());
isEdited = mtUserNewTs.compareTo(mtUserEditTs) != 0;
companyName = client.getSessionXXX().getCompany().getCompany();
bpName = SDataReadDescriptions.getCatalogueDescription(client, SDataConstants.BPSU_BP, new int[] { mnFkBizPartnerId_r }, SLibConstants.DESCRIPTION_NAME);
moDpsType = (SDataDpsType) SDataUtilities.readRegistry(client, SDataConstants.TRNU_TP_DPS, getDpsTypeKey(), SLibConstants.EXEC_MODE_VERBOSE);
dpsReference = !getNumberReference().isEmpty() ? getNumberReference() : "N/D";
toRecipients = new ArrayList<>();
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
try {
mmsConfigKey = STrnUtilities.readMmsConfigurationByLinkType(client, mmsType, entry.getFkItemId());
if (mmsConfigKey[0] != SLibConsts.UNDEFINED) {
mmsConfig = new SDbMmsConfig();
mmsConfig.read(client.getSession(), mmsConfigKey);
setCfgEmail.add(mmsConfig.getEmail());
}
}
catch (java.lang.Exception e) {
SLibUtilities.renderException(this, e);
}
}
if (!setCfgEmail.isEmpty()) {
msg = "Se enviará correo-e de notificación a los siguientes destinatarios:";
for (String email : setCfgEmail) {
msg += "\n" + email;
}
client.showMsgBoxInformation(msg);
}
else {
send = false;
}
if (send) {
for (String cfgEmail : setCfgEmail) {
try {
msg = STrnUtilities.computeMailHeaderBeginTable(companyName, moDpsType.getDpsType(), getDpsNumber(), bpName, mtDate, (isEdited ? mtUserEditTs : mtUserNewTs), isEdited, mbIsRebill);
for (SDataDpsEntry entry : mvDbmsDpsEntries) {
mmsConfigKey = STrnUtilities.readMmsConfigurationByLinkType(client, mmsType, entry.getFkItemId());
if (mmsConfigKey[0] != SLibConsts.UNDEFINED) {
mmsConfig = new SDbMmsConfig();
mmsConfig.read(client.getSession(), mmsConfigKey);
if (cfgEmail.compareTo(mmsConfig.getEmail()) == 0) {
if (entry.getDbmsDpsLinksAsDestiny()!= null && !entry.getDbmsDpsLinksAsDestiny().isEmpty()) {
dpsDest = (SDataDps) SDataUtilities.readRegistry(client, SDataConstants.TRN_DPS, entry.getDbmsDpsLinksAsDestiny().get(0).getDbmsSourceDpsKey(), SLibConstants.EXEC_MODE_STEALTH);
dpsDestNumber = dpsDest.getDpsNumber();
}
else {
dpsDestNumber = "N/D";
}
msg += STrnUtilities.computeMailItem(client, entry.getFkItemId(), entry.getFkOriginalUnitId(), entry.getConceptKey(), entry.getConcept(), dpsDestNumber, msNumberSeries, msNumber, dpsReference, entry.getOriginalQuantity(), entry.getDbmsUnitSymbol(), getDate(), getDate(), getDpsTypeKey(), isEdited, mbIsRebill);
}
}
}
msg += STrnUtilities.computeMailFooterEndTable(SClient.APP_NAME , SClient.APP_COPYRIGHT, SClient.APP_PROVIDER, SClient.VENDOR_WEBSITE , SClient.APP_RELEASE);
toRecipients.add(cfgEmail);
STrnUtilities.sendMail(client, mmsType, toRecipients, null, null, msg);
toRecipients.clear();
}
catch (java.lang.Exception e) {
SLibUtilities.printOutException(this, e);
}
}
}
}
}
|
package org.openoffice.test;
import com.sun.star.bridge.UnoUrlResolver;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.connection.NoConnectException;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.DisposedException;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.UUID;
import static org.junit.Assert.*;
/** Start up and shut down an OOo instance.
Details about the OOo instance are tunneled in via
org.openoffice.test.arg.... system properties.
*/
public final class OfficeConnection {
/** Start up an OOo instance.
*/
public void setUp() throws Exception {
String sofficeArg = Argument.get("soffice");
if (sofficeArg.startsWith("path:")) {
description = "pipe,name=oootest" + UUID.randomUUID();
ProcessBuilder pb = new ProcessBuilder(
sofficeArg.substring("path:".length()), "--quickstart=no",
"--nofirststartwizard", "--norestore",
"--accept=" + description + ";urp",
"-env:UserInstallation=" + Argument.get("user"),
"-env:UNO_JAVA_JFW_ENV_JREHOME=true");
String envArg = Argument.get("env");
if (envArg != null) {
Map<String, String> env = pb.environment();
int i = envArg.indexOf("=");
if (i == -1) {
env.remove(envArg);
} else {
env.put(envArg.substring(0, i), envArg.substring(i + 1));
}
}
process = pb.start();
outForward = new Forward(process.getInputStream(), System.out);
outForward.start();
errForward = new Forward(process.getErrorStream(), System.err);
errForward.start();
} else if (sofficeArg.startsWith("connect:")) {
description = sofficeArg.substring("connect:".length());
} else {
fail(
"\"soffice\" argument \"" + sofficeArg +
" starts with neither \"path:\" nor \"connect:\"");
}
XUnoUrlResolver resolver = UnoUrlResolver.create(
Bootstrap.createInitialComponentContext(null));
for (;;) {
try {
context = UnoRuntime.queryInterface(
XComponentContext.class,
resolver.resolve(
"uno:" + description +
";urp;StarOffice.ComponentContext"));
break;
} catch (NoConnectException e) {}
if (process != null) {
assertNull(waitForProcess(process, 1000)); // 1 sec
}
}
}
/** Shut down the OOo instance.
*/
public void tearDown()
throws InterruptedException, com.sun.star.uno.Exception
{
boolean desktopTerminated = true;
if (process != null) {
if (context != null) {
XMultiComponentFactory factory = context.getServiceManager();
assertNotNull(factory);
XDesktop desktop = UnoRuntime.queryInterface(
XDesktop.class,
factory.createInstanceWithContext(
"com.sun.star.frame.Desktop", context));
context = null;
try {
desktopTerminated = desktop.terminate();
} catch (DisposedException e) {}
// it appears that DisposedExceptions can already happen
// while receiving the response of the terminate call
desktop = null;
} else {
process.destroy();
}
}
int code = 0;
if (process != null) {
code = process.waitFor();
}
boolean outTerminated = outForward == null || outForward.terminated();
boolean errTerminated = errForward == null || errForward.terminated();
assertTrue(desktopTerminated);
assertEquals(0, code);
assertTrue(outTerminated);
assertTrue(errTerminated);
}
/** Obtain the component context of the running OOo instance.
*/
public XComponentContext getComponentContext() {
return context;
}
//TODO: get rid of this hack for legacy qa/unoapi tests
public String getDescription() {
return description;
}
private static Integer waitForProcess(Process process, final long millis)
throws InterruptedException
{
final Thread t1 = Thread.currentThread();
Thread t2 = new Thread("waitForProcess") {
public void run() {
try {
Thread.currentThread().sleep(millis);
} catch (InterruptedException e) {}
t1.interrupt();
}
};
boolean old = Thread.interrupted();
// clear interrupted status, get old status
t2.start();
int n = 0;
boolean done = false;
try {
n = process.waitFor();
done = true;
} catch (InterruptedException e) {}
t2.interrupt();
try {
t2.join();
} catch (InterruptedException e) {
t2.join();
}
Thread.interrupted(); // clear interrupted status
if (old) {
t1.interrupt(); // reset old status
}
return done ? new Integer(n) : null;
}
private static final class Forward extends Thread {
public Forward(InputStream in, PrintStream out) {
super("process output forwarder");
this.in = in;
this.out = out;
}
public void run() {
for (;;) {
byte[] buf = new byte[1024];
int n;
try {
n = in.read(buf);
} catch (IOException e) {
throw new RuntimeException("wrapping", e);
}
if (n == -1) {
break;
}
out.write(buf, 0, n);
}
done = true;
}
public boolean terminated() throws InterruptedException {
join();
return done;
}
private final InputStream in;
private final PrintStream out;
private boolean done = false;
}
private String description;
private Process process = null;
private Forward outForward = null;
private Forward errForward = null;
private XComponentContext context = null;
}
|
package app.hongs.action;
import app.hongs.Cnst;
import app.hongs.Core;
import app.hongs.CoreConfig;
import app.hongs.CoreLogger;
import app.hongs.HongsError;
import app.hongs.HongsUnchecked;
import app.hongs.util.Data;
import app.hongs.util.Dict;
import java.io.File;
import java.io.Writer;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*
*
* <p>
* getRequestData, getParameter, getAttribute, getSessValue
* //, reply
* </p>
*
* @author Hongs
*/
public class ActionHelper implements Cloneable
{
/**
* HttpServletRequest
*/
private HttpServletRequest request;
private Map<String, Object> requestData = null;
private Map<String, Object> contextData = null;
private Map<String, Object> sessionData = null;
private Map<String, String> cookiesData = null;
/**
* HttpServletResponse
*/
private HttpServletResponse response;
private Map<String, Object> responseData = null;
private OutputStream outputStream = null;
private Writer outputWriter = null;
/**
* (cmdlet)
*
* @param req
* @param att
* @param ses Session
* @param cok Cookies
*/
public ActionHelper(Map req, Map att, Map ses, Map cok)
{
this.request = null;
this.requestData = req != null ? req : new HashMap();
this.contextData = att != null ? att : new HashMap();
this.sessionData = ses != null ? ses : new HashMap();
this.cookiesData = cok != null ? cok : new HashMap();
this.response = null;
}
/**
* (action)
*
* @param req
* @param rsp
*/
public ActionHelper(HttpServletRequest req, HttpServletResponse rsp)
{
this.request = req;
this.response = rsp;
try
{
if (null != this.request )
{
this.request .setCharacterEncoding("UTF-8");
}
if (null != this.response)
{
this.response.setCharacterEncoding("UTF-8");
}
}
catch (UnsupportedEncodingException ex)
{
throw new HongsError(0x31, "Can not set encoding.", ex);
}
}
public void reinitHelper(HttpServletRequest req, HttpServletResponse rsp)
{
this.request = req;
this.response = rsp;
try
{
if (null != this.request )
{
this.request .setCharacterEncoding("UTF-8");
}
if (null != this.response)
{
this.response.setCharacterEncoding("UTF-8");
}
}
catch (UnsupportedEncodingException ex)
{
throw new HongsError(0x31, "Can not set encoding.", ex);
}
}
public void setRequestData(Map<String, Object> data) {
this.requestData = data;
}
public void setContextData(Map<String, Object> data) {
this.contextData = data;
}
public void setSessionData(Map<String, Object> data) {
this.sessionData = data;
}
public void setCookiesData(Map<String, String> data) {
this.cookiesData = data;
}
public void setOutputStream(OutputStream pipe) {
this.outputStream = pipe;
}
public void setOutputWriter(Writer pipe) {
this.outputWriter = pipe;
}
public final HttpServletRequest getRequest()
{
return this.request;
}
/**
*
* @return
*/
public String getRequestText()
{
if (null != this.request) try
{
BufferedReader reader = this.request.getReader();
String text = "";
char[] buf = new char[1024];
int i = 0, j = 0;
while (-1 != ( i = reader.read(buf, j, 1024) ) )
{
text += new String ( buf);
j += i * 1024 ;
}
return text;
}
catch (IOException ex)
{
CoreLogger.error(ex);
}
return "";
}
/**
*
*
* request.getParameterMap,
* "[]"List, "[xxx]"Map, .
* "." , a.b.c a[b][c] .
* ".""[]".
* Content-Type"multipart/form-data", apache-common-fileupload .
*
* @return
*/
public Map<String, Object> getRequestData()
{
if (this.request != null && this.requestData == null)
{
String ct = this.request.getContentType();
if ( ct != null)
{
ct = ct.split(";", 2)[0];
}
else
{
ct = "application/x-www-form-urlencode" ;
}
if ("application/json".equals(ct) || "text/json".equals(ct))
{
this.requestData = (Map<String, Object>) Data.toObject(getRequestText());
}
else
{
this.requestData = parseParam(request.getParameterMap( ));
if ("multipart/form-data".equals(ct))
{
getUploadsData( this.requestData );
}
}
}
return this.requestData;
}
/**
* multipart/form-data ,
* @param rd
*/
final void getUploadsData(Map rd) {
CoreConfig conf = CoreConfig.getInstance();
String path = Core.DATA_PATH+"/upload";
File df = new File (path);
if (!df.isDirectory()) {
df.mkdirs();
}
Set<String> allowTypes = null;
Set<String> denyTypes = null;
Set<String> allowExtns = null;
Set<String> denyExtns = null;
String x;
x = conf.getProperty("fore.upload.allow.types", null);
if (x != null) {
allowTypes = new HashSet(Arrays.asList(x.split(",")));
}
x = conf.getProperty("fore.upload.deny.types" , null);
if (x != null) {
denyTypes = new HashSet(Arrays.asList(x.split(",")));
}
x = conf.getProperty("fore.upload.allow.extns", null);
if (x != null) {
allowExtns = new HashSet(Arrays.asList(x.split(",")));
}
x = conf.getProperty("fore.upload.deny.extns" , null);
if (x != null) {
denyExtns = new HashSet(Arrays.asList(x.split(",")));
}
long fileSizeMax = 0;
long fullSizeMax = 0;
long i;
i = conf.getProperty("fore.upload.file.size.max", 0);
if ( i != 0 ) {
fileSizeMax = i;
}
i = conf.getProperty("fore.upload.full.size.max", 0);
if ( i != 0 ) {
fullSizeMax = i;
}
Set<String> uploadKeys = new HashSet();
setAttribute(Cnst.UPLOAD_ATTR, uploadKeys);
/
try {
ServletFileUpload sfu = new ServletFileUpload();
if (fileSizeMax > 0) {
sfu.setFileSizeMax(fullSizeMax);
}
if (fullSizeMax > 0) {
sfu.setSizeMax(fullSizeMax);
}
FileItemIterator fit = sfu.getItemIterator(request);
while (fit.hasNext()) {
FileItemStream fis = fit.next();
String n = fis.getFieldName();
String v;
if (fis.isFormField()) {
v = Streams.asString(fis.openStream());
} else {
String type = fis.getContentType();
if (type != null) {
type = type.split(";" , 2)[0];
} else {
type = "";
}
if (allowTypes != null && !allowTypes.contains(type)) {
continue;
}
if ( denyTypes != null && denyTypes.contains(type)) {
continue;
}
String extn;
String name = fis.getName().replaceAll("[\r\n]", "");
int pos = name.lastIndexOf('.');
if (pos > 1) {
extn = name.substring(1+pos);
}
else {
extn = "";
}
if (allowExtns != null && !allowExtns.contains(extn)) {
continue;
}
if ( denyExtns != null && denyExtns.contains(extn)) {
continue;
}
v = Core.getUniqueId();
String file = path + File.separator + v + ".tmp";
String info = path + File.separator + v + ".tnp";
FileOutputStream fos = new FileOutputStream(new File( file ));
BufferedInputStream bis = new BufferedInputStream(fis.openStream());
BufferedOutputStream bos = new BufferedOutputStream(fos);
long size = Streams.copy(bis, bos, true );
if (size == 0) {
continue;
}
try(FileWriter fw = new FileWriter(info)) {
fw.write(name+ "\r\n" + type + "\r\n" +size);
}
}
Dict.setParam (rd, v, n);
uploadKeys.add( n);
}
} catch (FileUploadException ex) {
throw new HongsUnchecked(0x1110, ex);
} catch (IOException ex) {
throw new HongsUnchecked(0x1110, ex);
}
}
public final HttpServletResponse getResponse()
{
return this.response;
}
/**
*
*
* :
* ,
* reply ,
* ,
* null.
*
* @return
*/
public Map<String, Object> getResponseData()
{
return this.responseData;
}
/**
*
* @return
*/
public OutputStream getOutputStream()
{
if (this.outputStream != null)
{
return this.outputStream;
} else
if (this.response != null)
{
try
{
return this.response.getOutputStream();
}
catch (IOException ex)
{
throw new HongsError(0x32, "Can not get output stream.", ex);
}
} else
{
throw new HongsError(0x32, "Can not get output stream.");
}
}
/**
*
* @return
*/
public Writer getOutputWriter()
{
if (this.outputWriter != null)
{
return this.outputWriter;
} else
if (this.response != null)
{
try
{
return this.response.getWriter();
}
catch (IOException ex)
{
throw new HongsError(0x32, "Can not get output writer.", ex);
}
} else
{
throw new HongsError(0x32, "Can not get output writer.");
}
}
/**
*
* @param name
* @return
*/
public String getParameter(String name)
{
Object o = Dict.getParam(getRequestData(), name);
if (o == null)
{
return null;
}
if (o instanceof Map )
{
o = new ArrayList(((Map) o).values());
}
if (o instanceof Set )
{
o = new ArrayList(((Set) o));
}
if (o instanceof List)
{
List a = (List) o;
int i = a.size();
o = a.get(i - 1);
}
return o.toString();
}
/**
*
* ; , name "[","]""."
* @param name
* @return , null
*/
public Object getAttribute(String name)
{
if (null != this.contextData) {
return this.contextData.get(name);
} else
if (null != this.request) {
return this.request.getAttribute(name);
} else {
return null;
}
}
/**
*
* ; , name "[","]""."
* value null name
* @param name
* @param value
*/
public void setAttribute(String name, Object value)
{
if (this.contextData != null) {
if (value == null) {
this.contextData.remove(name);
} else {
this.contextData.put(name , value);
}
this.contextData.put(Cnst.UPDATE_ATTR, System.currentTimeMillis());
} else
if (this.request != null) {
if (value == null) {
this.request.removeAttribute(name);
} else {
this.request.setAttribute(name , value);
}
}
}
/**
*
* ; , name "[","]""."
* @param name
* @return , null
*/
public Object getSessibute(String name)
{
if (null != this.sessionData) {
return this.sessionData.get(name);
} else
if (null != this.request) {
HttpSession ss = this.request.getSession(false);
if (null != ss ) return ss.getAttribute ( name);
return null;
} else {
return null;
}
}
/**
*
* ; , name "[","]""."
* value null name
* @param name
* @param value
*/
public void setSessibute(String name, Object value)
{
if (this.sessionData != null) {
if (value == null) {
this.sessionData.remove(name);
} else {
this.sessionData.put(name , value);
}
this.sessionData.put(Cnst.UPDATE_ATTR, System.currentTimeMillis());
} else
if (this.request != null) {
if (value == null) {
HttpSession ss = this.request.getSession(false);
if (null != ss ) ss.removeAttribute(name);
} else {
HttpSession ss = this.request.getSession(true );
if (null != ss ) ss.setAttribute(name , value );
}
}
}
/**
*
* @param name
* @return
*/
public String getCookibute(String name) {
if (null != this.cookiesData) {
return this.cookiesData.get(name);
} else
if (null != this.request) {
Cookie [] cs = this.request.getCookies();
if (cs != null) {
for(Cookie ce: cs) {
if (ce.getName().equals(name)) {
try {
return URLDecoder.decode(ce.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HongsUnchecked.Common ( e);
}
}
}
}
return null;
} else {
return null;
}
}
/**
*
* @param name
* @param value
*/
public void setCookibute(String name, String value) {
if (this.cookiesData != null) {
if (value == null) {
this.cookiesData.remove(name);
} else {
this.cookiesData.put(name, value);
}
this.cookiesData.put(Cnst.UPDATE_ATTR, Long.toString(System.currentTimeMillis()));
} else
if (this.response != null) {
if (value == null) {
setCookibute(name, value, 0/*Remove*/, Core.BASE_HREF + "/", null, false, false );
} else {
setCookibute(name, value, Cnst.CL_DEF, Core.BASE_HREF + "/", null, false, false );
}
}
}
/**
*
* : Cookie
* @param name
* @param value
* @param life ()
* @param path
* @param host
* @param httpOnly
* @param secuOnly
*/
public void setCookibute(String name, String value,
int life, String path, String host, boolean httpOnly, boolean secuOnly) {
if (value != null) {
try {
value = URLEncoder.encode(value,"UTF-8");
} catch ( UnsupportedEncodingException e ) {
throw new HongsError.Common(e);
}
}
Cookie ce = new Cookie(name , value);
if (path != null) {
ce.setPath (path);
}
if (host != null) {
ce.setDomain(host);
}
if (life >= 0 ) {
ce.setMaxAge(life);
}
if (secuOnly) {
ce.setSecure(true);
}
if (httpOnly) {
ce.setHttpOnly(true);
}
response.addCookie( ce );
}
/**
* ActionHelper ActionDriver,CmdletRunner
* @return
* @deprecated
*/
public static ActionHelper getInstance()
{
throw new HongsError.Common("Please use the ActionHelper in the coverage of the ActionDriver or CmdletRunner inside");
}
/**
*
* ActionRunner ,
* setXxxxxData .
* @return
*/
public static ActionHelper newInstance() {
Core core = Core.getInstance();
String inst = ActionHelper.class.getName();
if (core.containsKey(inst)) {
return ((ActionHelper) core.got(inst)).clone( );
} else {
return new ActionHelper(null, null, null, null);
}
}
/**
*
* ActionRunner ,
* setXxxxxData .
* @return
*/
@Override
public ActionHelper clone() {
ActionHelper helper;
try {
helper = (ActionHelper) super.clone();
} catch (CloneNotSupportedException ex) {
throw new HongsError.Common( ex);
}
helper.outputStream = this.getOutputStream();
helper.outputWriter = this.getOutputWriter();
helper.responseData = null;
return helper;
}
/
/**
*
* retrieve
* @param map
*/
public void reply(Map map)
{
if(!map.containsKey("ok" )) {
map.put("ok", true);
}
if(!map.containsKey("ern")) {
map.put("ern", "" );
}
if(!map.containsKey("err")) {
map.put("err", "" );
}
if(!map.containsKey("msg")) {
map.put("msg", "" );
}
this.responseData = map;
}
/**
*
* create
* @param msg
* @param info
*/
public void reply(String msg, Map info)
{
Map map = new HashMap();
if (null != msg) {
map.put("msg", msg);
}
map.put("info", info);
reply(map);
}
/**
*
* update,delete
* @param msg
* @param rows
*/
public void reply(String msg, int rows)
{
Map map = new HashMap();
if (null != msg) {
map.put("msg", msg);
}
map.put("rows", rows);
reply(map);
}
/**
*
* unique,exists
* @param msg
* @param ok rows 1,0
*/
public void reply(String msg, boolean ok)
{
Map map = new HashMap();
if (null != msg) {
map.put("msg", msg);
}
map.put("rows", ok ? 1 : 0);
reply(map);
}
/**
*
* @param msg
*/
public void reply(String msg)
{
Map map = new HashMap();
if (null != msg) {
map.put("msg", msg);
}
reply(map);
}
/**
*
* @param msg
*/
public void fault(String msg)
{
Map map = new HashMap();
if (null != msg) {
map.put("msg", msg);
}
map.put("ok", false);
reply(map);
}
/**
*
* @param msg
* @param ern
*/
public void fault(String msg, String ern)
{
Map map = new HashMap();
if (null != msg) {
map.put("msg", msg);
}
if (null != ern) {
map.put("ern", ern);
}
map.put("ok", false);
reply(map);
}
/**
*
* @param msg
* @param ern
* @param err
*/
public void fault(String msg, String ern, String err)
{
Map map = new HashMap();
if (null != msg) {
map.put("msg", msg);
}
if (null != ern) {
map.put("ern", ern);
}
if (null != err) {
map.put("err", err);
}
map.put("ok", false);
reply(map);
}
/
/**
*
* @param txt
* @param ctt Content-Type , text/html
* @param cst Content-Type , utf-8
*/
public void print(String txt, String ctt, String cst)
{
if (this.response != null && !this.response.isCommitted()) {
if (cst != null) {
this.response.setCharacterEncoding(cst);
}
if (ctt != null) {
this.response.setContentType(ctt);
}
}
try {
this.getOutputWriter( ).write(txt);
} catch (IOException e) {
throw new HongsError(0x32, "Can not send to client.", e);
}
}
/**
*
* @param txt
* @param ctt
*/
public void print(String txt, String ctt)
{
this.print(txt,ctt,"UTF-8");
}
/**
*
* @param htm
*/
public void print(String htm)
{
this.print(htm,"text/html");
}
/**
*
*
* @param dat
*/
public void print(Object dat)
{
String str = Data.toString( dat );
this.print(str,"application/json");
}
/
/**
*
* JSON/JSONP , UTF-8
*/
public void responed()
{
Writer pw = this.getOutputWriter( );
String pb = CoreConfig.getInstance().getProperty ("core.powered.by");
String cb = ( String ) this.request.getAttribute( Cnst.BACK_ATTR );
if (this.response.isCommitted() != true) {
this.response.setContentType(cb != null ? "text/javascript" : "application/json");
this.response.setCharacterEncoding("UTF-8");
}
if (pb != null) {
this.response.setHeader("X-Powered-By", pb);
}
try {
if (cb != null) {
pw.write("function " + cb + "() {return " );
pw.write( Data.toString(this.responseData));
pw.write(";}");
} else {
pw.write( Data.toString(this.responseData));
}
} catch (IOException ex ) {
throw new HongsError(0x32, "Can not send to client.", ex);
}
this.responseData = null;
}
/**
* 302
* @param url
*/
public void redirect(String url)
{
this.response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
this.response.setHeader("Location", url);
this.responseData = null;
}
/**
* 400
* @param msg
*/
public void error400(String msg)
{
this.response.setStatus(HttpServletResponse.SC_BAD_REQUEST );
this.responseData = null;
this.print(msg);
}
/**
* 401
* @param msg
*/
public void error401(String msg)
{
this.response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
this.responseData = null;
this.print(msg);
}
/**
* 403
* @param msg
*/
public void error403(String msg)
{
this.response.setStatus(HttpServletResponse.SC_FORBIDDEN);
this.responseData = null;
this.print(msg);
}
/**
* 404
* @param msg
*/
public void error404(String msg)
{
this.response.setStatus(HttpServletResponse.SC_NOT_FOUND);
this.responseData = null;
this.print(msg);
}
/**
* 405
* @param msg
*/
public void error405(String msg)
{
this.response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
this.responseData = null;
this.print(msg);
}
/**
* 500
* @param msg
*/
public void error500(String msg)
{
this.response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
this.responseData = null;
this.print(msg);
}
/**
* 500
* @param ex
*/
public void error500(Throwable ex)
{
this.error500(ex.getLocalizedMessage());
}
/
/**
*
*
* @param s
* @return
*/
public static Map parseQuery(String s) {
HashMap<String, List<String>> a = new HashMap<>();
int j , i;
j = 0;
while (j < s.length()) {
i = j;
while (j < s.length() && s.charAt(j) != '=' && s.charAt(j) != '&') {
j ++;
}
String k;
try {
k = s.substring(i, j);
k = URLDecoder.decode(k, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new HongsError.Common(ex);
}
if (j < s.length() && s.charAt(j) == '=') {
j++;
}
i = j;
while (j < s.length() && s.charAt(j) != '&') {
j++;
}
String v;
try {
v = s.substring(i, j);
v = URLDecoder.decode(v, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new HongsError.Common(ex);
}
if (j < s.length() && s.charAt(j) == '&') {
j++;
}
Dict.setParam(a, v, k);
}
return a;
}
/**
*
* Servlet
* @param params
* @return Map
*/
public static Map parseParam(Map<String, String[]> params)
{
Map<String, Object> paramz = new HashMap();
for (Map.Entry<String, String[]> et : params.entrySet())
{
String key = et.getKey( );
String[] arr = et.getValue();
for ( String value : arr )
{
Dict.setParam(paramz, value, key );
}
}
return paramz;
}
/**
*
* WebSocket
* @param params
* @return Map
*/
public static Map parseParan(Map<String, List<String>> params)
{
Map<String, Object> paramz = new HashMap();
for (Map.Entry<String, List<String>> et : params.entrySet())
{
String key = et.getKey( );
List arr = et.getValue();
for ( Object value : arr )
{
Dict.setParam(paramz, value, key );
}
}
return paramz;
}
/**
*
*
* @param params
* @return
*/
public static Map parseParax(Map params)
{
Map<String, Object> paramz = new HashMap();
Iterator it = params.entrySet().iterator();
while ( it.hasNext() )
{
Map.Entry<String, Object> et = (Map.Entry) it.next();
String key = et.getKey( );
Object val = et.getValue();
if (val instanceof Object[]) {
Object[] arr =(Object[]) val;
for (Object value : arr) {
Dict.setParam(paramz, value, key );
}
} else
if (val instanceof List) {
List<Object> lst =(List) val;
for (Object value : lst) {
Dict.setParam(paramz, value, key );
}
} else {
Dict.setParam(paramz, val, key );
}
}
return paramz;
}
}
|
package ibis.impl.net;
import ibis.ipl.ReadMessage;
import ibis.ipl.SendPortIdentifier;
import ibis.ipl.ConnectionClosedException;
import ibis.ipl.InterruptedIOException;
import ibis.ipl.Ibis;
import java.io.InputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Provide an abstraction of a network input.
*/
public abstract class NetInput extends NetIO implements ReadMessage, NetInputUpcall {
/**
* Active {@link NetConnection connection} number or <code>null</code> if
* no connection is active.
*/
private volatile Integer activeNum = null;
private volatile PooledUpcallThread activeThread = null;
private final int threadStackSize = 256;
private volatile int threadStackPtr = 0;
private PooledUpcallThread[] threadStack = new PooledUpcallThread[threadStackSize];
private NetMutex threadStackLock = new NetMutex(false);
private volatile int upcallThreadNum = 0;
private volatile boolean upcallThreadNotStarted = true;
private NetThreadStat utStat = null;
private volatile boolean freeCalled = false;
final private Integer takenNum = new Integer(-1);
private int pollWaiters;
/**
* Upcall interface for incoming messages.
*/
protected NetInputUpcall upcallFunc = null;
private boolean upcallSpawnMode = true;
private Object nonSpawnSyncer = new Object();
private int nonSpawnWaiters;
/**
* Synchronize between threads if an upcallFunc is installed after
* this Input has been in use as a downcall receive handler
*/
private Object upcallInstaller = new Object();
private int upcallInstallWaiters;
static private volatile int threadCount = 0;
static private boolean globalThreadStat = false;
static {
if (globalThreadStat) {
Runtime.getRuntime().addShutdownHook(new Thread("NetInput's shutdown hook") {
public void run() {
System.err.println("used "+threadCount+" Upcall threads");
System.err.println("current memory values: "+Runtime.getRuntime().totalMemory()+"/"+Runtime.getRuntime().freeMemory()+"/"+Runtime.getRuntime().maxMemory());
}
});
}
}
public final class NetThreadStat extends NetStat {
private int nb_thread_requested = 0;
private int nb_thread_allocated = 0;
private int nb_thread_reused = 0;
private int nb_thread_discarded = 0;
private int nb_thread_poll = 0;
private int nb_max_thread_stack = 0;
public NetThreadStat(boolean on, String moduleName) {
super(on, moduleName);
if (on) {
pluralExceptions.put("entry", "entries");
}
}
public NetThreadStat(boolean on) {
this(on, "");
}
public void addAllocation() {
if (on) {
nb_thread_allocated++;
nb_thread_requested++;
}
}
public void addReuse() {
if (on) {
nb_thread_requested++;
nb_thread_reused++;
}
}
public void addStore() {
if (on) {
if (nb_max_thread_stack < threadStackPtr) {
nb_max_thread_stack = threadStackPtr;
}
}
}
public void addDiscarded() {
if (on) {
nb_thread_discarded++;
}
}
public void addPoll() {
if (on) {
nb_thread_poll++;
}
}
public void report() {
if (on) {
// System.err.println(this + ".poll: Success " + pollSuccess + " Fail " + pollFail);
System.err.println();
System.err.println("Upcall thread allocation stats for module "+moduleName + " " + NetInput.this);
System.err.println("
reportVal(nb_thread_requested, " thread request");
reportVal(nb_thread_allocated, " thread allocation");
reportVal(nb_thread_reused , " thread reuse");
reportVal(nb_thread_discarded , " thread discardal");
reportVal(nb_thread_poll , " poll");
reportVal(nb_max_thread_stack, " stack", "entry", "used");
}
}
}
private int waitingUpcallThreads;
private int livingUpcallThreads;
private int pollingThreads;
private int finishedUpcallThreads;
private final class PooledUpcallThread extends Thread {
private volatile boolean end = false;
private NetMutex sleep = new NetMutex(true);
private int polls;
private int pollSuccess;
private int sleeps;
public PooledUpcallThread(String name) {
super(NetInput.this + ".PooledUpcallThread["+(threadCount++)+"]: "+name);
}
public void run() {
log.in();
while (!end) {
livingUpcallThreads++;
log.disp("sleeping...");
try {
waitingUpcallThreads++;
sleeps++;
sleep.ilock();
// if (livingUpcallThreads - waitingUpcallThreads > 0)
// System.err.println(Thread.currentThread() + ": UpcallThreads waiting " + waitingUpcallThreads + " living " + livingUpcallThreads);
waitingUpcallThreads
// if (activeThread != null && activeThread != this)
// System.err.println(this + ": want to become activeThread; but activeThread is " + activeThread);
activeThread = this;
if (activeNum != null) {
System.err.println(NetInput.this + ": " + Thread.currentThread() + ": connection unavailable " + activeNum);
throw new Error(Thread.currentThread() + ": connection unavailable: "+activeNum);
}
if (finishedUpcallThreads > 1) {
// System.err.print(finishedUpcallThreads + " ");
// try {
for (int i = 0; i < finishedUpcallThreads; i++) {
// threadStackLock.lock();
// threadStackLock.unlock();
// System.err.print("x");
Thread.yield();
}
// } catch (InterruptedIOException e) {
}
} catch (InterruptedIOException e) {
log.disp("was interrupted...");
end = true;
return;
}
utStat.addPoll();
log.disp("just woke up, polling...");
while (!end) {
pollingThreads++;
// if (pollingThreads > 1)
// System.err.println("pollingThreads " + pollingThreads);
try {
polls++;
Integer num = doPoll(true);
if (num == null) {
// the connection was probably closed
// let the 'while' test the end flag
pollingThreads
continue;
}
pollSuccess++;
activeNum = num;
initReceive(activeNum);
} catch (ConnectionClosedException e) {
end = true;
return;
} catch (InterruptedIOException e) {
if (end) {
return;
} else {
throw new Error(e);
}
} catch (IOException e) {
// System.err.println("PooledUpcallThread + doPoll throws IOException. Shouldn't I quit??? " + e);
// throw new Error(e);
return;
}
try {
upcallFunc.inputUpcall(NetInput.this, activeNum);
} catch (InterruptedIOException e) {
if (! end) {
throw new Error(e);
}
return;
} catch (ConnectionClosedException e) {
// System.err.println("PooledUpcallThread.inputUpcall() throws ConnectionClosedException " + e);
end = true;
return;
} catch (IOException e) {
// System.err.println("PooledUpcallThread.inputUpcall() throws IOException. Shouldn't I quit??? " + e);
// throw new Error(e);
end = true;
return;
}
// System.err.println(this + ": upcallSpawnMode " + upcallSpawnMode + " activeThread " + activeThread + " this " + this);
if (! upcallSpawnMode) {
pollingThreads
synchronized (nonSpawnSyncer) {
while (activeThread != null) {
try {
nonSpawnWaiters++;
nonSpawnSyncer.wait();
nonSpawnWaiters
} catch (InterruptedException ie) {
// Ignore
}
}
}
} else if (activeThread == this) {
pollingThreads
try {
implicitFinish();
} catch (Exception e) {
// System.err.println("PooledUpcallThread,implicitFinish() throws IOException. Shouldn't I quit??? " + e);
// throw new Error(e);
return;
}
log.disp("reusing thread");
utStat.addReuse();
continue;
} else {
synchronized (this) {
finishedUpcallThreads
}
try {
threadStackLock.lock();
} catch (InterruptedIOException e) {
if (end != true) {
throw new Error(e);
}
return;
}
if (threadStackPtr < threadStackSize) {
threadStack[threadStackPtr++] = this;
log.disp("storing thread into the stack");
utStat.addStore();
} else {
log.disp("discarding the thread");
end = true;
}
threadStackLock.unlock();
break;
}
}
}
// livingUpcallThreads--;
// System.err.println(Thread.currentThread() + ": call it quits");
log.out();
}
public void exec() {
log.in();
sleep.unlock();
log.out();
}
public void end() {
log.in();
end = true;
// System.err.println(this + ": polls " + pollSuccess + " (of " + polls + ") sleeps " + sleeps);
this.interrupt();
log.out();
}
}
/**
* Constructor.
*
* @param portType the port {@link NetPortType} type.
* @param driver the driver.
* @param context the context.
*/
protected NetInput(NetPortType portType,
NetDriver driver,
String context) {
super(portType, driver, context);
// setBufferFactory(new NetBufferFactory(new NetReceiveBufferFactoryDefaultImpl()));
// Stat object
String s = "//"+type.name()+this.context+".input";
boolean utStatOn = type.getBooleanStringProperty(this.context, "UpcallThreadStat", false);
utStat = new NetThreadStat(utStatOn, s);
}
/**
* Default incoming message upcall method.
*
* Note: this method is only useful for filtering drivers.
*
* @param input the {@link NetInput sub-input} that generated the upcall.
* @param num the active connection number
* @exception IOException in case of trouble.
*/
public synchronized void inputUpcall(NetInput input, Integer num) throws IOException {
log.in();
activeNum = num;
upcallFunc.inputUpcall(this, num);
activeNum = null;
log.out();
}
protected abstract void initReceive(Integer num) throws IOException;
protected void handleEmptyMsg() throws IOException {
readByte();
}
protected void enableUpcallSpawnMode() {
upcallSpawnMode = true;
}
protected void disableUpcallSpawnMode() {
upcallSpawnMode = false;
}
private int pollFail;
private int pollSuccess;
/**
* Test for incoming data.
*
* Note: if {@linkplain #poll} is called again immediately
* after a successful {@linkplain #poll} without extracting the message and
* {@linkplain #finish finishing} the input, the result is
* undefined and data might get lost. Use {@link
* #getActiveSendPortNum} instead.
*
* @param blockForMessage indicates whether this method must block until
* a message has arrived, or just query the input one.
* @return the {@link NetConnection connection} identifier or <code>null</code> if no data is available.
* @exception InterruptedIOException if the polling fails (!= the
* polling is unsuccessful).
*/
public final Integer poll(boolean blockForMessage) throws IOException {
log.in();
synchronized(this) {
while (activeNum != null) {
pollWaiters++;
try {
wait();
} catch (InterruptedException e) {
throw new InterruptedIOException(e);
} finally {
pollWaiters
}
}
activeNum = takenNum;
}
Integer num = doPoll(blockForMessage);
synchronized(this) {
if (activeNum.equals(takenNum)) {
if (num != null) {
pollSuccess++;
} else {
pollFail++;
}
activeNum = num;
} else {
// Closing?
num = null;
}
}
if (num != null) {
initReceive(num);
} else if (upcallInstallWaiters > 0) {
System.err.println("Release the install handler");
synchronized (upcallInstaller) {
upcallInstaller.notifyAll();
}
}
log.out();
return num;
}
protected abstract Integer doPoll(boolean blockForMessage) throws IOException;
/**
* Unblockingly test for incoming data.
*
* Note: if {@linkplain #poll} is called again immediately
* after a successful {@linkplain #poll} without extracting the message and
* {@linkplain #finish finishing} the input, the result is
* undefined and data might get lost. Use {@link
* #getActiveSendPortNum} instead.
*
* @return the {@link NetConnection connection} identifier or <code>null</code> if no data is available.
* @exception InterruptedIOException if the polling fails (!= the
* polling is unsuccessful).
*/
public Integer poll() throws IOException {
return poll(false);
}
/**
* Return the active {@link NetConnection connection} identifier or <code>null</code> if no {@link NetConnection connection} is active.
*
* @return the active {@link NetConnection connection} identifier or <code>null</code> if no {@link NetConnection connection} is active.
*/
public final Integer getActiveSendPortNum() {
return activeNum;
}
/**
* Actually establish a connection with a remote port and register an upcall function for incoming message notification.
*
* @param cnx the connection attributes.
* @param inputUpcall the upcall function for incoming message notification.
* @exception IOException if the connection setup fails.
*/
public synchronized void setupConnection(NetConnection cnx,
NetInputUpcall inputUpcall) throws IOException {
log.in();
if (freeCalled) {
throw new ConnectionClosedException("input closed");
}
this.upcallFunc = inputUpcall;
log.disp("this.upcallFunc = ", this.upcallFunc);
setupConnection(cnx);
log.out();
}
protected final void startUpcallThread() throws IOException {
log.in();
// System.err.println(this + ": in startUpcallThread; upcallFunc " + upcallFunc);
// Thread.dumpStack();
threadStackLock.lock();
if (upcallFunc != null && upcallThreadNotStarted) {
System.err.println(this + ": in startUpcallThread; upcallFunc " + upcallFunc);
upcallThreadNotStarted = false;
PooledUpcallThread up = new PooledUpcallThread("no "+upcallThreadNum++);
utStat.addAllocation();
up.start();
up.exec();
}
threadStackLock.unlock();
log.out();
}
protected void installUpcallFunc(NetInputUpcall upcallFunc)
throws IOException {
if (this.upcallFunc != null) {
throw new IllegalArgumentException("Cannot restart upcall");
}
this.upcallFunc = upcallFunc;
/*
* Fight race with poll: if an upcallFunc is installed for
* a NetInput that used to do downcall receives, we must ensure
* that the downcall poll has finished completely. In that case,
* activeNum is null.
*/
synchronized (upcallInstaller) {
while (activeNum != null) {
System.err.println("Wait for release the install handler");
upcallInstallWaiters++;
try {
upcallInstaller.wait();
} catch (InterruptedException e) {
// Ignore
}
upcallInstallWaiters
System.err.println("Unwait for release the install handler");
}
}
startUpcallThread();
}
public NetReceiveBuffer createReceiveBuffer(int contentsLength) {
log.in();
NetReceiveBuffer b = (NetReceiveBuffer)createBuffer();
b.length = contentsLength;
log.out();
return b;
}
/**
* Utility function to get a {@link NetReceiveBuffer} from our
* {@link NetBufferFactory}.
*
* @param length the length of the data stored in the buffer
* @param contentsLength indicates how many bytes of data must be received.
* 0 indicates that any length is fine and that the buffer.length field
* should be filled with the length actually read.
* @return the new {@link NetReceiveBuffer}.
*/
public NetReceiveBuffer createReceiveBuffer(int length, int contentsLength) {
log.in();
NetReceiveBuffer b = (NetReceiveBuffer)createBuffer(length);
b.length = contentsLength;
log.out();
return b;
}
public final void close(Integer num) throws IOException {
log.in();
synchronized(this) {
doClose(num);
if (activeNum == num) {
activeNum = null;
notifyAll();
}
}
threadStackLock.lock();
if (activeThread != null) {
((PooledUpcallThread)activeThread).end();
activeThread = null;
}
while (threadStackPtr > 0) {
threadStack[--threadStackPtr].end();
}
upcallThreadNotStarted = true;
threadStackLock.unlock();
log.out();
}
protected abstract void doClose(Integer num) throws IOException;
/*
* Closes the I/O.
*
* Note: methods redefining this one should also call it, just in case
* we need to add something here
* @exception IOException if this operation fails.
*/
public void free() throws IOException {
log.in();trace.in("this = ", this);
freeCalled = true;
doFree();
activeNum = null;
threadStackLock.lock();
if (activeThread != null) {
trace.disp("this = "+this+", active thread end ["+(activeThread.getName())+"]
((PooledUpcallThread)activeThread).end();
while (true) {
try {
((PooledUpcallThread)activeThread).join();
activeThread = null;
break;
} catch (InterruptedException e) {
}
}
trace.disp("this = "+this+", active thread end<
}
for (int i = 0; i < threadStackSize; i++) {
if (threadStack[i] != null) {
trace.disp("this = "+this+", thread stack["+i+"] end
threadStack[i].end();
while (true) {
try {
threadStack[i].join();
threadStack[i] = null;
break;
} catch (InterruptedException e) {
}
}
trace.disp("this = "+this+", thread stack["+i+"] end<
}
}
threadStackLock.unlock();
super.free();
trace.out("this = "+this);log.out();
}
protected abstract void doFree() throws IOException;
/**
* {@inheritDoc}
*/
protected void finalize() throws Throwable {
log.in();
free();
super.finalize();
log.out();
}
/* ReadMessage Interface */
private final void implicitFinish() throws IOException {
log.in();
if (_inputConvertStream != null) {
try {
_inputConvertStream.close();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
_inputConvertStream = null;
}
doFinish();
synchronized(this) {
activeNum = null;
if (pollWaiters > 0) {
notify();
// notifyAll();
}
}
log.out();
}
/**
* Complete the current incoming message extraction.
*
* Only one message is alive at one time for a given
* receiveport. This is done to prevent flow control
* problems. when a message is alive, and a new messages is
* requested with a receive, the requester is blocked until
* the live message is finished.
*
* @exception IOException in case of trouble.
*/
public final void finish() throws IOException {
log.in();
// System.err.println(this + " " + Thread.currentThread() + ": finish()");
// Thread.dumpStack();
implicitFinish();
if (! upcallSpawnMode) {
synchronized (nonSpawnSyncer) {
// System.err.println("Reset activeThread from finish");
activeThread = null;
if (nonSpawnWaiters > 0) {
nonSpawnSyncer.notify();
// nonSpawnSyncer.notifyAll();
}
}
} else if (activeThread != null) {
synchronized (this) {
finishedUpcallThreads++;
}
pollingThreads
PooledUpcallThread ut = null;
threadStackLock.lock();
if (threadStackPtr > 0) {
ut = threadStack[--threadStackPtr];
utStat.addReuse();
} else {
ut = new PooledUpcallThread("no "+upcallThreadNum++);
// System.err.println(this + ": msg.finish creates another PooledUpcallThread[" + livingUpcallThreads + "] " + threadStackPtr + "; sleepingThreads " + waitingUpcallThreads + " finishedUpcallThreads " + finishedUpcallThreads);
// Thread.dumpStack();
ut.start();
utStat.addAllocation();
}
threadStackLock.unlock();
activeThread = ut;
if (ut != null) {
ut.exec();
}
}
log.out();
}
protected abstract void doFinish() throws IOException;
/**
* Unimplemented.
*
* @return 0.
*/
public long sequenceNumber() {
return 0;
}
/**
* Unimplemented.
*
* @return <code>null</code>.
*/
public SendPortIdentifier origin() {
return null;
}
/* fallback serialization implementation */
/**
* Object stream for the internal fallback serialization.
*
* Note: the fallback serialization implementation internally uses
* a JVM {@link ObjectOutputStream}/{@link ObjectInputStream} pair.
* The stream pair is closed upon each message completion to ensure data
* consistency.
*/
private ObjectInputStream _inputConvertStream = null;
/**
* Check whether the convert stream should be initialized, and
* initialize it when needed.
*/
private final void checkConvertStream() throws IOException {
if (_inputConvertStream == null) {
DummyInputStream dis = new DummyInputStream();
_inputConvertStream = new ObjectInputStream(dis);
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @return the <code>boolean</code> value just read.
* @exception IOException in case of trouble.
*/
private final boolean defaultReadBoolean() throws IOException {
boolean result = false;
try {
checkConvertStream();
result = _inputConvertStream.readBoolean();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
return result;
}
/**
* Default implementation of {@link #readChar}.
*
* Note: this method must not be changed.
*
* @return the <code>char</code> value just read.
* @exception IOException in case of trouble.
*/
private final char defaultReadChar() throws IOException {
char result = 0;
try {
checkConvertStream();
result = _inputConvertStream.readChar();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
return result;
}
/**
* Default implementation of {@link #readShort}.
*
* Note: this method must not be changed.
*
* @return the <code>short</code> value just read.
* @exception IOException in case of trouble.
*/
private final short defaultReadShort() throws IOException {
short result = 0;
try {
checkConvertStream();
result = _inputConvertStream.readShort();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
return result;
}
/**
* Default implementation of {@link #readInt}.
*
* Note: this method must not be changed.
*
* @return the <code>int</code> value just read.
* @exception IOException in case of trouble.
*/
private final int defaultReadInt() throws IOException {
int result = 0;
try {
checkConvertStream();
result = _inputConvertStream.readInt();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
return result;
}
/**
* Default implementation of {@link #readLong}.
*
* Note: this method must not be changed.
*
* @return the <code>long</code> value just read.
* @exception IOException in case of trouble.
*/
private final long defaultReadLong() throws IOException {
long result = 0;
try {
checkConvertStream();
result = _inputConvertStream.readLong();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
return result;
}
/**
* Default implementation of {@link #readFloat}.
*
* Note: this method must not be changed.
*
* @return the <code>float</code> value just read.
* @exception IOException in case of trouble.
*/
private final float defaultReadFloat() throws IOException {
float result = 0;
try {
checkConvertStream();
result = _inputConvertStream.readFloat();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
return result;
}
/**
* Default implementation of {@link #readDouble}.
*
* Note: this method must not be changed.
*
* @return the <code>double</code> value just read.
* @exception IOException in case of trouble.
*/
private final double defaultReadDouble() throws IOException {
double result = 0;
try {
checkConvertStream();
result = _inputConvertStream.readDouble();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
return result;
}
/**
* Default implementation of {@link #readString}.
*
* Note: this method must not be changed.
*
* @return the {@link String string} value just read.
* @exception IOException in case of trouble.
*/
private final String defaultReadString() throws IOException {
String result = null;
try {
checkConvertStream();
result = _inputConvertStream.readUTF();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
/*
} catch (Exception e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
*/
}
return result;
}
/**
* Default implementation of {@link #readObject}.
*
* Note: this method must not be changed.
*
* @return the {@link Object object} value just read.
* @exception IOException in case of trouble.
*/
private final Object defaultReadObject() throws IOException, ClassNotFoundException {
Object result = null;
try {
checkConvertStream();
result = _inputConvertStream.readObject();
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
// } catch (Exception e) {
// throw new IOException(e);
}
return result;
}
/**
* Default implementation of {@link #readArray}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(boolean [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readBoolean();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(byte [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readByte();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(char [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readChar();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(short [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readShort();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(int [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readInt();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(long [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readLong();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(float [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readFloat();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(double [] b, int o, int l) throws IOException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readDouble();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
}
}
/**
* Default implementation of {@link #readBoolean}.
*
* Note: this method must not be changed.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to read.
* @exception IOException in case of trouble.
*/
private final void defaultReadArray(Object [] b, int o, int l) throws IOException, ClassNotFoundException {
try {
checkConvertStream();
while (l
b[o++] = _inputConvertStream.readObject();
}
} catch (EOFException e) {
throw new ConnectionClosedException(e);
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null && msg.equalsIgnoreCase("connection closed")) {
throw new ConnectionClosedException(e);
}
throw e;
// } catch (Exception e) {
// throw new IOException(e);
}
}
public ibis.ipl.ReceivePort localPort() {
// what the @#@ should we do here --Rob
throw new ibis.ipl.IbisError("AAAAA");
}
/**
* Atomic packet read function.
*
* @param expectedLength a hint about how many bytes are expected.
* @exception IOException in case of trouble.
*/
public NetReceiveBuffer readByteBuffer(int expectedLength) throws IOException {
int len = defaultReadInt();
NetReceiveBuffer buffer = createReceiveBuffer(len);
defaultReadArray(buffer.data, 0, len);
return buffer;
}
/**
* Atomic packet read function.
*
* @param b the buffer to fill.
* @exception IOException in case of trouble.
*/
public void readByteBuffer(NetReceiveBuffer buffer) throws IOException {
int len = defaultReadInt();
defaultReadArray(buffer.data, 0, len);
buffer.length = len;
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public boolean readBoolean() throws IOException {
return defaultReadBoolean();
}
/**
* Extract a byte from the current message.
*
* @exception IOException in case of trouble.
*/
public abstract byte readByte() throws IOException;
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public char readChar() throws IOException {
return defaultReadChar();
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public short readShort() throws IOException {
return defaultReadShort();
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public int readInt() throws IOException {
return defaultReadInt();
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public long readLong() throws IOException {
return defaultReadLong();
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public float readFloat() throws IOException {
return defaultReadFloat();
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public double readDouble() throws IOException {
return defaultReadDouble();
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public String readString() throws IOException {
return (String)defaultReadString();
}
/**
* Extract an element from the current message.
*
* @exception IOException in case of trouble.
*/
public Object readObject() throws IOException, ClassNotFoundException {
return defaultReadObject();
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(boolean [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(byte [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(char [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(short [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(int [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(long [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(float [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(double [] b, int o, int l) throws IOException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
* @param o the offset.
* @param l the number of elements to extract.
*
* @exception IOException in case of trouble.
*/
public void readArray(Object [] b, int o, int l) throws IOException, ClassNotFoundException {
defaultReadArray(b, o, l);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(boolean [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(byte [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(char [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(short [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(int [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(long [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(float [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(double [] b) throws IOException {
readArray(b, 0, b.length);
}
/**
* Extract some elements from the current message.
*
* @param b the array.
*
* @exception IOException in case of trouble.
*/
public final void readArray(Object [] b) throws IOException, ClassNotFoundException {
readArray(b, 0, b.length);
}
/**
* Internal dummy {@link InputStream} to be used as a byte stream source for
* the {@link ObjectInputStream} based fallback serialization.
*/
private final class DummyInputStream extends InputStream {
/**
* {@inheritDoc}
*
* Note: the other read methods must _not_ be overloaded
* because the ObjectInput/OutputStream do not guaranty
* symmetrical transactions.
*
*/
public int read() throws IOException {
int result = 0;
result = readByte();
return (result & 255);
}
}
}
|
package bisq.network.p2p.network;
import bisq.network.p2p.NodeAddress;
import bisq.common.UserThread;
import bisq.common.proto.network.NetworkEnvelope;
import bisq.common.proto.network.NetworkProtoResolver;
import bisq.common.util.Utilities;
import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.SettableFuture;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
// Run in UserThread
public abstract class NetworkNode implements MessageListener {
private static final Logger log = LoggerFactory.getLogger(NetworkNode.class);
private static final int CREATE_SOCKET_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(120);
final int servicePort;
private final NetworkProtoResolver networkProtoResolver;
private final CopyOnWriteArraySet<InboundConnection> inBoundConnections = new CopyOnWriteArraySet<>();
private final CopyOnWriteArraySet<MessageListener> messageListeners = new CopyOnWriteArraySet<>();
private final CopyOnWriteArraySet<ConnectionListener> connectionListeners = new CopyOnWriteArraySet<>();
final CopyOnWriteArraySet<SetupListener> setupListeners = new CopyOnWriteArraySet<>();
ListeningExecutorService executorService;
private Server server;
private volatile boolean shutDownInProgress;
// accessed from different threads
private final CopyOnWriteArraySet<OutboundConnection> outBoundConnections = new CopyOnWriteArraySet<>();
protected final ObjectProperty<NodeAddress> nodeAddressProperty = new SimpleObjectProperty<>();
// Constructor
NetworkNode(int servicePort, NetworkProtoResolver networkProtoResolver) {
this.servicePort = servicePort;
this.networkProtoResolver = networkProtoResolver;
}
// API
// Calls this (and other registered) setup listener's ``onTorNodeReady()`` and ``onHiddenServicePublished``
// when the events happen.
abstract public void start(@Nullable SetupListener setupListener);
public SettableFuture<Connection> sendMessage(@NotNull NodeAddress peersNodeAddress,
NetworkEnvelope networkEnvelope) {
if (log.isDebugEnabled())
log.debug("sendMessage: peersNodeAddress=" + peersNodeAddress + "\n\tmessage=" + Utilities.toTruncatedString(networkEnvelope));
checkNotNull(peersNodeAddress, "peerAddress must not be null");
Connection connection = getOutboundConnection(peersNodeAddress);
if (connection == null)
connection = getInboundConnection(peersNodeAddress);
if (connection != null) {
return sendMessage(connection, networkEnvelope);
} else {
log.debug("We have not found any connection for peerAddress {}.\n\t" +
"We will create a new outbound connection.", peersNodeAddress);
final SettableFuture<Connection> resultFuture = SettableFuture.create();
ListenableFuture<Connection> future = executorService.submit(() -> {
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + peersNodeAddress.getFullAddress());
if (peersNodeAddress.equals(getNodeAddress())) {
throw new ConnectException("We do not send a message to ourselves");
}
OutboundConnection outboundConnection = null;
try {
// can take a while when using tor
long startTs = System.currentTimeMillis();
if (log.isDebugEnabled())
log.debug("Start create socket to peersNodeAddress {}", peersNodeAddress.getFullAddress());
Socket socket = createSocket(peersNodeAddress);
long duration = System.currentTimeMillis() - startTs;
if (log.isDebugEnabled())
log.debug("Socket creation to peersNodeAddress {} took {} ms", peersNodeAddress.getFullAddress(),
duration);
if (duration > CREATE_SOCKET_TIMEOUT)
throw new TimeoutException("A timeout occurred when creating a socket.");
// Tor needs sometimes quite long to create a connection. To avoid that we get too many double
// sided connections we check again if we still don't have any connection for that node address.
Connection existingConnection = getInboundConnection(peersNodeAddress);
if (existingConnection == null)
existingConnection = getOutboundConnection(peersNodeAddress);
if (existingConnection != null) {
if (log.isDebugEnabled())
log.debug("We found in the meantime a connection for peersNodeAddress {}, " +
"so we use that for sending the message.\n" +
"That can happen if Tor needs long for creating a new outbound connection.\n" +
"We might have got a new inbound or outbound connection.",
peersNodeAddress.getFullAddress());
try {
socket.close();
} catch (Throwable throwable) {
log.error("Error at closing socket " + throwable);
}
existingConnection.sendMessage(networkEnvelope);
return existingConnection;
} else {
final ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void onConnection(Connection connection) {
if (!connection.isStopped()) {
outBoundConnections.add((OutboundConnection) connection);
printOutBoundConnections();
connectionListeners.stream().forEach(e -> e.onConnection(connection));
}
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason,
Connection connection) {
log.trace("onDisconnect connectionListener\n\tconnection={}" + connection);
//noinspection SuspiciousMethodCalls
outBoundConnections.remove(connection);
printOutBoundConnections();
connectionListeners.stream().forEach(e -> e.onDisconnect(closeConnectionReason, connection));
}
@Override
public void onError(Throwable throwable) {
log.error("new OutboundConnection.ConnectionListener.onError " + throwable.getMessage());
connectionListeners.stream().forEach(e -> e.onError(throwable));
}
};
outboundConnection = new OutboundConnection(socket,
NetworkNode.this,
connectionListener,
peersNodeAddress,
networkProtoResolver);
if (log.isDebugEnabled())
log.debug("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" +
"NetworkNode created new outbound connection:"
+ "\nmyNodeAddress=" + getNodeAddress()
+ "\npeersNodeAddress=" + peersNodeAddress
+ "\nuid=" + outboundConnection.getUid()
+ "\nmessage=" + networkEnvelope
+ "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
// can take a while when using tor
outboundConnection.sendMessage(networkEnvelope);
return outboundConnection;
}
} catch (Throwable throwable) {
if (!(throwable instanceof ConnectException ||
throwable instanceof IOException ||
throwable instanceof TimeoutException)) {
log.warn("Executing task failed. " + throwable.getMessage());
}
throw throwable;
}
});
Futures.addCallback(future, new FutureCallback<>() {
public void onSuccess(Connection connection) {
UserThread.execute(() -> resultFuture.set(connection));
}
public void onFailure(@NotNull Throwable throwable) {
log.info("onFailure at sendMessage: peersNodeAddress={}\n\tmessage={}\n\tthrowable={}", peersNodeAddress, networkEnvelope.getClass().getSimpleName(), throwable.toString());
UserThread.execute(() -> resultFuture.setException(throwable));
}
});
return resultFuture;
}
}
@Nullable
private InboundConnection getInboundConnection(@NotNull NodeAddress peersNodeAddress) {
Optional<InboundConnection> inboundConnectionOptional = lookupInBoundConnection(peersNodeAddress);
if (inboundConnectionOptional.isPresent()) {
InboundConnection connection = inboundConnectionOptional.get();
log.trace("We have found a connection in inBoundConnections. Connection.uid={}", connection.getUid());
if (connection.isStopped()) {
log.warn("We have a connection which is already stopped in inBoundConnections. Connection.uid=" + connection.getUid());
inBoundConnections.remove(connection);
return null;
} else {
return connection;
}
} else {
return null;
}
}
@Nullable
private OutboundConnection getOutboundConnection(@NotNull NodeAddress peersNodeAddress) {
Optional<OutboundConnection> outboundConnectionOptional = lookupOutBoundConnection(peersNodeAddress);
if (outboundConnectionOptional.isPresent()) {
OutboundConnection connection = outboundConnectionOptional.get();
log.trace("We have found a connection in outBoundConnections. Connection.uid={}", connection.getUid());
if (connection.isStopped()) {
log.warn("We have a connection which is already stopped in outBoundConnections. Connection.uid=" + connection.getUid());
outBoundConnections.remove(connection);
return null;
} else {
return connection;
}
} else {
return null;
}
}
@Nullable
public Socks5Proxy getSocksProxy() {
return null;
}
public SettableFuture<Connection> sendMessage(Connection connection, NetworkEnvelope networkEnvelope) {
// connection.sendMessage might take a bit (compression, write to stream), so we use a thread to not block
ListenableFuture<Connection> future = executorService.submit(() -> {
String id = connection.getPeersNodeAddressOptional().isPresent() ? connection.getPeersNodeAddressOptional().get().getFullAddress() : connection.getUid();
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + id);
connection.sendMessage(networkEnvelope);
return connection;
});
final SettableFuture<Connection> resultFuture = SettableFuture.create();
Futures.addCallback(future, new FutureCallback<Connection>() {
public void onSuccess(Connection connection) {
UserThread.execute(() -> resultFuture.set(connection));
}
public void onFailure(@NotNull Throwable throwable) {
UserThread.execute(() -> resultFuture.setException(throwable));
}
});
return resultFuture;
}
public ReadOnlyObjectProperty<NodeAddress> nodeAddressProperty() {
return nodeAddressProperty;
}
public Set<Connection> getAllConnections() {
// Can contain inbound and outbound connections with the same peer node address,
// as connection hashcode is using uid and port info
Set<Connection> set = new HashSet<>(inBoundConnections);
set.addAll(outBoundConnections);
return set;
}
public Set<Connection> getConfirmedConnections() {
// Can contain inbound and outbound connections with the same peer node address,
// as connection hashcode is using uid and port info
return getAllConnections().stream()
.filter(Connection::hasPeersNodeAddress)
.collect(Collectors.toSet());
}
public Set<NodeAddress> getNodeAddressesOfConfirmedConnections() {
// Does not contain inbound and outbound connection with the same peer node address
return getConfirmedConnections().stream()
.map(e -> e.getPeersNodeAddressOptional().get())
.collect(Collectors.toSet());
}
public void shutDown(Runnable shutDownCompleteHandler) {
if (!shutDownInProgress) {
shutDownInProgress = true;
if (server != null) {
server.shutDown();
server = null;
}
getAllConnections().stream().forEach(c -> c.shutDown(CloseConnectionReason.APP_SHUT_DOWN));
log.debug("NetworkNode shutdown complete");
}
if (shutDownCompleteHandler != null) shutDownCompleteHandler.run();
}
// SetupListener
void addSetupListener(SetupListener setupListener) {
boolean isNewEntry = setupListeners.add(setupListener);
if (!isNewEntry)
log.warn("Try to add a setupListener which was already added.");
}
// MessageListener implementation
@Override
public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) {
messageListeners.stream().forEach(e -> e.onMessage(networkEnvelope, connection));
}
// Listeners
public void addConnectionListener(ConnectionListener connectionListener) {
boolean isNewEntry = connectionListeners.add(connectionListener);
if (!isNewEntry)
log.warn("Try to add a connectionListener which was already added.\n\tconnectionListener={}\n\tconnectionListeners={}"
, connectionListener, connectionListeners);
}
public void removeConnectionListener(ConnectionListener connectionListener) {
boolean contained = connectionListeners.remove(connectionListener);
if (!contained)
log.debug("Try to remove a connectionListener which was never added.\n\t" +
"That might happen because of async behaviour of CopyOnWriteArraySet");
}
public void addMessageListener(MessageListener messageListener) {
boolean isNewEntry = messageListeners.add(messageListener);
if (!isNewEntry)
log.warn("Try to add a messageListener which was already added.");
}
public void removeMessageListener(MessageListener messageListener) {
boolean contained = messageListeners.remove(messageListener);
if (!contained)
log.debug("Try to remove a messageListener which was never added.\n\t" +
"That might happen because of async behaviour of CopyOnWriteArraySet");
}
// Protected
void createExecutorService() {
if (executorService == null)
executorService = Utilities.getListeningExecutorService("NetworkNode-" + servicePort, 15, 30, 60);
}
void startServer(ServerSocket serverSocket) {
final ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void onConnection(Connection connection) {
if (!connection.isStopped()) {
inBoundConnections.add((InboundConnection) connection);
printInboundConnections();
connectionListeners.stream().forEach(e -> e.onConnection(connection));
}
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
log.trace("onDisconnect at server socket connectionListener\n\tconnection={}", connection);
//noinspection SuspiciousMethodCalls
inBoundConnections.remove(connection);
printInboundConnections();
connectionListeners.stream().forEach(e -> e.onDisconnect(closeConnectionReason, connection));
}
@Override
public void onError(Throwable throwable) {
log.error("server.ConnectionListener.onError " + throwable.getMessage());
connectionListeners.stream().forEach(e -> e.onError(throwable));
}
};
server = new Server(serverSocket,
NetworkNode.this,
connectionListener,
networkProtoResolver);
executorService.submit(server);
}
private Optional<OutboundConnection> lookupOutBoundConnection(NodeAddress peersNodeAddress) {
log.trace("lookupOutboundConnection for peersNodeAddress={}", peersNodeAddress.getFullAddress());
printOutBoundConnections();
return outBoundConnections.stream()
.filter(connection -> connection.hasPeersNodeAddress() &&
peersNodeAddress.equals(connection.getPeersNodeAddressOptional().get())).findAny();
}
private void printOutBoundConnections() {
StringBuilder sb = new StringBuilder("outBoundConnections size()=")
.append(outBoundConnections.size()).append("\n\toutBoundConnections=");
outBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
log.debug(sb.toString());
}
private Optional<InboundConnection> lookupInBoundConnection(NodeAddress peersNodeAddress) {
log.trace("lookupInboundConnection for peersNodeAddress={}", peersNodeAddress.getFullAddress());
printInboundConnections();
return inBoundConnections.stream()
.filter(connection -> connection.hasPeersNodeAddress() &&
peersNodeAddress.equals(connection.getPeersNodeAddressOptional().get())).findAny();
}
private void printInboundConnections() {
StringBuilder sb = new StringBuilder("inBoundConnections size()=")
.append(inBoundConnections.size()).append("\n\tinBoundConnections=");
inBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
log.debug(sb.toString());
}
abstract protected Socket createSocket(NodeAddress peersNodeAddress) throws IOException;
@Nullable
public NodeAddress getNodeAddress() {
return nodeAddressProperty.get();
}
}
|
package org.lwjgl.opengl;
import org.lwjgl.system.*;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.macosx.MacOSXLibrary;
import org.lwjgl.system.windows.*;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.*;
import static java.lang.Math.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.opengl.GL32.*;
import static org.lwjgl.opengl.GLX.*;
import static org.lwjgl.opengl.GLX11.*;
import static org.lwjgl.opengl.WGL.*;
import static org.lwjgl.system.APIUtil.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.linux.X11.*;
import static org.lwjgl.system.windows.GDI32.*;
import static org.lwjgl.system.windows.User32.*;
import static org.lwjgl.system.windows.WindowsUtil.*;
/**
* This class must be used before any OpenGL function is called. It has the following responsibilities:
* <ul>
* <li>Loads the OpenGL native library into the JVM process.</li>
* <li>Creates instances of {@link GLCapabilities} classes. A {@code GLCapabilities} instance contains flags for functionality that is available in an OpenGL
* context. Internally, it also contains function pointers that are only valid in that specific OpenGL context.</li>
* <li>Maintains thread-local state for {@code GLCapabilities} instances, corresponding to OpenGL contexts that are current in those threads.</li>
* </ul>
*
* <h3>Library lifecycle</h3>
* <p>The OpenGL library is loaded automatically when this class is initialized. Set the {@link Configuration#OPENGL_EXPLICIT_INIT} option to override this
* behavior. Manual loading/unloading can be achieved with the {@link #create} and {@link #destroy} functions. The name of the library loaded can be overridden
* with the {@link Configuration#OPENGL_LIBRARY_NAME} option. The maximum OpenGL version loaded can be set with the {@link Configuration#OPENGL_MAXVERSION}
* option. This can be useful to ensure that no functionality above a specific version is used during development.</p>
*
* <h3>GLCapabilities creation</h3>
* <p>Instances of {@code GLCapabilities} can be created with the {@link #createCapabilities} method. An OpenGL context must be current in the current thread
* before it is called. Calling this method is expensive, so the {@code GLCapabilities} instance should be associated with the OpenGL context and reused as
* necessary.</p>
*
* <h3>Thread-local state</h3>
* <p>Before a function for a given OpenGL context can be called, the corresponding {@code GLCapabilities} instance must be passed to the
* {@link #setCapabilities} method. The user is also responsible for clearing the current {@code GLCapabilities} instance when the context is destroyed or made
* current in another thread.</p>
*
* <p>Note that the {@link #createCapabilities} method implicitly calls {@link #setCapabilities} with the newly created instance.</p>
*/
public final class GL {
private static final APIVersion MAX_VERSION;
private static FunctionProvider functionProvider;
private static final ThreadLocal<GLCapabilities> capabilitiesTLS = new ThreadLocal<>();
private static ICD icd = new ICDStatic();
private static WGLCapabilities capabilitiesWGL;
private static GLXCapabilities capabilitiesGLXClient;
private static GLXCapabilities capabilitiesGLX;
static {
Library.loadSystem(Platform.mapLibraryNameBundled("lwjgl_opengl"));
MAX_VERSION = apiParseVersion(Configuration.OPENGL_MAXVERSION);
if ( !Configuration.OPENGL_EXPLICIT_INIT.get(false) )
create();
}
private GL() {}
/** Ensures that the lwjgl_opengl shared library has been loaded. */
static void initialize() {
// intentionally empty to trigger static initializer
}
/** Loads the OpenGL native library, using the default library name. */
public static void create() {
SharedLibrary GL;
switch ( Platform.get() ) {
case LINUX:
GL = Library.loadNative(Configuration.OPENGL_LIBRARY_NAME, "libGL.so.1", "libGL.so");
break;
case MACOSX:
GL = Configuration.OPENGL_LIBRARY_NAME.get() != null
? Library.loadNative(Configuration.OPENGL_LIBRARY_NAME)
: MacOSXLibrary.getWithIdentifier("com.apple.opengl");
break;
case WINDOWS:
GL = Library.loadNative(Configuration.OPENGL_LIBRARY_NAME, "opengl32");
break;
default:
throw new IllegalStateException();
}
create(GL);
}
/**
* Loads the OpenGL native library, using the specified library name.
*
* @param libName the native library name
*/
public static void create(String libName) {
create(Library.loadNative(libName));
}
private abstract static class SharedLibraryGL extends SharedLibrary.Delegate {
SharedLibraryGL(SharedLibrary library) {
super(library);
}
abstract long getExtensionAddress(long name);
@Override
public long getFunctionAddress(ByteBuffer functionName) {
long address = getExtensionAddress(memAddress(functionName));
if ( address == NULL ) {
address = library.getFunctionAddress(functionName);
if ( address == NULL && DEBUG_FUNCTIONS )
apiLog("Failed to locate address for GL function " + memASCII(functionName));
}
return address;
}
}
private static void create(SharedLibrary OPENGL) {
FunctionProvider functionProvider;
try {
switch ( Platform.get() ) {
case WINDOWS:
functionProvider = new SharedLibraryGL(OPENGL) {
private final long wglGetProcAddress = library.getFunctionAddress("wglGetProcAddress");
@Override
long getExtensionAddress(long name) {
return callPP(wglGetProcAddress, name);
}
};
break;
case LINUX:
functionProvider = new SharedLibraryGL(OPENGL) {
private final long glXGetProcAddress;
{
long GetProcAddress = library.getFunctionAddress("glXGetProcAddress");
if ( GetProcAddress == NULL )
GetProcAddress = library.getFunctionAddress("glXGetProcAddressARB");
glXGetProcAddress = GetProcAddress;
}
@Override
long getExtensionAddress(long name) {
return glXGetProcAddress == NULL ? NULL : callPP(glXGetProcAddress, name);
}
};
break;
case MACOSX:
functionProvider = new SharedLibraryGL(OPENGL) {
@Override
long getExtensionAddress(long name) {
return NULL;
}
};
break;
default:
throw new IllegalStateException();
}
create(functionProvider);
} catch (RuntimeException e) {
OPENGL.free();
throw e;
}
}
/**
* Initializes OpenGL with the specified {@link FunctionProvider}. This method can be used to implement custom OpenGL library loading.
*
* @param functionProvider the provider of OpenGL function addresses
*/
public static void create(FunctionProvider functionProvider) {
if ( GL.functionProvider != null )
throw new IllegalStateException("OpenGL has already been created.");
GL.functionProvider = functionProvider;
}
/** Unloads the OpenGL native library. */
public static void destroy() {
if ( functionProvider == null )
return;
capabilitiesWGL = null;
capabilitiesGLX = null;
if ( functionProvider instanceof NativeResource )
((NativeResource)functionProvider).free();
functionProvider = null;
}
/** Returns the {@link FunctionProvider} for the OpenGL native library. */
public static FunctionProvider getFunctionProvider() {
return functionProvider;
}
/**
* Sets the {@link GLCapabilities} of the OpenGL context that is current in the current thread.
*
* <p>This {@code GLCapabilities} instance will be used by any OpenGL call in the current thread, until {@code setCapabilities} is called again with a
* different value.</p>
*/
public static void setCapabilities(GLCapabilities caps) {
capabilitiesTLS.set(caps);
ThreadLocalUtil.setEnv(caps == null ? NULL : memAddress(caps.addresses), 3);
icd.set(caps);
}
public static GLCapabilities getCapabilities() {
return checkCapabilities(capabilitiesTLS.get());
}
private static GLCapabilities checkCapabilities(GLCapabilities caps) {
if ( CHECKS && caps == null )
throw new IllegalStateException("No GLCapabilities instance set for the current thread. Possible solutions:\n" +
"\ta) Call GL.createCapabilities() after making a context current in the current thread.\n" +
"\tb) Call GL.setCapabilities() if a GLCapabilities instance already exists for the current context.");
return caps;
}
/**
* Returns the WGL capabilities.
*
* <p>This method may only be used on Windows.</p>
*/
public static WGLCapabilities getCapabilitiesWGL() {
if ( capabilitiesWGL == null )
capabilitiesWGL = createCapabilitiesWGLDummy();
return capabilitiesWGL;
}
/** Returns the GLX client capabilities. */
static GLXCapabilities getCapabilitiesGLXClient() {
if ( capabilitiesGLXClient == null )
capabilitiesGLXClient = initCapabilitiesGLX(true);
return capabilitiesGLXClient;
}
/**
* Returns the GLX capabilities.
*
* <p>This method may only be used on Linux.</p>
*/
public static GLXCapabilities getCapabilitiesGLX() {
if ( capabilitiesGLX == null )
capabilitiesGLX = initCapabilitiesGLX(false);
return capabilitiesGLX;
}
private static GLXCapabilities initCapabilitiesGLX(boolean client) {
long display = nXOpenDisplay(NULL);
try {
return createCapabilitiesGLX(display, client ? -1 : XDefaultScreen(display));
} finally {
XCloseDisplay(display);
}
}
/**
* Creates a new {@link GLCapabilities} instance for the OpenGL context that is current in the current thread.
*
* <p>Depending on the current context, the instance returned may or may not contain the deprecated functionality removed since OpenGL version 3.1.</p>
*
* <p>This method calls {@link #setCapabilities(GLCapabilities)} with the new instance before returning.</p>
*
* @return the GLCapabilities instance
*/
public static GLCapabilities createCapabilities() {
return createCapabilities(false);
}
/**
* Creates a new {@link GLCapabilities} instance for the OpenGL context that is current in the current thread.
*
* <p>Depending on the current context, the instance returned may or may not contain the deprecated functionality removed since OpenGL version 3.1. The
* {@code forwardCompatible} flag will force LWJGL to not load the deprecated functions, even if the current context exposes them.</p>
*
* <p>This method calls {@link #setCapabilities(GLCapabilities)} with the new instance before returning.</p>
*
* @param forwardCompatible if true, LWJGL will create forward compatible capabilities
*
* @return the GLCapabilities instance
*/
public static GLCapabilities createCapabilities(boolean forwardCompatible) {
GLCapabilities caps = null;
try {
// We don't have a current ContextCapabilities when this method is called
// so we have to use the native bindings directly.
long GetError = functionProvider.getFunctionAddress("glGetError");
long GetString = functionProvider.getFunctionAddress("glGetString");
long GetIntegerv = functionProvider.getFunctionAddress("glGetIntegerv");
if ( GetError == NULL || GetString == NULL || GetIntegerv == NULL )
throw new IllegalStateException("Core OpenGL functions could not be found. Make sure that the OpenGL library has been loaded correctly.");
int errorCode = callI(GetError);
if ( errorCode != GL_NO_ERROR )
apiLog(String.format("An OpenGL context was in an error state before the creation of its capabilities instance. Error: 0x%X", errorCode));
int majorVersion;
int minorVersion;
try ( MemoryStack stack = stackPush() ) {
IntBuffer version = stack.ints(0);
// Try the 3.0+ version query first
callPV(GetIntegerv, GL_MAJOR_VERSION, memAddress(version));
if ( callI(GetError) == GL_NO_ERROR && 3 <= (majorVersion = version.get(0)) ) {
// We're on an 3.0+ context.
callPV(GetIntegerv, GL_MINOR_VERSION, memAddress(version));
minorVersion = version.get(0);
} else {
// Fallback to the string query.
long versionString = callP(GetString, GL_VERSION);
if ( versionString == NULL || callI(GetError) != GL_NO_ERROR )
throw new IllegalStateException("There is no OpenGL context current in the current thread.");
APIVersion apiVersion = apiParseVersion(memUTF8(versionString));
majorVersion = apiVersion.major;
minorVersion = apiVersion.minor;
}
}
if ( majorVersion < 1 || (majorVersion == 1 && minorVersion < 1) )
throw new IllegalStateException("OpenGL 1.1 is required.");
int[] GL_VERSIONS = {
5, // OpenGL 1.1 to 1.5
1, // OpenGL 2.0 to 2.1
3, // OpenGL 3.0 to 3.3
5, // OpenGL 4.0 to 4.5
};
Set<String> supportedExtensions = new HashSet<>(512);
int maxMajor = min(majorVersion, GL_VERSIONS.length);
if ( MAX_VERSION != null )
maxMajor = min(MAX_VERSION.major, maxMajor);
for ( int M = 1; M <= maxMajor; M++ ) {
int maxMinor = GL_VERSIONS[M - 1];
if ( M == majorVersion )
maxMinor = min(minorVersion, maxMinor);
if ( MAX_VERSION != null && M == MAX_VERSION.major )
maxMinor = min(MAX_VERSION.minor, maxMinor);
for ( int m = M == 1 ? 1 : 0; m <= maxMinor; m++ )
supportedExtensions.add(String.format("OpenGL%d%d", M, m));
}
if ( majorVersion < 3 ) {
// Parse EXTENSIONS string
String extensionsString = memASCII(check(callP(GetString, GL_EXTENSIONS)));
StringTokenizer tokenizer = new StringTokenizer(extensionsString);
while ( tokenizer.hasMoreTokens() )
supportedExtensions.add(tokenizer.nextToken());
} else {
// Use indexed EXTENSIONS
try ( MemoryStack stack = stackPush() ) {
IntBuffer pi = stack.ints(0);
callPV(GetIntegerv, GL_NUM_EXTENSIONS, memAddress(pi));
int extensionCount = pi.get(0);
long GetStringi = apiGetFunctionAddress(functionProvider, "glGetStringi");
for ( int i = 0; i < extensionCount; i++ )
supportedExtensions.add(memASCII(callP(GetStringi, GL_EXTENSIONS, i)));
// In real drivers, we may encounter the following weird scenarios:
// - 3.1 context without GL_ARB_compatibility but with deprecated functionality exposed and working.
// - Core or forward-compatible context with GL_ARB_compatibility exposed, but not working when used.
// We ignore these and go by the spec.
// Force forwardCompatible to true if the context is a forward-compatible context.
callPV(GetIntegerv, GL_CONTEXT_FLAGS, memAddress(pi));
if ( (pi.get(0) & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) != 0 )
forwardCompatible = true;
else {
// Force forwardCompatible to true if the context is a core profile context.
if ( (3 < majorVersion || 1 <= minorVersion) ) { // OpenGL 3.1+
if ( 3 < majorVersion || 2 <= minorVersion ) { // OpenGL 3.2+
callPV(GetIntegerv, GL_CONTEXT_PROFILE_MASK, memAddress(pi));
if ( (pi.get(0) & GL_CONTEXT_CORE_PROFILE_BIT) != 0 )
forwardCompatible = true;
} else
forwardCompatible = !supportedExtensions.contains("GL_ARB_compatibility");
}
}
}
}
return caps = new GLCapabilities(getFunctionProvider(), supportedExtensions, forwardCompatible);
} finally {
setCapabilities(caps);
}
}
/** Creates a dummy context and retrieves the WGL capabilities. */
private static WGLCapabilities createCapabilitiesWGLDummy() {
long hdc = wglGetCurrentDC(); // just use the current context if one exists
if ( hdc != NULL )
return createCapabilitiesWGL(hdc);
short classAtom = 0;
long hwnd = NULL;
long hglrc = NULL;
try ( MemoryStack stack = stackPush() ) {
WNDCLASSEX wc = WNDCLASSEX.callocStack(stack)
.cbSize(WNDCLASSEX.SIZEOF)
.style(CS_HREDRAW | CS_VREDRAW)
.hInstance(WindowsLibrary.HINSTANCE)
.lpszClassName(stack.UTF16("WGL"));
memPutAddress(
wc.address() + WNDCLASSEX.LPFNWNDPROC,
User32.Functions.DefWindowProc
);
classAtom = RegisterClassEx(wc);
if ( classAtom == 0 )
throw new IllegalStateException("Failed to register WGL window class");
hwnd = check(nCreateWindowEx(
0, classAtom & 0xFFFF, NULL,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
0, 0, 1, 1,
NULL, NULL, NULL, NULL
));
hdc = check(GetDC(hwnd));
PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.callocStack(stack)
.nSize((short)PIXELFORMATDESCRIPTOR.SIZEOF)
.nVersion((short)1)
.dwFlags(PFD_SUPPORT_OPENGL); // we don't care about anything else
int pixelFormat = ChoosePixelFormat(hdc, pfd);
if ( pixelFormat == 0 )
windowsThrowException("Failed to choose an OpenGL-compatible pixel format");
if ( DescribePixelFormat(hdc, pixelFormat, pfd) == 0 )
windowsThrowException("Failed to obtain pixel format information");
if ( !SetPixelFormat(hdc, pixelFormat, pfd) )
windowsThrowException("Failed to set the pixel format");
hglrc = check(wglCreateContext(hdc));
wglMakeCurrent(hdc, hglrc);
return createCapabilitiesWGL(hdc);
} finally {
if ( hglrc != NULL ) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hglrc);
}
if ( hwnd != NULL )
DestroyWindow(hwnd);
if ( classAtom != 0 )
nUnregisterClass(classAtom & 0xFFFF, WindowsLibrary.HINSTANCE);
}
}
/**
* Creates a {@link WGLCapabilities} instance for the context that is current in the current thread.
*
* <p>This method may only be used on Windows.</p>
*/
public static WGLCapabilities createCapabilitiesWGL() {
long hdc = wglGetCurrentDC();
if ( hdc == NULL )
throw new IllegalStateException("Failed to retrieve the device context of the current OpenGL context");
return createCapabilitiesWGL(hdc);
}
/**
* Creates a {@link WGLCapabilities} instance for the specified device context.
*
* @param hdc the device context handle ({@code HDC})
*/
private static WGLCapabilities createCapabilitiesWGL(long hdc) {
String extensionsString = null;
long wglGetExtensionsString = functionProvider.getFunctionAddress("wglGetExtensionsStringARB");
if ( wglGetExtensionsString != NULL )
extensionsString = memASCII(callPP(wglGetExtensionsString, hdc));
else {
wglGetExtensionsString = functionProvider.getFunctionAddress("wglGetExtensionsStringEXT");
if ( wglGetExtensionsString != NULL )
extensionsString = memASCII(callP(wglGetExtensionsString));
}
Set<String> supportedExtensions = new HashSet<>(32);
if ( extensionsString != null ) {
StringTokenizer tokenizer = new StringTokenizer(extensionsString);
while ( tokenizer.hasMoreTokens() )
supportedExtensions.add(tokenizer.nextToken());
}
return new WGLCapabilities(functionProvider, supportedExtensions);
}
/**
* Creates a {@link GLXCapabilities} instance for the default screen of the specified X connection.
*
* <p>This method may only be used on Linux.</p>
*
* @param display the X connection handle ({@code DISPLAY})
*/
public static GLXCapabilities createCapabilitiesGLX(long display) {
return createCapabilitiesGLX(display, XDefaultScreen(display));
}
/**
* Creates a {@link GLXCapabilities} instance for the specified screen of the specified X connection.
*
* <p>This method may only be used on Linux.</p>
*
* @param display the X connection handle ({@code DISPLAY})
* @param screen the screen index
*/
public static GLXCapabilities createCapabilitiesGLX(long display, int screen) {
int majorVersion;
int minorVersion;
try ( MemoryStack stack = stackPush() ) {
IntBuffer piMajor = stack.ints(0);
IntBuffer piMinor = stack.ints(0);
if ( glXQueryVersion(display, piMajor, piMinor) == 0 )
throw new IllegalStateException("Failed to query GLX version");
majorVersion = piMajor.get(0);
minorVersion = piMinor.get(0);
if ( majorVersion != 1 )
throw new IllegalStateException("Invalid GLX major version: " + majorVersion);
}
Set<String> supportedExtensions = new HashSet<>(32);
int[][] GLX_VERSIONS = {
{ 1, 2, 3, 4 }
};
for ( int major = 1; major <= GLX_VERSIONS.length; major++ ) {
int[] minors = GLX_VERSIONS[major - 1];
for ( int minor : minors ) {
if ( major < majorVersion || (major == majorVersion && minor <= minorVersion) )
supportedExtensions.add("GLX" + Integer.toString(major) + Integer.toString(minor));
}
}
if ( 1 <= minorVersion ) {
long extensionsString;
if ( screen == -1 ) {
long glXGetClientString = functionProvider.getFunctionAddress("glXGetClientString");
extensionsString = callPP(glXGetClientString, display, GLX_EXTENSIONS);
} else {
long glXQueryExtensionsString = functionProvider.getFunctionAddress("glXQueryExtensionsString");
extensionsString = callPP(glXQueryExtensionsString, display, screen);
}
StringTokenizer tokenizer = new StringTokenizer(memASCII(extensionsString));
while ( tokenizer.hasMoreTokens() )
supportedExtensions.add(tokenizer.nextToken());
}
return new GLXCapabilities(functionProvider, supportedExtensions);
}
// Only used by array overloads
static GLCapabilities getICD() {
return icd.get();
}
/** Function pointer provider. */
private interface ICD {
default void set(GLCapabilities caps) {}
GLCapabilities get();
}
/**
* Write-once {@link ICD}.
*
* <p>This is the default implementation that skips the thread-local lookup. When a new GLCapabilities is set, we compare it to the write-once capabilities.
* If different function pointers are found, we fall back to the expensive lookup.</p>
*/
private static class ICDStatic implements ICD {
private static GLCapabilities tempCaps;
@Override
public void set(GLCapabilities caps) {
if ( caps != null && tempCaps != null && !ThreadLocalUtil.compareCapabilities(tempCaps.addresses, caps.addresses) ) {
apiLog("[WARNING] Incompatible context detected. Falling back to thread-local lookup for GL contexts.");
icd = GL::getCapabilities; // fall back to thread/process lookup
return;
}
if ( tempCaps == null )
tempCaps = caps;
}
@Override
public GLCapabilities get() {
return WriteOnce.caps;
}
private static final class WriteOnce {
// This will be initialized the first time get() above is called
private static final GLCapabilities caps = ICDStatic.tempCaps;
static {
if ( caps == null )
throw new IllegalStateException("No GLCapabilities instance has been set");
}
}
}
}
|
package org.onlab.netty;
import java.io.IOException;
/**
* Internal message representation with additional attributes
* for supporting, synchronous request/reply behavior.
*/
public final class InternalMessage implements Message {
public static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGIG_REQUEST_REPLY";
private long id;
private Endpoint sender;
private String type;
private byte[] payload;
private transient NettyMessagingService messagingService;
// Must be created using the Builder.
private InternalMessage() {}
public long id() {
return id;
}
public String type() {
return type;
}
public Endpoint sender() {
return sender;
}
@Override
public byte[] payload() {
return payload;
}
protected void setMessagingService(NettyMessagingService messagingService) {
this.messagingService = messagingService;
}
@Override
public void respond(byte[] data) throws IOException {
Builder builder = new Builder(messagingService);
InternalMessage message = builder.withId(this.id)
// FIXME: Sender should be messagingService.localEp.
.withSender(this.sender)
.withPayload(data)
.withType(REPLY_MESSAGE_TYPE)
.build();
messagingService.sendAsync(sender, message);
}
/**
* Builder for InternalMessages.
*/
public static final class Builder {
private InternalMessage message;
public Builder(NettyMessagingService messagingService) {
message = new InternalMessage();
message.messagingService = messagingService;
}
public Builder withId(long id) {
message.id = id;
return this;
}
public Builder withType(String type) {
message.type = type;
return this;
}
public Builder withSender(Endpoint sender) {
message.sender = sender;
return this;
}
public Builder withPayload(byte[] payload) {
message.payload = payload;
return this;
}
public InternalMessage build() {
return message;
}
}
}
|
package org.jpos.ee;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.*;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.jpos.core.ConfigurationException;
import org.jpos.ee.support.ModuleUtils;
import org.jpos.util.Log;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;
@SuppressWarnings({"UnusedDeclaration"})
public class DB implements Closeable
{
Session session;
Log log;
String configModifier;
private static volatile SessionFactory sessionFactory = null;
private static String propFile;
private static final String MODULES_CONFIG_PATH = "META-INF/org/jpos/ee/modules/";
/**
* Creates DB Object using default Hibernate instance
*/
public DB()
{
super();
}
/**
* Creates DB Object using a config <i>modifier</i>.
*
* The <i>configModifier</i> can take a number of different forms used to locate the <code>cfg/db.properties</code> file.
*
* <ul>
*
* <li>a filename prefix, i.e.: "mysql" used as modifier would pick the configuration from
* <code>cfg/mysql-db.properties</code> instead of the default <code>cfg/db.properties</code> </li>
*
* <li>if a colon and a second modifier is present (e.g.: "mysql:v1"), the metadata is picked from
* <code>META-INF/org/jpos/ee/modules/v1-*</code> instead of just
* <code>META-INF/org/jpos/ee/modules/</code> </li>
*
* <li>finally, if the modifier ends with <code>.hbm.xml</code> (case insensitive), then all configuration
* is picked from that config file.</li>
* </ul>
*
* @param configModifier modifier
*/
public DB (String configModifier) {
super();
this.configModifier = configModifier;
}
/**
* Creates DB Object using default Hibernate instance
*
* @param log Log object
*/
public DB(Log log)
{
super();
setLog(log);
}
/**
* Creates DB Object using default Hibernate instance
*
* @param log Log object
* @param configModifier modifier
*/
public DB(Log log, String configModifier) {
this(configModifier);
setLog(log);
}
/**
* @return Hibernate's session factory
*/
public SessionFactory getSessionFactory()
{
if (sessionFactory == null)
{
synchronized (DB.class)
{
if (sessionFactory == null)
{
try
{
sessionFactory = newSessionFactory();
}
catch (IOException | ConfigurationException | DocumentException e)
{
throw new RuntimeException("Could not configure session factory", e);
}
}
}
}
return sessionFactory;
}
public static synchronized void invalidateSessionFactory()
{
sessionFactory = null;
}
private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException {
return getMetadata().buildSessionFactory();
}
private void configureProperties(Configuration cfg) throws IOException
{
String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null)
{
cfg.addProperties(dbProps);
}
}
private void configureMappings(Configuration cfg) throws ConfigurationException, IOException {
try {
List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/");
for (String moduleConfig : moduleConfigs) {
addMappings(cfg, moduleConfig);
}
} catch (DocumentException e) {
throw new ConfigurationException("Could not parse mappings document", e);
}
}
private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(cfg, mapping, moduleConfig);
}
}
}
private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
{
cfg.addResource(resource);
}
else if (clazz != null)
{
try
{
cfg.addAnnotatedClass(ReflectHelper.classForName(clazz));
}
catch (ClassNotFoundException e)
{
throw new ConfigurationException("Class " + clazz + " specified in mapping for module " + moduleName + " cannot be found");
}
}
else
{
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
}
private Element readMappingElements(String moduleConfig) throws DocumentException
{
SAXReader reader = new SAXReader();
final URL url = getClass().getClassLoader().getResource(moduleConfig);
assert url != null;
final Document doc = reader.read(url);
return doc.getRootElement().element("mappings");
}
private Properties loadProperties(String filename) throws IOException
{
Properties props = new Properties();
final String s = filename.replaceAll("/", "\\" + File.separator);
final File f = new File(s);
if (f.exists())
{
props.load(new FileReader(f));
}
return props;
}
/**
* Creates database schema
*
* @param outputFile optional output file (may be null)
* @param create true to actually issue the create statements
*/
public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException {
try {
// SchemaExport export = new SchemaExport(getMetadata());
SchemaExport export = new SchemaExport();
List<TargetType> targetTypes=new ArrayList<>();
if (outputFile != null) {
if(outputFile.trim().equals("-")) targetTypes.add(TargetType.STDOUT);
else {
export.setOutputFile(outputFile);
export.setDelimiter(";");
targetTypes.add(TargetType.SCRIPT);
}
}
if (create)
targetTypes.add(TargetType.DATABASE);
if(targetTypes.size()>0)
export.create(EnumSet.copyOf(targetTypes), getMetadata());
}
catch (IOException | ConfigurationException e)
{
throw new HibernateException("Could not create schema", e);
}
}
/**
* open a new HibernateSession if none exists
*
* @return HibernateSession associated with this DB object
* @throws HibernateException
*/
public synchronized Session open() throws HibernateException
{
if (session == null)
{
session = getSessionFactory().openSession();
}
return session;
}
/**
* close hibernate session
*
* @throws HibernateException
*/
public synchronized void close() throws HibernateException
{
if (session != null)
{
session.close();
session = null;
}
}
/**
* @return session hibernate Session
*/
public Session session()
{
return session;
}
/**
* handy method used to avoid having to call db.session().save (xxx)
*
* @param obj to save
*/
public void save(Object obj) throws HibernateException
{
session.save(obj);
}
/**
* handy method used to avoid having to call db.session().saveOrUpdate (xxx)
*
* @param obj to save or update
*/
public void saveOrUpdate(Object obj) throws HibernateException
{
session.saveOrUpdate(obj);
}
public void delete(Object obj)
{
session.delete(obj);
}
/**
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction() throws HibernateException
{
return session.beginTransaction();
}
public synchronized void commit()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().isOneOf(TransactionStatus.ACTIVE))
{
tx.commit();
}
}
}
public synchronized void rollback()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().canRollback())
{
tx.rollback();
}
}
}
/**
* @param timeout in seconds
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction(int timeout) throws HibernateException
{
Transaction tx = session.getTransaction();
if (timeout > 0)
tx.setTimeout(timeout);
tx.begin();
return tx;
}
public synchronized Log getLog()
{
if (log == null)
{
log = Log.getLog("Q2", "DB"); // Q2 standard Logger
}
return log;
}
public synchronized void setLog(Log log)
{
this.log = log;
}
public static Object exec(DBAction action) throws Exception
{
try (DB db = new DB())
{
db.open();
return action.exec(db);
}
}
public static Object execWithTransaction(DBAction action) throws Exception
{
try (DB db = new DB())
{
db.open();
db.beginTransaction();
Object obj = action.exec(db);
db.commit();
return obj;
}
}
@SuppressWarnings("unchecked")
public static <T> T unwrap (T proxy) {
Hibernate.getClass(proxy);
Hibernate.initialize(proxy);
return (proxy instanceof HibernateProxy) ?
(T) ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation() : proxy;
}
@SuppressWarnings({"unchecked"})
public void printStats()
{
if (getLog() != null)
{
LogEvent info = getLog().createInfo();
if (session != null)
{
info.addMessage("==== STATISTICS ====");
SessionStatistics statistics = session().getStatistics();
info.addMessage("==== ENTITIES ====");
Set<EntityKey> entityKeys = statistics.getEntityKeys();
for (EntityKey ek : entityKeys)
{
info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName()));
}
info.addMessage("==== COLLECTIONS ====");
Set<CollectionKey> collectionKeys = statistics.getCollectionKeys();
for (CollectionKey ck : collectionKeys)
{
info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole()));
}
info.addMessage("=====================");
}
else
{
info.addMessage("Session is not open");
}
Logger.log(info);
}
}
private MetadataImplementor getMetadata() throws IOException, ConfigurationException, DocumentException {
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
String propFile;
String dbPropertiesPrefix = "";
String metadataPrefix = "";
if (configModifier != null) {
String[] ss = configModifier.split(":");
if (ss.length > 0)
dbPropertiesPrefix = ss[0] + "-";
if (ss.length > 1)
metadataPrefix = ss[1] + "-";
}
String hibCfg = System.getProperty("HIBERNATE_CFG","/" + dbPropertiesPrefix + "hibernate.cfg.xml");
if (getClass().getClassLoader().getResource(hibCfg) == null)
hibCfg = null;
if (hibCfg == null)
hibCfg = System.getProperty("HIBERNATE_CFG","/hibernate.cfg.xml");
ssrb.configure(hibCfg);
propFile = System.getProperty(dbPropertiesPrefix + "DB_PROPERTIES", "cfg/" + dbPropertiesPrefix + "db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null) {
for (Map.Entry entry : dbProps.entrySet()) {
ssrb.applySetting((String) entry.getKey(), entry.getValue());
}
}
MetadataSources mds = new MetadataSources(ssrb.build());
List<String> moduleConfigs = ModuleUtils.getModuleEntries(MODULES_CONFIG_PATH);
for (String moduleConfig : moduleConfigs) {
if (metadataPrefix.length() == 0 || moduleConfig.substring(MODULES_CONFIG_PATH.length()).startsWith(metadataPrefix)) {
addMappings(mds, moduleConfig);
}
}
return (MetadataImplementor) mds.buildMetadata();
}
private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(mds, mapping, moduleConfig);
}
}
}
private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
mds.addResource(resource);
else if (clazz != null)
mds.addAnnotatedClassName(clazz);
else
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
}
|
package org.jpos.ee;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.jpos.core.ConfigurationException;
import org.jpos.ee.support.ModuleUtils;
import org.jpos.space.Space;
import org.jpos.space.SpaceFactory;
import org.jpos.util.Log;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Semaphore;
@SuppressWarnings({"UnusedDeclaration"})
public class DB implements Closeable {
Session session;
Log log;
String configModifier;
private static Semaphore sfSem = new Semaphore(1);
private static Semaphore mdSem = new Semaphore(1);
private static String propFile;
private static final String MODULES_CONFIG_PATH = "META-INF/org/jpos/ee/modules/";
private static Map<String,SessionFactory> sessionFactories = Collections.synchronizedMap(new HashMap<>());
private static Map<String,Metadata> metadatas = Collections.synchronizedMap(new HashMap<>());
/**
* Creates DB Object using default Hibernate instance
*/
public DB() {
super();
}
/**
* Creates DB Object using a config <i>modifier</i>.
*
* The <i>configModifier</i> can take a number of different forms used to locate the <code>cfg/db.properties</code> file.
*
* <ul>
*
* <li>a filename prefix, i.e.: "mysql" used as modifier would pick the configuration from
* <code>cfg/mysql-db.properties</code> instead of the default <code>cfg/db.properties</code> </li>
*
* <li>if a colon and a second modifier is present (e.g.: "mysql:v1"), the metadata is picked from
* <code>META-INF/org/jpos/ee/modules/v1-*</code> instead of just
* <code>META-INF/org/jpos/ee/modules/</code> </li>
*
* <li>finally, if the modifier ends with <code>.hbm.xml</code> (case insensitive), then all configuration
* is picked from that config file.</li>
* </ul>
*
* @param configModifier modifier
*/
public DB (String configModifier) {
super();
this.configModifier = configModifier;
}
/**
* Creates DB Object using default Hibernate instance
*
* @param log Log object
*/
public DB(Log log) {
super();
setLog(log);
}
/**
* Creates DB Object using default Hibernate instance
*
* @param log Log object
* @param configModifier modifier
*/
public DB(Log log, String configModifier) {
this(configModifier);
setLog(log);
}
/**
* @return Hibernate's session factory
*/
public SessionFactory getSessionFactory() {
String cm = configModifier != null ? configModifier : "";
sfSem.acquireUninterruptibly();
SessionFactory sf = sessionFactories.get(cm);
try {
if (sf == null)
sessionFactories.put(cm, sf = newSessionFactory());
} catch (IOException | ConfigurationException | DocumentException e) {
throw new RuntimeException("Could not configure session factory", e);
} finally {
sfSem.release();
}
return sf;
}
public static synchronized void invalidateSessionFactories() {
sessionFactories.clear();
}
private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException {
return getMetadata().buildSessionFactory();
}
private void configureProperties(Configuration cfg) throws IOException
{
String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null)
{
cfg.addProperties(dbProps);
}
}
private void configureMappings(Configuration cfg) throws ConfigurationException, IOException {
try {
List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/");
for (String moduleConfig : moduleConfigs) {
addMappings(cfg, moduleConfig);
}
} catch (DocumentException e) {
throw new ConfigurationException("Could not parse mappings document", e);
}
}
private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(cfg, mapping, moduleConfig);
}
}
}
private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
{
cfg.addResource(resource);
}
else if (clazz != null)
{
try
{
cfg.addAnnotatedClass(ReflectHelper.classForName(clazz));
}
catch (ClassNotFoundException e)
{
throw new ConfigurationException("Class " + clazz + " specified in mapping for module " + moduleName + " cannot be found");
}
}
else
{
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
}
private Element readMappingElements(String moduleConfig) throws DocumentException
{
SAXReader reader = new SAXReader();
final URL url = getClass().getClassLoader().getResource(moduleConfig);
assert url != null;
final Document doc = reader.read(url);
return doc.getRootElement().element("mappings");
}
private Properties loadProperties(String filename) throws IOException
{
Properties props = new Properties();
final String s = filename.replaceAll("/", "\\" + File.separator);
final File f = new File(s);
if (f.exists())
{
props.load(new FileReader(f));
}
return props;
}
/**
* Creates database schema
*
* @param outputFile optional output file (may be null)
* @param create true to actually issue the create statements
*/
public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException {
try {
// SchemaExport export = new SchemaExport(getMetadata());
SchemaExport export = new SchemaExport();
List<TargetType> targetTypes=new ArrayList<>();
if (outputFile != null) {
export.setDelimiter(";");
if(outputFile.trim().equals("-")) {
targetTypes.add(TargetType.STDOUT);
}
else {
export.setOutputFile(outputFile);
targetTypes.add(TargetType.SCRIPT);
}
}
if (create)
targetTypes.add(TargetType.DATABASE);
if(targetTypes.size()>0)
export.create(EnumSet.copyOf(targetTypes), getMetadata());
}
catch (IOException | ConfigurationException e)
{
throw new HibernateException("Could not create schema", e);
}
}
/**
* open a new HibernateSession if none exists
*
* @return HibernateSession associated with this DB object
* @throws HibernateException
*/
public synchronized Session open() throws HibernateException
{
if (session == null)
{
session = getSessionFactory().openSession();
}
return session;
}
/**
* close hibernate session
*
* @throws HibernateException
*/
public synchronized void close() throws HibernateException
{
if (session != null)
{
session.close();
session = null;
}
}
/**
* @return session hibernate Session
*/
public Session session()
{
return session;
}
/**
* handy method used to avoid having to call db.session().save (xxx)
*
* @param obj to save
*/
public void save(Object obj) throws HibernateException
{
session.save(obj);
}
/**
* handy method used to avoid having to call db.session().saveOrUpdate (xxx)
*
* @param obj to save or update
*/
public void saveOrUpdate(Object obj) throws HibernateException
{
session.saveOrUpdate(obj);
}
public void delete(Object obj)
{
session.delete(obj);
}
/**
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction() throws HibernateException
{
return session.beginTransaction();
}
public synchronized void commit()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().isOneOf(TransactionStatus.ACTIVE))
{
tx.commit();
}
}
}
public synchronized void rollback()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().canRollback())
{
tx.rollback();
}
}
}
/**
* @param timeout in seconds
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction(int timeout) throws HibernateException
{
Transaction tx = session.getTransaction();
if (timeout > 0)
tx.setTimeout(timeout);
tx.begin();
return tx;
}
public synchronized Log getLog()
{
if (log == null)
{
log = Log.getLog("Q2", "DB"); // Q2 standard Logger
}
return log;
}
public synchronized void setLog(Log log)
{
this.log = log;
}
public static Object exec(DBAction action) throws Exception {
try (DB db = new DB()) {
db.open();
return action.exec(db);
}
}
public static Object exec(String configModifier, DBAction action) throws Exception {
try (DB db = new DB(configModifier)) {
db.open();
return action.exec(db);
}
}
public static Object execWithTransaction(DBAction action) throws Exception {
try (DB db = new DB()) {
db.open();
db.beginTransaction();
Object obj = action.exec(db);
db.commit();
return obj;
}
}
public static Object execWithTransaction(String configModifier, DBAction action) throws Exception {
try (DB db = new DB(configModifier)) {
db.open();
db.beginTransaction();
Object obj = action.exec(db);
db.commit();
return obj;
}
}
@SuppressWarnings("unchecked")
public static <T> T unwrap (T proxy) {
Hibernate.getClass(proxy);
Hibernate.initialize(proxy);
return (proxy instanceof HibernateProxy) ?
(T) ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation() : proxy;
}
@SuppressWarnings({"unchecked"})
public void printStats()
{
if (getLog() != null)
{
LogEvent info = getLog().createInfo();
if (session != null)
{
info.addMessage("==== STATISTICS ====");
SessionStatistics statistics = session().getStatistics();
info.addMessage("==== ENTITIES ====");
Set<EntityKey> entityKeys = statistics.getEntityKeys();
for (EntityKey ek : entityKeys)
{
info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName()));
}
info.addMessage("==== COLLECTIONS ====");
Set<CollectionKey> collectionKeys = statistics.getCollectionKeys();
for (CollectionKey ck : collectionKeys)
{
info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole()));
}
info.addMessage("=====================");
}
else
{
info.addMessage("Session is not open");
}
Logger.log(info);
}
}
@Override
public String toString() {
return "DB{" + (configModifier != null ? configModifier : "") + '}';
}
private Metadata getMetadata() throws IOException, ConfigurationException, DocumentException {
String cm = configModifier != null ? configModifier : "";
mdSem.acquireUninterruptibly();
Metadata md = metadatas.get(cm);
try {
if (md == null) {
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
String propFile;
String dbPropertiesPrefix = "";
String metadataPrefix = "";
if (configModifier != null) {
String[] ss = configModifier.split(":");
if (ss.length > 0)
dbPropertiesPrefix = ss[0] + ":";
if (ss.length > 1)
metadataPrefix = ss[1] + ":";
}
String hibCfg = System.getProperty("HIBERNATE_CFG","/" + dbPropertiesPrefix + "hibernate.cfg.xml");
if (getClass().getClassLoader().getResource(hibCfg) == null)
hibCfg = null;
if (hibCfg == null)
hibCfg = System.getProperty("HIBERNATE_CFG","/hibernate.cfg.xml");
ssrb.configure(hibCfg);
propFile = System.getProperty(dbPropertiesPrefix + "DB_PROPERTIES", "cfg/" + dbPropertiesPrefix + "db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null) {
for (Map.Entry entry : dbProps.entrySet()) {
ssrb.applySetting((String) entry.getKey(), entry.getValue());
}
}
// if DBInstantiator has put db user name and/or password in Space, set Hibernate config accordingly
Space sp = SpaceFactory.getSpace("tspace:dbconfig");
String user = (String) sp.inp(dbPropertiesPrefix +"connection.username");
String pass = (String) sp.inp(dbPropertiesPrefix +"connection.password");
if (user != null)
ssrb.applySetting("hibernate.connection.username", user);
if (pass != null)
ssrb.applySetting("hibernate.connection.password", pass);
MetadataSources mds = new MetadataSources(ssrb.build());
List<String> moduleConfigs = ModuleUtils.getModuleEntries(MODULES_CONFIG_PATH);
for (String moduleConfig : moduleConfigs) {
if (metadataPrefix.length() == 0 || moduleConfig.substring(MODULES_CONFIG_PATH.length()).startsWith(metadataPrefix)) {
if ( (!metadataPrefix.contains(":") && moduleConfig.contains(":")) ||
(!moduleConfig.contains(":") && metadataPrefix.contains(":")))
continue;
addMappings(mds, moduleConfig);
}
}
md = mds.buildMetadata();
metadatas.put(cm, md);
}
} finally {
mdSem.release();
}
return md;
}
private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(mds, mapping, moduleConfig);
}
}
}
private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
mds.addResource(resource);
else if (clazz != null)
mds.addAnnotatedClassName(clazz);
else
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
}
|
package vars.avplayer.jfx.vcr;
import javafx.beans.value.ChangeListener;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;
import org.mbari.vcr4j.VCRAdapter;
import org.mbari.vcr4j.time.Timecode;
public class VCR extends VCRAdapter {
/**
* To best handle proxies. We use fractional seconds as frames. This lets us swap videos
* and likely be close enough (1/100th sec) to the actual frame of interest between
* alternate proxies.
*/
public static final double DEFAULT_FRAME_RATE = 100D;
public static final double FAST_FORWARD_RATE = 5D;
public static final double MAX_RATE = 8D; // According to JavaFX docs this is the max rate
private final MediaPlayer mediaPlayer;
private final ChangeListener<Duration> timeListener;
public VCR(final MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
vcrReply = new Reply(this);
timeListener = (observableValue, oldDuration, newDuration) -> {
double frames = newDuration.toSeconds() * VCR.DEFAULT_FRAME_RATE;
Timecode timecode = new Timecode(frames, VCR.DEFAULT_FRAME_RATE);
vcrReply.getVcrTimecode().timecodeProperty().set(timecode);
};
mediaPlayer.currentTimeProperty().addListener(timeListener);
triggerStateNotification();
}
@Override
public void shuttleForward(int speed) {
double rate = speed / 255D * MAX_RATE;
mediaPlayer.setRate(rate);
//mediaPlayer.play();
super.shuttleForward(speed);
triggerStateNotification();
}
@Override
public String getConnectionName() {
return mediaPlayer.getMedia().getSource();
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
@Override
public void pause() {
mediaPlayer.pause();
triggerStateNotification();
}
@Override
public void play() {
mediaPlayer.setRate(1.0);
mediaPlayer.play();
triggerStateNotification();
}
@Override
public void rewind() {
// Negative rate playback is not supported
}
@Override
public void stop() {
mediaPlayer.pause();
triggerStateNotification();
}
@Override
public void disconnect() {
if (mediaPlayer != null) {
mediaPlayer.currentTimeProperty().removeListener(timeListener);
}
super.disconnect();
triggerStateNotification();
}
@Override
public void fastForward() {
mediaPlayer.setRate(FAST_FORWARD_RATE);
mediaPlayer.play();
super.fastForward();
triggerStateNotification();
}
public void triggerStateNotification() {
State state = (State) getVcrState();
state.notifyObserversFX();
}
@Override
public void requestStatus() {
super.requestStatus();
triggerStateNotification();
}
@Override
public void seekTimecode(Timecode timecode) {
//Timecode currentTimecode = getVcrTimecode().getTimecode();
Timecode tc = timecode;
if (!timecode.isComplete()) {
tc = new Timecode(timecode.toString(), DEFAULT_FRAME_RATE);
}
//double seconds = tc.getFrames() / currentTimecode.getFrameRate();
double seconds = tc.getSeconds();
Duration duration = new Duration(seconds * 1000D);
//System.out.println(duration);
mediaPlayer.seek(duration);
super.seekTimecode(timecode);
triggerStateNotification();
}
}
|
package org.flymine.xml.lite;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.flymine.util.TypeUtil;
import org.apache.log4j.Logger;
/**
* Render an object in FlyMine Lite XML format
*
* @author Andrew Varley
*/
public class LiteRenderer
{
protected static final Logger LOG = Logger.getLogger(LiteRenderer.class);
/**
* Don't allow construction
*/
private LiteRenderer() {
}
/**
* Render the given object as XML in FlyMine Lite format
*
* @param obj the object to render
* @return the XML for that object
*/
public static String render(Object obj) {
StringBuffer sb = new StringBuffer();
sb.append("<object class=\"")
.append(getClassName(obj))
.append("\" implements=\"")
.append(getImplements(obj))
.append("\">")
.append(getFields(obj))
.append("</object>");
return sb.toString();
}
/**
* Get all interfaces that an object implements.
*
* @param obj the object
* @return space separated list of extended/implemented classes/interfaces
*/
protected static String getImplements(Object obj) {
StringBuffer sb = new StringBuffer();
Class [] interfaces = obj.getClass().getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
sb.append(interfaces[i].getName())
.append(" ");
}
return sb.toString().trim();
}
/**
* Get all interfaces that an object implements.
*
* @param obj the object
* @return space separated list of extended/implemented classes/interfaces
*/
protected static String getClassName(Object obj) {
StringBuffer sb = new StringBuffer();
// This class - will need to be cleverer when dynamic classes introduced
sb.append(obj.getClass().getName())
.append(" ");
return sb.toString().trim();
}
/**
* Get all classes and interfaces that an object extends/implements.
*
* @param obj the object
* @return string separated list of extended/implemented classes/interfaces
*/
protected static String getFields(Object obj) {
StringBuffer sb = new StringBuffer();
Map infos = TypeUtil.getFieldInfos(obj.getClass());
Iterator iter = infos.keySet().iterator();
try {
while (iter.hasNext()) {
// If reference, value is id of referred-to object
// If field, value is field value
// If collection, no element output
// Element is not output if the value is null
String fieldname = (String) iter.next();
Object value = TypeUtil.getFieldValue(obj, fieldname);
if (value == null) {
continue;
}
// Collection
if (Collection.class.isAssignableFrom(value.getClass())) {
continue;
}
Object id = null;
// Reference
try {
Method m = value.getClass().getMethod("getId", new Class[] {});
id = m.invoke(value, null);
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
} catch (NoSuchMethodException e) {
}
if (id != null) {
value = id;
}
sb.append((id == null ? "<field" : "<reference") + " name=\"")
.append(fieldname)
.append("\" value=\"");
if (value instanceof Date) {
sb.append(((Date) value).getTime());
} else {
sb.append(value);
}
sb.append("\"/>");
}
} catch (IllegalAccessException e) {
}
return sb.toString().trim();
}
}
|
package inpro.audio;
import inpro.synthesis.hts.VocodingAudioStream;
import java.io.IOException;
import java.net.URL;
import gov.nist.sphere.jaudio.SphereFileReader;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.spi.AudioFileReader;
import marytts.util.data.BaseDoubleDataSource;
import marytts.util.data.DoubleDataSource;
import marytts.util.data.audio.AudioConverterUtils;
import marytts.util.data.audio.DDSAudioInputStream;
import org.kc7bfi.jflac.sound.spi.FlacAudioFileReader;
public class AudioUtils {
public static AudioInputStream getAudioStreamForURL(URL audioFileURL) throws UnsupportedAudioFileException, IOException {
AudioInputStream ais;
String lowerCaseURL = audioFileURL.getFile().toLowerCase();
if (lowerCaseURL.endsWith(".sph") ||
lowerCaseURL.endsWith(".nis")) {
AudioFileReader sfr = new SphereFileReader();
ais = sfr.getAudioInputStream(audioFileURL);
} else if (lowerCaseURL.endsWith(".flac")) {
ais = null;
FlacAudioFileReader fafr = new FlacAudioFileReader();
ais = fafr.getAudioInputStream(audioFileURL);
} else {
// System.err.println(AudioSystem.getAudioFileFormat(audioFileURL));
ais = AudioSystem.getAudioInputStream(audioFileURL);
}
return ais;
}
public static AudioInputStream get16kAudioStreamForVocodingStream(VocodingAudioStream source) {
if (source.getSamplingRate() == 48000) {
// TODO: handle 48000 incrementally by averaging or picking every second sample
DoubleDataSource skippingSource = new SkipStream(source, 3);
return new DDSAudioInputStream(skippingSource, new AudioFormat(16000, 16, 1, true, false));
} else if (source.getSamplingRate() == 32000) {
// TODO: handle 32000 incrementally by averaging or picking every second sample
DoubleDataSource skippingSource = new SkipStream(source, 2);
return new DDSAudioInputStream(skippingSource, new AudioFormat(16000, 16, 1, true, false));
} else {
DDSAudioInputStream ddsStream = new DDSAudioInputStream(source, new AudioFormat(source.getSamplingRate(), 16, 1, true, false));
if (source.getSamplingRate() == 16000) {
return ddsStream;
} else {
try {
// FIXME: add a warning that the following doesn't work incrementally!!
System.err.println("WARNING: downsampling is non-incremental!");
return AudioConverterUtils.downSampling(ddsStream, 16000);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
// this is a dirty hack:
private static class SkipStream extends BaseDoubleDataSource {
DoubleDataSource source;
int skip;
public SkipStream(VocodingAudioStream source, int skip) {
this.source = source;
this.skip = skip;
}
@Override
public int getData(double[] target, int targetPos, int length) {
if (available() == 0) {
try { Thread.sleep(2); // take it easy, buddy.
} catch (InterruptedException e) { e.printStackTrace(); }
}
int outputAmount = Math.min(available() / skip, length);
int inputAmount = outputAmount * skip;
double[] inputValues = new double[inputAmount];
source.getData(inputValues, 0, inputAmount);
for (int i = 0; i < outputAmount; i++) {
target[i] = inputValues[i * skip];
}
return outputAmount;
}
@Override
public boolean hasMoreData() {
return source.hasMoreData();
}
@Override
public int available() {
return source.available() / 2;
}
@Override
public long getDataLength() {
return source.getDataLength() == DoubleDataSource.NOT_SPECIFIED ? DoubleDataSource.NOT_SPECIFIED : source.getDataLength() / 2; // not specified
}
}
}
|
package org.epics.vtype.json;
import javax.json.JsonObject;
import org.epics.vtype.VType;
/**
* Utility to serialize and de-serialize vTypes to and from JSON objects.
* These methods convert vTypes to and from standard JSONP objects. One
* can then use the standard library to serialize/de-serialize text streams.
*
* @author carcassi
*/
public class VTypeToJson {
/**
* Converts the given JsonObject to a vType.
*
* @param json a JSON object
* @return the corresponding vType
*/
public static VType toVType(JsonObject json) {
return VTypeToJsonV1.toVType(json);
}
/**
* Converts the given vType to a JsonObject.
*
* @param vType a vType
* @return the corresponding JsonObject
*/
public static JsonObject toJson(VType vType) {
return VTypeToJsonV1.toJson(vType);
}
}
|
package com.intellij.codeInsight.actions;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.LanguageImportStatements;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.util.Arrays;
public class OptimizeImportsAction extends AnAction {
private static final @NonNls String HELP_ID = "editing.manageImports";
private static final String NO_IMPORTS_OPTIMIZED = "No unused imports found";
private static boolean myProcessVcsChangedFilesInTests;
public OptimizeImportsAction() {
setEnabledInModalContext(true);
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
actionPerformedImpl(event.getDataContext());
}
public static void actionPerformedImpl(final DataContext dataContext) {
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
if (project == null) {
return;
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
final Editor editor = BaseCodeInsightAction.getInjectedEditor(project, CommonDataKeys.EDITOR.getData(dataContext));
final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
PsiFile file = null;
PsiDirectory dir;
if (editor != null){
file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (file == null) return;
dir = file.getContainingDirectory();
}
else if (files != null && ReformatCodeAction.containsOnlyFiles(files)) {
final ReadonlyStatusHandler.OperationStatus operationStatus = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(
Arrays.asList(files));
if (!operationStatus.hasReadonlyFiles()) {
new OptimizeImportsProcessor(project, ReformatCodeAction.convertToPsiFiles(files, project), null).run();
}
return;
}
else{
Project projectContext = PlatformDataKeys.PROJECT_CONTEXT.getData(dataContext);
Module moduleContext = LangDataKeys.MODULE_CONTEXT.getData(dataContext);
if (projectContext != null || moduleContext != null) {
final String text;
final boolean hasChanges;
if (moduleContext != null) {
text = CodeInsightBundle.message("process.scope.module", moduleContext.getName());
hasChanges = FormatChangedTextUtil.hasChanges(moduleContext);
}
else {
text = CodeInsightBundle.message("process.scope.project", projectContext.getPresentableUrl());
hasChanges = FormatChangedTextUtil.hasChanges(projectContext);
}
Boolean isProcessVcsChangedText = isProcessVcsChangedText(project, text, hasChanges);
if (isProcessVcsChangedText == null) {
return;
}
if (moduleContext != null) {
OptimizeImportsProcessor processor = new OptimizeImportsProcessor(project, moduleContext);
processor.setProcessChangedTextOnly(isProcessVcsChangedText);
processor.run();
}
else {
new OptimizeImportsProcessor(projectContext).run();
}
return;
}
PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
if (element == null) return;
if (element instanceof PsiDirectoryContainer) {
dir = ArrayUtil.getFirstElement(((PsiDirectoryContainer)element).getDirectories());
}
else if (element instanceof PsiDirectory) {
dir = (PsiDirectory)element;
}
else{
file = element.getContainingFile();
if (file == null) return;
dir = file.getContainingDirectory();
}
}
boolean processDirectory = false;
boolean processOnlyVcsChangedFiles = false;
if (!ApplicationManager.getApplication().isUnitTestMode() && file == null && dir != null) {
String message = CodeInsightBundle.message("process.scope.directory", dir.getName());
OptimizeImportsDialog dialog = new OptimizeImportsDialog(project, message, FormatChangedTextUtil.hasChanges(dir));
dialog.show();
if (!dialog.isOK()) {
return;
}
processDirectory = true;
processOnlyVcsChangedFiles = dialog.isProcessOnlyVcsChangedFiles();
}
if (processDirectory){
new OptimizeImportsProcessor(project, dir, true, processOnlyVcsChangedFiles).run();
}
else{
final OptimizeImportsProcessor optimizer = new OptimizeImportsProcessor(project, file);
if (editor != null && EditorSettingsExternalizable.getInstance().isShowNotificationAfterOptimizeImports()) {
optimizer.setCollectInfo(true);
optimizer.setPostRunnable(() -> {
LayoutCodeInfoCollector collector = optimizer.getInfoCollector();
if (collector != null) {
String info = collector.getOptimizeImportsNotification();
if (!editor.isDisposed() && editor.getComponent().isShowing()) {
String message = info != null ? info : NO_IMPORTS_OPTIMIZED;
FileInEditorProcessor.showHint(editor, StringUtil.capitalize(message), null);
}
}
});
}
optimizer.run();
}
}
@Override
public void update(@NotNull AnActionEvent event) {
if (!LanguageImportStatements.INSTANCE.hasAnyExtensions()) {
event.getPresentation().setVisible(false);
return;
}
Presentation presentation = event.getPresentation();
boolean available = isActionAvailable(event);
if (event.isFromContextMenu()) {
presentation.setEnabledAndVisible(available);
}
else {
presentation.setEnabled(available);
}
}
private static boolean isActionAvailable(@NotNull AnActionEvent event) {
DataContext dataContext = event.getDataContext();
Project project = CommonDataKeys.PROJECT.getData(dataContext);
if (project == null){
return false;
}
final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
final Editor editor = BaseCodeInsightAction.getInjectedEditor(project, CommonDataKeys.EDITOR.getData(dataContext), false);
if (editor != null){
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (file == null || !isOptimizeImportsAvailable(file)){
return false;
}
}
else if (files != null && ReformatCodeAction.containsOnlyFiles(files)) {
boolean anyHasOptimizeImports = false;
for (VirtualFile virtualFile : files) {
PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
if (file == null) {
return false;
}
if (isOptimizeImportsAvailable(file)) {
anyHasOptimizeImports = true;
break;
}
}
if (!anyHasOptimizeImports) {
return false;
}
}
else if (files != null && files.length == 1) {
// skip. Both directories and single files are supported.
}
else if (LangDataKeys.MODULE_CONTEXT.getData(dataContext) == null &&
PlatformDataKeys.PROJECT_CONTEXT.getData(dataContext) == null) {
PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
if (element == null){
return false;
}
if (!(element instanceof PsiDirectory)){
PsiFile file = element.getContainingFile();
if (file == null || !isOptimizeImportsAvailable(file)){
return false;
}
}
}
return true;
}
private static boolean isOptimizeImportsAvailable(final PsiFile file) {
return !LanguageImportStatements.INSTANCE.forFile(file).isEmpty();
}
private static Boolean isProcessVcsChangedText(Project project, String text, boolean hasChanges) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
return myProcessVcsChangedFilesInTests;
}
OptimizeImportsDialog dialog = new OptimizeImportsDialog(project, text, hasChanges);
if (!dialog.showAndGet()) {
return null;
}
return dialog.isProcessOnlyVcsChangedFiles();
}
@TestOnly
protected static void setProcessVcsChangedFilesInTests(boolean value) {
myProcessVcsChangedFilesInTests = value;
}
private static class OptimizeImportsDialog extends DialogWrapper {
private final boolean myContextHasChanges;
private final String myText;
private JCheckBox myOnlyVcsCheckBox;
private final LastRunReformatCodeOptionsProvider myLastRunOptions;
OptimizeImportsDialog(Project project, String text, boolean hasChanges) {
super(project, false);
myText = text;
myContextHasChanges = hasChanges;
myLastRunOptions = new LastRunReformatCodeOptionsProvider(PropertiesComponent.getInstance());
setOKButtonText(CodeInsightBundle.message("reformat.code.accept.button.text"));
setTitle(CodeInsightBundle.message("process.optimize.imports"));
init();
}
public boolean isProcessOnlyVcsChangedFiles() {
return myOnlyVcsCheckBox.isSelected();
}
@Nullable
@Override
protected JComponent createCenterPanel() {
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
panel.add(new JLabel(myText));
myOnlyVcsCheckBox = new JCheckBox(CodeInsightBundle.message("process.scope.changed.files"));
boolean lastRunVcsChangedTextEnabled = myLastRunOptions.getLastTextRangeType() == TextRangeType.VCS_CHANGED_TEXT;
myOnlyVcsCheckBox.setEnabled(myContextHasChanges);
myOnlyVcsCheckBox.setSelected(myContextHasChanges && lastRunVcsChangedTextEnabled);
myOnlyVcsCheckBox.setBorder(JBUI.Borders.emptyLeft(10));
panel.add(myOnlyVcsCheckBox);
return panel;
}
@Nullable
@Override
protected String getHelpId() {
return HELP_ID;
}
}
}
|
package com.intellij.ide.navigationToolbar.ui;
import com.intellij.icons.AllIcons;
import com.intellij.ide.navigationToolbar.NavBarItem;
import com.intellij.ide.navigationToolbar.NavBarPanel;
import com.intellij.ide.ui.UISettings;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import static com.intellij.ui.RelativeFont.SMALL;
/**
* @author Konstantin Bulenkov
*/
public abstract class AbstractNavBarUI implements NavBarUI {
private final static Map<NavBarItem, Map<ImageType, BufferedImage>> myCache = new THashMap<>();
private enum ImageType {
INACTIVE, NEXT_ACTIVE, ACTIVE, INACTIVE_FLOATING, NEXT_ACTIVE_FLOATING, ACTIVE_FLOATING,
INACTIVE_NO_TOOLBAR, NEXT_ACTIVE_NO_TOOLBAR, ACTIVE_NO_TOOLBAR
}
@Override
public Insets getElementIpad(boolean isPopupElement) {
return isPopupElement ? JBUI.insets(1, 2) : JBUI.emptyInsets();
}
@Override
public JBInsets getElementPadding() {
return JBUI.insets(3);
}
@Override
public Font getElementFont(NavBarItem navBarItem) {
Font font = UIUtil.getLabelFont();
return UISettings.getInstance().getUseSmallLabelsOnTabs() ? SMALL.derive(font) : font;
}
@Override
public Color getBackground(boolean selected, boolean focused) {
return selected && focused ? UIUtil.getListSelectionBackground() : UIUtil.getListBackground();
}
@Nullable
@Override
public Color getForeground(boolean selected, boolean focused, boolean inactive) {
return (selected && focused) ? UIUtil.getListSelectionForeground()
: inactive ? UIUtil.getInactiveTextColor() : null;
}
@Override
public short getSelectionAlpha() {
return 150;
}
@Override
public void doPaintNavBarItem(Graphics2D g, NavBarItem item, NavBarPanel navbar) {
final boolean floating = navbar.isInFloatingMode();
boolean toolbarVisible = UISettings.getInstance().getShowMainToolbar();
final boolean selected = item.isSelected() && item.isFocused();
boolean nextSelected = item.isNextSelected() && navbar.isFocused();
ImageType type;
if (floating) {
type = selected ? ImageType.ACTIVE_FLOATING : nextSelected ? ImageType.NEXT_ACTIVE_FLOATING : ImageType.INACTIVE_FLOATING;
} else {
if (toolbarVisible) {
type = selected ? ImageType.ACTIVE : nextSelected ? ImageType.NEXT_ACTIVE : ImageType.INACTIVE;
} else {
type = selected ? ImageType.ACTIVE_NO_TOOLBAR : nextSelected ? ImageType.NEXT_ACTIVE_NO_TOOLBAR : ImageType.INACTIVE_NO_TOOLBAR;
}
}
Map<ImageType, BufferedImage> cached = myCache.computeIfAbsent(item, k -> new HashMap<>());
BufferedImage image = cached.computeIfAbsent(type, k -> drawToBuffer(item, floating, toolbarVisible, selected, navbar));
UIUtil.drawImage(g, image, 0, 0, null);
Icon icon = item.getIcon();
final int offset = item.isFirstElement() ? getFirstElementLeftOffset() : 0;
final int iconOffset = getElementPadding().left + offset;
icon.paintIcon(item, g, iconOffset, (item.getHeight() - icon.getIconHeight()) / 2);
final int textOffset = icon.getIconWidth() + getElementPadding().width() + offset;
item.doPaintText(g, textOffset);
}
private static BufferedImage drawToBuffer(NavBarItem item, boolean floating, boolean toolbarVisible, boolean selected, NavBarPanel navbar) {
int w = item.getWidth();
int h = item.getHeight();
int offset = (w - getDecorationOffset());
int h2 = h / 2;
BufferedImage result = UIUtil.createImage(w, h, BufferedImage.TYPE_INT_ARGB);
Color defaultBg = UIUtil.isUnderDarcula() ? Gray._100 : JBColor.WHITE;
final Paint bg = floating ? defaultBg : null;
final Color selection = UIUtil.getListSelectionBackground();
Graphics2D g2 = result.createGraphics();
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Path2D.Double shape = new Path2D.Double();
shape.moveTo(0, 0);
shape.lineTo(offset, 0);
shape.lineTo(w, h2);
shape.lineTo(offset, h);
shape.lineTo(0, h);
shape.closePath();
Path2D.Double endShape = new Path2D.Double();
endShape.moveTo(offset, 0);
endShape.lineTo(w, 0);
endShape.lineTo(w, h);
endShape.lineTo(offset, h);
endShape.lineTo(w, h2);
endShape.closePath();
if (bg != null && toolbarVisible) {
g2.setPaint(bg);
g2.fill(shape);
g2.fill(endShape);
}
if (selected) {
Path2D.Double focusShape = new Path2D.Double();
if (toolbarVisible || floating) {
focusShape.moveTo(offset, 0);
} else {
focusShape.moveTo(0, 0);
focusShape.lineTo(offset, 0);
}
focusShape.lineTo(w - 1, h2);
focusShape.lineTo(offset, h - 1);
if (!toolbarVisible && !floating) {
focusShape.lineTo(0, h - 1);
}
g2.setColor(selection);
if (floating && item.isLastElement()) {
g2.fillRect(0, 0, w, h);
} else {
g2.fill(shape);
}
}
if (item.isNextSelected() && navbar.isFocused()) {
g2.setColor(selection);
g2.fill(endShape);
}
if (!item.isLastElement()) {
if (!selected && (!navbar.isFocused() | !item.isNextSelected())) {
Icon icon = AllIcons.Ide.NavBarSeparator;
icon.paintIcon(item, g2, w - icon.getIconWidth() - JBUI.scale(1), h2 - icon.getIconHeight() / 2);
}
}
g2.dispose();
return result;
}
private static int getDecorationOffset() {
return JBUI.scale(8);
}
private static int getFirstElementLeftOffset() {
return JBUI.scale(6);
}
@Override
public Dimension getOffsets(NavBarItem item) {
final Dimension size = new Dimension();
if (! item.isPopupElement()) {
size.width += getDecorationOffset() + getElementPadding().width() + (item.isFirstElement() ? getFirstElementLeftOffset() : 0);
size.height += getElementPadding().height();
}
return size;
}
@Override
public Insets getWrapperPanelInsets(Insets insets) {
final JBInsets result = JBUI.insets(insets);
if (shouldPaintWrapperPanel()) {
result.top += JBUI.scale(1);
}
return result;
}
private static boolean shouldPaintWrapperPanel() {
return false; //return !UISettings.getInstance().SHOW_MAIN_TOOLBAR && NavBarRootPaneExtension.runToolbarExists();
}
protected Color getBackgroundColor() {
return UIUtil.getSlightlyDarkerColor(UIUtil.getPanelBackground());
}
@Override
public void doPaintNavBarPanel(Graphics2D g, Rectangle r, boolean mainToolbarVisible, boolean undocked) {
g.setColor(getBackgroundColor());
if (mainToolbarVisible) {
g.fillRect(0, 0, r.width, r.height);
}
}
@Override
public void clearItems() {
myCache.clear();
}
@Override
public int getPopupOffset(@NotNull NavBarItem item) {
return item.isFirstElement() ? 0 : JBUI.scale(5);
}
}
|
package org.shokai.voicetweet;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.wearable.activity.ConfirmationActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.Wearable;
import java.util.List;
public class WearMainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<MessageApi.SendMessageResult> {
private String mTweet;
private ImageButton mButton;
private GoogleApiClient mGoogleApiClient;
public final String TAG = "WearMainActivity";
private final int CODE_RECOGNIZE_SPEECH = 567;
private final int CODE_CONFIRM_TWEET = 3;
public final String MESSAGE_PATH_TWEET = "/tweet/post";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (ImageButton) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSpeechRecognition();
}
});
startSpeechRecognition();
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
if (!mGoogleApiClient.isConnected()){
mGoogleApiClient.connect();
}
}
@Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
private void startSpeechRecognition(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, CODE_RECOGNIZE_SPEECH);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CODE_RECOGNIZE_SPEECH &&
resultCode == RESULT_OK){
List<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mTweet = results.get(0);
Intent confirmIntent = new Intent(this, WearTweetConfirmActivity.class);
confirmIntent.putExtra("tweet", mTweet);
startActivityForResult(confirmIntent, CODE_CONFIRM_TWEET);
}
if(requestCode == CODE_CONFIRM_TWEET
&& resultCode == RESULT_OK){
sendTweetAsync(mTweet);
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "GoogleApiClient Connected");
}
public void sendTweetAsync(String tweet){
if(tweet == null) return;
Log.i(TAG, "send \"" + tweet + "\" to handheld");
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String tweet = params[0];
byte[] bytes;
try {
bytes = tweet.getBytes("UTF-8");
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
return null;
}
for (Node node : Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await().getNodes()){
Log.v(TAG, "sending to node:" + node.getId());
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), MESSAGE_PATH_TWEET, bytes)
.setResultCallback(WearMainActivity.this);
}
return null;
}
}.execute(tweet);
}
@Override
public void onConnectionSuspended(int i) {
String msg = "GoogleApiClient connection suspended";
Log.i(TAG, msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
String msg = "GoogleApiClient connection failed" + result.toString();
Log.i(TAG, msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
finish();
}
/*
Result from Handheld
*/
@Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
Intent intent = new Intent(WearMainActivity.this, ConfirmationActivity.class);
if (sendMessageResult.getStatus().isSuccess()) {
Log.v(TAG, "success");
intent.putExtra(ConfirmationActivity.EXTRA_MESSAGE, "success");
intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.SUCCESS_ANIMATION);
}
else{
intent.putExtra(ConfirmationActivity.EXTRA_MESSAGE, "failed");
intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.FAILURE_ANIMATION);
}
startActivity(intent);
}
}
|
package com.github.pixelrunstudios.GdxTest;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
return new IOSApplication(new GdxTest(), config);
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
}
|
package com.kii.iotcloud;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Pair;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import com.google.gson.JsonParseException;
import com.kii.iotcloud.command.Action;
import com.kii.iotcloud.command.ActionResult;
import com.kii.iotcloud.command.Command;
import com.kii.iotcloud.exception.IoTCloudException;
import com.kii.iotcloud.exception.IoTCloudRestException;
import com.kii.iotcloud.exception.UnsupportedActionException;
import com.kii.iotcloud.exception.UnsupportedSchemaException;
import com.kii.iotcloud.http.IoTRestClient;
import com.kii.iotcloud.http.IoTRestRequest;
import com.kii.iotcloud.schema.Schema;
import com.kii.iotcloud.trigger.Predicate;
import com.kii.iotcloud.trigger.Trigger;
import com.kii.iotcloud.utils.JsonUtils;
import com.kii.iotcloud.utils.Path;
import com.squareup.okhttp.MediaType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class operates an IoT device that is specified by {@link #onBoard(String, String, String, JSONObject)} method.
*/
public class IoTCloudAPI implements Parcelable, Serializable {
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");
private static final MediaType MEDIA_TYPE_INSTALLATION_CREATION_REQUEST = MediaType.parse("application/vnd.kii.InstallationCreationRequest+json");
private static final MediaType MEDIA_TYPE_ONBOARDING_WITH_THING_ID_BY_OWNER_REQUEST = MediaType.parse("application/vnd.kii.OnboardingWithThingIDByOwner+json");
private static final MediaType MEDIA_TYPE_ONBOARDING_WITH_VENDOR_THING_ID_BY_OWNER_REQUEST = MediaType.parse("application/vnd.kii.OnboardingWithVendorThingIDByOwner+json");
private final String appID;
private final String appKey;
private final String baseUrl;
private final Owner owner;
private Target target;
private final Map<Pair<String, Integer>, Schema> schemas = new HashMap<Pair<String, Integer>, Schema>();
private final IoTRestClient restClient;
private String installationID;
IoTCloudAPI(
@NonNull String appID,
@NonNull String appKey,
@NonNull String baseUrl,
@NonNull Owner owner,
@NonNull List<Schema> schemas) {
// Parameters are checked by IoTCloudAPIBuilder
this.appID = appID;
this.appKey = appKey;
this.baseUrl = baseUrl;
this.owner = owner;
for (Schema schema : schemas) {
this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema);
}
this.restClient = new IoTRestClient();
}
@NonNull
@WorkerThread
public Target onBoard(
@NonNull String vendorThingID,
@NonNull String thingPassword,
@Nullable String thingType,
@Nullable JSONObject thingProperties)
throws IoTCloudException {
if (TextUtils.isEmpty(vendorThingID)) {
throw new IllegalArgumentException("vendorThingID is null or empty");
}
if (TextUtils.isEmpty(thingPassword)) {
throw new IllegalArgumentException("thingPassword is null or empty");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("vendorThingID", vendorThingID);
requestBody.put("thingPassword", thingPassword);
if (thingType != null) {
requestBody.put("thingType", thingType);
}
if (thingProperties != null && thingProperties.length() > 0) {
requestBody.put("thingProperties", thingProperties);
}
requestBody.put("owner", this.owner.getID().toString());
} catch (JSONException e) {
}
return this.onBoard(MEDIA_TYPE_ONBOARDING_WITH_VENDOR_THING_ID_BY_OWNER_REQUEST, requestBody);
}
/**
* On board IoT Cloud with the specified thing ID.
* When you are sure that the on boarding process has been done,
* this method is more convenient than
* {@link #onBoard(String, String, String, JSONObject)}.
* @param thingID Thing ID given by IoT Cloud. Must be specified.
* @param thingPassword Thing password given by vendor. Must be specified.
* @return Target instance can be used to operate target, manage resources
* of the target.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Target onBoard(
@NonNull String thingID,
@NonNull String thingPassword) throws
IoTCloudException {
if (TextUtils.isEmpty(thingID)) {
throw new IllegalArgumentException("thingID is null or empty");
}
if (TextUtils.isEmpty(thingPassword)) {
throw new IllegalArgumentException("thingPassword is null or empty");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("thingID", thingID);
requestBody.put("thingPassword", thingPassword);
requestBody.put("owner", this.owner.getID().toString());
} catch (JSONException e) {
}
return this.onBoard(MEDIA_TYPE_ONBOARDING_WITH_THING_ID_BY_OWNER_REQUEST, requestBody);
}
private Target onBoard(MediaType contentType, JSONObject requestBody) throws IoTCloudException {
String path = MessageFormat.format("/iot-api/apps/{0}/onboardings", this.appID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, contentType, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String thingID = responseBody.optString("thingID", null);
String accessToken = responseBody.optString("accessToken", null);
this.target = new Target(new TypedID(TypedID.Types.THING, thingID), accessToken);
return this.target;
}
/**
* Checks whether on boarding is done.
* @return true if done, otherwise false.
*/
public boolean onBoarded()
{
return this.target != null;
}
/**
* Install push notification to receive notification from IoT Cloud.
* IoT Cloud will send notification when the Target replies to the Command.
* Application can receive the notification and check the result of Command
* fired by Application or registered Trigger.
* After installation is done Installation ID is managed in this class.
* @param deviceToken for GCM, specify token obtained by
* InstanceID.getToken().
* for JPUSH, specify id obtained by
* JPushInterface.getUdid().
* @param pushBackend Specify backend to use.
* @return Installation ID used in IoT Cloud.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public String installPush(
@Nullable String deviceToken,
@NonNull PushBackend pushBackend
) throws IoTCloudException {
if (pushBackend == null) {
throw new IllegalArgumentException("pushBackend is null");
}
String path = MessageFormat.format("/api/apps/{0}/installations", this.appID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
try {
if (!TextUtils.isEmpty(deviceToken)) {
requestBody.put("installationRegistrationID", deviceToken);
}
requestBody.put("deviceType", pushBackend.getDeviceType());
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MEDIA_TYPE_INSTALLATION_CREATION_REQUEST, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
this.installationID = responseBody.optString("installationID", null);
return this.installationID;
}
/**
* Get installationID if the push is already installed.
* null will be returned if the push installation has not been done.
* @return Installation ID used in IoT Cloud.
*/
@Nullable
public String getInstallationID() {
return this.installationID;
}
/**
* Uninstall push notification.
* After done, notification from IoT Cloud won't be notified.
* @param installationID installation ID returned from
* {@link #installPush(String, PushBackend)}
* if null is specified, value obtained by
* {@link #getInstallationID()} is used.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public void uninstallPush(@NonNull String installationID) throws IoTCloudException {
if (installationID == null) {
throw new IllegalArgumentException("installationID is null");
}
String path = MessageFormat.format("/api/apps/{0}/installations/{1}", this.appID, installationID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers);
this.restClient.sendRequest(request);
}
/**
* Post new command to IoT Cloud.
* Command will be delivered to specified target and result will be notified
* through push notification.
* @param schemaName name of the schema.
* @param schemaVersion version of schema.
* @param actions Actions to be executed.
* @return Created Command instance. At this time, Command is delivered to
* the target Asynchronously and may not finished. Actual Result will be
* delivered through push notification or you can check the latest status
* of the command by calling {@link #getCommand}.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Command postNewCommand(
@NonNull String schemaName,
int schemaVersion,
@NonNull List<Action> actions) throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/commands", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
Command command = new Command(schemaName, schemaVersion, this.owner.getID(), actions);
JSONObject requestBody = JsonUtils.newJson(GsonRepository.gson(schema).toJson(command));
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String commandID = responseBody.optString("commandID", null);
return this.getCommand(commandID);
}
/**
* Get specified command.
* @param commandID ID of the command to obtain. ID is present in the
* instance returned by {@link #postNewCommand}
* and can be obtained by {@link Command#getCommandID}
*
* @return Command instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Command getCommand(
@NonNull String commandID)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(commandID)) {
throw new IllegalArgumentException("commandID is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/commands/{2}", this.appID, this.target.getID().toString(), commandID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
String schemaName = responseBody.optString("schema", null);
int schemaVersion = responseBody.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
return this.deserialize(schema, responseBody, Command.class);
}
/**
* List Commands in the specified Target.
* @param bestEffortLimit Maximum number of the Commands in the response.
* if the value is <= 0, default limit internally
* defined is applied.
* Meaning of 'bestEffort' is if the specified limit
* is greater than default limit, default limit is
* applied.
* @param paginationKey Used to get the next page of previously obtained.
* If there is further page to obtain, this method
* returns paginationKey as the 2nd element of pair.
* Applying this key to the argument results continue
* to get the result from the next page.
* @return 1st Element is Commands belongs to the Target. 2nd element is
* paginationKey if there is next page to be obtained.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
public Pair<List<Command>, String> listCommands (
int bestEffortLimit,
@Nullable String paginationKey)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/commands", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
if (bestEffortLimit > 0) {
request.addQueryParameter("bestEffortLimit", bestEffortLimit);
}
if (!TextUtils.isEmpty(paginationKey)) {
request.addQueryParameter("paginationKey", paginationKey);
}
JSONObject responseBody = this.restClient.sendRequest(request);
String nextPaginationKey = responseBody.optString("nextPaginationKey", null);
JSONArray commandArray = responseBody.optJSONArray("commands");
List<Command> commands = new ArrayList<Command>();
if (commandArray != null) {
for (int i = 0; i < commandArray.length(); i++) {
JSONObject commandJson = commandArray.optJSONObject(i);
String schemaName = commandJson.optString("schema", null);
int schemaVersion = commandJson.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
commands.add(this.deserialize(schema, commandJson, Command.class));
}
}
return new Pair<List<Command>, String>(commands, nextPaginationKey);
}
/**
* Post new Trigger to IoT Cloud.
* @param schemaName name of the schema.
* @param schemaVersion version of schema.
* @param actions Specify actions included in the Command is fired by the
* trigger.
* @param predicate Specify when the Trigger fires command.
* @return Instance of the Trigger registered in IoT Cloud.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger postNewTrigger(
@NonNull String schemaName,
int schemaVersion,
@NonNull List<Action> actions,
@NonNull Predicate predicate)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(schemaName)) {
throw new IllegalArgumentException("schemaName is null or empty");
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
Schema schema = this.getSchema(schemaName, schemaVersion);
Command command = new Command(schemaName, schemaVersion, this.target.getID(), this.owner.getID(), actions);
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson(schema).toJson(predicate)));
requestBody.put("command", JsonUtils.newJson(GsonRepository.gson(schema).toJson(command)));
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String triggerID = responseBody.optString("triggerID", null);
return this.getTrigger(triggerID);
}
/**
* Get specified Trigger.
* @param triggerID ID of the Trigger to get.
* @return Trigger instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Trigger getTrigger(
@NonNull String triggerID)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}", this.appID, this.target.getID().toString(), triggerID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
JSONObject commandObject = responseBody.optJSONObject("command");
String schemaName = commandObject.optString("schema", null);
int schemaVersion = commandObject.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
return this.deserialize(schema, responseBody, Trigger.class);
}
@NonNull
@WorkerThread
public Trigger patchTrigger(
@NonNull String triggerID,
@NonNull String schemaName,
int schemaVersion,
@Nullable List<Action> actions,
@Nullable Predicate predicate) throws
IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
if (TextUtils.isEmpty(schemaName)) {
throw new IllegalArgumentException("schemaName is null or empty");
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}", this.appID, this.target.getID().toString(), triggerID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
Schema schema = this.getSchema(schemaName, schemaVersion);
Command command = new Command(schemaName, schemaVersion, this.target.getID(), this.owner.getID(), actions);
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson(schema).toJson(predicate)));
requestBody.put("command", JsonUtils.newJson(GsonRepository.gson(schema).toJson(command)));
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PATCH, headers, MEDIA_TYPE_JSON, requestBody);
this.restClient.sendRequest(request);
return this.getTrigger(triggerID);
}
/**
* Enable/Disable registered Trigger
* If its already enabled(/disabled),
* this method won't throw Exception and behave as succeeded.
* @param triggerID ID of the Trigger to be enabled(/disabled).
* @param enable specify whether enable of disable the Trigger.
* @return Updated Trigger Instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger enableTrigger(
@NonNull String triggerID,
boolean enable)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}/{3}", this.appID, this.target.getID().toString(), triggerID, (enable ? "enable" : "disable"));
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers);
this.restClient.sendRequest(request);
return this.getTrigger(triggerID);
}
/**
* Delete the specified Trigger.
* @param triggerID ID of the Trigger to be deleted.
* @return Deleted Trigger Instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger deleteTrigger(
@NonNull String triggerID) throws
IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
Trigger trigger = this.getTrigger(triggerID);
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}", this.appID, target.getID().toString(), triggerID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers);
this.restClient.sendRequest(request);
return trigger;
}
/**
* List Triggers belongs to the specified Target.
* @param bestEffortLimit limit the maximum number of the Triggers in the
* Response. It ensures numbers in
* response is equals to or less than specified number.
* But doesn't ensures number of the Triggers
* in the response is equal to specified value.<br>
* If the specified value <= 0, Default size of the limit
* is applied by IoT Cloud.
* @param paginationKey If specified obtain rest of the items.
* @return first is list of the Triggers and second is paginationKey returned
* by IoT Cloud. paginationKey is null when there is next page to be obtained.
* Obtained paginationKey can be used to get the rest of the items stored
* in the target.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Pair<List<Trigger>, String> listTriggers(
int bestEffortLimit,
@Nullable String paginationKey) throws
IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
if (bestEffortLimit > 0) {
request.addQueryParameter("bestEffortLimit", bestEffortLimit);
}
if (!TextUtils.isEmpty(paginationKey)) {
request.addQueryParameter("paginationKey", paginationKey);
}
JSONObject responseBody = this.restClient.sendRequest(request);
String nextPaginationKey = responseBody.optString("nextPaginationKey", null);
JSONArray triggerArray = responseBody.optJSONArray("triggers");
List<Trigger> triggers = new ArrayList<Trigger>();
if (triggerArray != null) {
for (int i = 0; i < triggerArray.length(); i++) {
JSONObject triggerJson = triggerArray.optJSONObject(i);
JSONObject commandJson = triggerJson.optJSONObject("command");
String schemaName = commandJson.optString("schema", null);
int schemaVersion = commandJson.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
triggers.add(this.deserialize(schema, triggerJson, Trigger.class));
}
}
return new Pair<List<Trigger>, String>(triggers, nextPaginationKey);
}
/**
* Get the State of specified Target.
* State will be serialized with Gson library.
* @param classOfS Specify class of the State.
* @param <S> State class.
* @return Instance of Target State.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public <S extends TargetState> S getTargetState(
@NonNull Class<S> classOfS) throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (classOfS == null) {
throw new IllegalArgumentException("classOfS is null");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/states", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
S ret = GsonRepository.gson(null).fromJson(responseBody.toString(), classOfS);
return ret;
}
/**
* Get AppID
* @return
*/
public String getAppID() {
return this.appID;
}
/**
* Get AppKey
* @return
*/
public String getAppKey() {
return this.appKey;
}
/**
* Get base URL
* @return
*/
public String getBaseUrl() {
return this.baseUrl;
}
/**
*
* @return
*/
public List<Schema> getSchemas() {
return new ArrayList<Schema>(this.schemas.values());
}
/**
* Get owner who uses the IoTCloudAPI.
* @return
*/
public Owner getOwner() {
return this.owner;
}
public Target getTarget() {
return this.target;
}
public void setTarget() {
this.target = target;
}
private Schema getSchema(String schemaName, int schemaVersion) {
return this.schemas.get(new Pair<String, Integer>(schemaName, schemaVersion));
}
private Action generateAction(String schemaName, int schemaVersion, String actionName, JSONObject actionParameters) throws IoTCloudException {
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
Class<? extends Action> actionClass = schema.getActionClass(actionName);
if (actionClass == null) {
throw new UnsupportedActionException(schemaName, schemaVersion, actionName);
}
String json = actionParameters == null ? "{}" : actionParameters.toString();
return this.deserialize(schema, json, actionClass);
}
private ActionResult generateActionResult(String schemaName, int schemaVersion, String actionName, JSONObject actionResult) throws IoTCloudException {
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
Class<? extends ActionResult> actionResultClass = schema.getActionResultClass(actionName);
if (actionResultClass == null) {
throw new UnsupportedActionException(schemaName, schemaVersion, actionName);
}
String json = actionResult == null ? "{}" : actionResult.toString();
return this.deserialize(schema, json, actionResultClass);
}
private Map<String, String> newHeader() {
Map<String, String> headers = new HashMap<String, String>();
if (!TextUtils.isEmpty(this.appID)) {
headers.put("X-Kii-AppID", this.appID);
}
if (!TextUtils.isEmpty(this.appKey)) {
headers.put("X-Kii-AppKey", this.appKey);
}
if (this.owner != null && !TextUtils.isEmpty(this.owner.getAccessToken())) {
headers.put("Authorization", "Bearer " + this.owner.getAccessToken());
}
return headers;
}
private <T> T deserialize(Schema schema, JSONObject json, Class<T> clazz) throws IoTCloudException {
return this.deserialize(schema, json.toString(), clazz);
}
private <T> T deserialize(Schema schema, String json, Class<T> clazz) throws IoTCloudException {
try {
return GsonRepository.gson(schema).fromJson(json, clazz);
} catch (JsonParseException e) {
if (e.getCause() instanceof IoTCloudException) {
throw (IoTCloudException)e.getCause();
}
throw e;
}
}
// Implementation of Parcelable
protected IoTCloudAPI(Parcel in) {
this.appID = in.readString();
this.appKey = in.readString();
this.baseUrl = in.readString();
this.owner = in.readParcelable(Owner.class.getClassLoader());
this.target = in.readParcelable(Target.class.getClassLoader());
ArrayList<Schema> schemas = in.createTypedArrayList(Schema.CREATOR);
for (Schema schema : schemas) {
this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema);
}
this.restClient = new IoTRestClient();
this.installationID = in.readString();
}
public static final Creator<IoTCloudAPI> CREATOR = new Creator<IoTCloudAPI>() {
@Override
public IoTCloudAPI createFromParcel(Parcel in) {
return new IoTCloudAPI(in);
}
@Override
public IoTCloudAPI[] newArray(int size) {
return new IoTCloudAPI[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.appID);
dest.writeString(this.appKey);
dest.writeString(this.baseUrl);
dest.writeParcelable(this.owner, flags);
dest.writeParcelable(this.target, flags);
dest.writeTypedList(new ArrayList<Schema>(this.schemas.values()));
dest.writeString(this.installationID);
}
}
|
package org.javarosa.j2me.file;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import org.javarosa.core.reference.Reference;
/**
* A J2ME File reference is a reference type which refers to a
* FileConnection on a j2me phone. It is assumed that the
* file reference is provided with a local file root
* which is valid on the device (For which helper utilities
* can be found in the J2meFileSystemProperties definition).
*
* Note: J2ME File Connections must be managed carefully
* (Multiple connections to a single file cannot exist),
* and this object cannot guarantee (yet) thread safety
* on access to a single connection.
*
* TODO: This still needs to be rewritten in a way that is consistent
* as to how we'll be accessing all of this data
*
* @author ctsims
*
*/
public class J2meFileReference implements Reference
{
//We really shouldn't need a lot of these
private static final int MAX_CONNECTIONS = 5;
private static Hashtable<String, FileConnection> connections = new Hashtable<String, FileConnection>();
//Queue for existing connections to allow for good caching
private static Vector<String> connectionList = new Vector<String>();
String localPart;
String referencePart;
/**
* Creates a J2ME file reference of the format
*
* "jr://file"+referencePart"
*
* which refers to the URI
*
* "file:///" + localPart + referencePart
*
* @param localPart
* @param referencePart
*/
public J2meFileReference(String localPart, String referencePart) {
this.localPart = localPart;
this.referencePart = referencePart;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.reference.Reference#getStream()
*/
public boolean doesBinaryExist() throws IOException {
//We do this a lot for many different things,
//no need to cache purely based on this
FileConnection connect = connector(false);
boolean exists = connect.exists();
synchronized (connections) {
//If this isn't cached (we didn't request that it should be),
//close the connection, otherwise leave it be
if(!isCached()) {
connect.close();
}
}
return exists;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.reference.Reference#getStream()
*/
public InputStream getStream() throws IOException {
InputStream stream = connector().openInputStream();
clearReferenceConnection(this.getLocalURI());
return stream;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.reference.Reference#getURI()
*/
public String getURI() {
return "jr://file" + referencePart;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.reference.Reference#isReadOnly()
*/
public boolean isReadOnly() {
try {
return !connector().canWrite();
} catch (IOException e) {
//Hmmmmm... not sure what to do about this exactly
e.printStackTrace();
return true;
} catch (SecurityException se) {
//Definitely can't write in this case.
return true;
}
}
/*
* (non-Javadoc)
* @see org.javarosa.core.reference.Reference#getOutputStream()
*/
public OutputStream getOutputStream() throws IOException {
FileConnection connector = connector();
if(!connector.exists()) {
connector.create();
if(!connector.exists()) {
throw new IOException("File still doesn't exist at " + this.getLocalURI() + " after create worked succesfully. Reference is probably incorrect");
}
} else {
//TODO: Delete exist file, maybe? Probably....
}
OutputStream os = connector.openOutputStream();
clearReferenceConnection(getLocalURI());
return os;
}
protected FileConnection connector() throws IOException {
return connector(true);
}
protected FileConnection connector(boolean cache) throws IOException {
return connector(getLocalURI(), cache);
}
protected FileConnection connector(String uri, boolean cache) throws IOException {
synchronized (connections) {
// We only want to allow one connection to a file at a time.
// Otherwise we can get into trouble when we want to remove it.
if (connections.containsKey(uri)) {
return connections.get(uri);
} else {
FileConnection connection = (FileConnection) Connector.open(uri);
if(cache) {
//These connections aren't cheap, we can't afford to keep all that many around
if(connectionList.size() == MAX_CONNECTIONS) {
//FIFO, make room for one more
clearReferenceConnection(connectionList.elementAt(0));
}
// Store the newly opened connection for reuse.
connections.put(uri, connection);
//Add it to the end of the queue for management
connectionList.addElement(uri);
}
return connection;
}
}
}
private boolean isCached() {
synchronized (connections) {
return connections.containsKey(getLocalURI());
}
}
private void clearReferenceConnection(String ref) {
synchronized(connectionList) {
try {
connections.get(ref).close();
} catch (IOException e) {
e.printStackTrace();
}
connectionList.removeElement(ref);
connections.remove(ref);
}
}
/*
* (non-Javadoc)
* @see org.javarosa.core.reference.Reference#remove()
*/
public void remove() throws IOException {
FileConnection con = connector();
//TODO: this really needs to be written better, but
//for now avoiding deadlock is better than ensuring
//thread safety
//Take a lock on the connection so that nothing tries
//to access it while this happens
synchronized(con) {
con.delete();
con.close();
}
//Take a lock on the connections so that
//nothing can retrieve the connection
synchronized(connections) {
//Remove the local connection now that it's
//closed.
clearReferenceConnection(getLocalURI());
}
}
/*
* (non-Javadoc)
* @see org.javarosa.core.reference.Reference#getLocalURI()
*/
public String getLocalURI() {
return "file:///" + localPart + referencePart;
}
public Reference[] probeAlternativeReferences() {
//showtime
String local = this.getLocalURI();
String folder = local.substring(0,local.lastIndexOf('/') + 1);
String folderPart = folder.substring(("file:///" + localPart).length(),folder.length());
int finalIndex = local.length();
if(local.lastIndexOf('.') != -1 && local.lastIndexOf('/') < local.lastIndexOf('.')) {
finalIndex = local.lastIndexOf('.');
}
String fileNoExt = local.substring(local.lastIndexOf('/') + 1, finalIndex);
try {
Vector<Reference> results = new Vector<Reference>();
for(Enumeration en = connector(folder, false).list(fileNoExt + ".*", true) ; en.hasMoreElements() ; ) {
String file = (String)en.nextElement();
String referencePart = folderPart + file;
if(!referencePart.equals(this.referencePart)) {
results.addElement(new J2meFileReference(localPart, referencePart));
}
}
Reference[] refs = new Reference[results.size()];
for(int i = 0 ; i < refs.length ; ++i) {
refs[i] = results.elementAt(i);
}
return refs;
} catch (IOException e) {
return new Reference[0];
}
}
/**
* Cleanup task in case it becomes necessary. Not sure yet if it will
*/
public static void clearConnectionCache() {
synchronized(connections) {
connections.clear();
connectionList.removeAllElements();
}
}
}
|
package sample.javafx;
import javafx.fxml.FXML;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
public class MainController {
private Stage stage;
@FXML
public void openFileDialog() {
FileChooser chooser = new FileChooser();
File file = chooser.showSaveDialog(this.stage);
System.out.println("file=" + file);
}
public void setStage(Stage stage) {
this.stage = stage;
}
}
|
package org.broadinstitute.sting.gatk;
import org.broadinstitute.sting.gatk.walkers.Walker;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.cmdLine.Argument;
import org.broadinstitute.sting.utils.cmdLine.ArgumentCollection;
import org.broadinstitute.sting.utils.cmdLine.CommandLineProgram;
/**
* @author aaron
* @version 1.0
* @date May 8, 2009
* <p/>
* Class CommandLineGATK
* <p/>
* We run command line GATK programs using this class. It gets the command line args, parses them, and hands the
* gatk all the parsed out information. Pretty much anything dealing with the underlying system should go here,
* the gatk engine should deal with any data related information.
*/
public class CommandLineGATK extends CommandLineProgram {
@Argument(fullName = "analysis_type", shortName = "T", doc = "Type of analysis to run")
public String analysisName = null;
@ArgumentCollection // our argument collection, the collection of command line args we accept
public GATKArgumentCollection argCollection = new GATKArgumentCollection();
public String pluginPathName = null;
// our genome analysis engine
GenomeAnalysisEngine GATKEngine = null;
// our walker manager
private WalkerManager walkerManager = null;
/** Required main method implementation. */
public static void main(String[] argv) {
try {
CommandLineGATK instance = new CommandLineGATK();
start(instance, argv);
} catch (Exception e) {
exitSystemWithError(e);
}
}
/**
* this is the function that the inheriting class can expect to have called
* when the command line system has initialized.
*
* @return the return code to exit the program with
*/
protected int execute() {
Walker<?, ?> mWalker = null;
try {
mWalker = walkerManager.createWalkerByName(analysisName);
} catch (InstantiationException ex) {
throw new RuntimeException("Unable to instantiate walker.", ex);
}
catch (IllegalAccessException ex) {
throw new RuntimeException("Unable to access walker", ex);
}
loadArgumentsIntoObject(argCollection);
loadArgumentsIntoObject(mWalker);
this.argCollection.analysisName = this.analysisName;
try {
GATKEngine = new GenomeAnalysisEngine(argCollection, mWalker);
} catch (StingException exp) {
System.err.println("Caught StingException. It's message is " + exp.getMessage());
exp.printStackTrace();
return -1;
}
return 0;
}
/**
* GATK can add arguments dynamically based on analysis type.
*
* @return true
*/
@Override
protected boolean canAddArgumentsDynamically() {
return true;
}
/**
* GATK provides the walker as an argument source. As a side-effect, initializes the walker variable.
*
* @return List of walkers to load dynamically.
*/
@Override
protected Class[] getArgumentSources() {
if (analysisName == null)
throw new IllegalArgumentException("Must provide analysis name");
walkerManager = new WalkerManager(pluginPathName);
if (!walkerManager.doesWalkerExist(analysisName))
throw new IllegalArgumentException("Invalid analysis name");
return new Class[]{walkerManager.getWalkerClassByName(analysisName)};
}
@Override
protected String getArgumentSourceName(Class argumentSource) {
return WalkerManager.getWalkerName((Class<Walker>) argumentSource);
}
public GATKArgumentCollection getArgCollection() {
return argCollection;
}
public void setArgCollection(GATKArgumentCollection argCollection) {
this.argCollection = argCollection;
}
}
|
package org.ccnx.ccn.test.endtoend;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentObject;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* Part of the end to end test infrastructure.
* NOTE: This test requires ccnd to be running and complementary source process
*/
public class BaseLibrarySink {
static CCNHandle handle = null;
Semaphore sema = new Semaphore(0);
int next = 0;
protected static Throwable error = null; // for errors in callback
@BeforeClass
public static void setUpBeforeClass() throws Exception {
handle = CCNHandle.open();
// Set debug level: use for more FINE, FINER, FINEST for debug-level tracing
Log.setDefaultLevel(Level.FINEST);
}
@AfterClass
public static void tearDownAfterClass() {
handle.close();
}
/**
* Subclassible object processing operations, to make it possible to easily
* implement tests based on this one.
* @author smetters
*
*/
public void checkGetResults(ContentObject getResults) {
Log.info("Got result: " + getResults.name());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.