answer
stringlengths 17
10.2M
|
|---|
package com.spaceproject.systems;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.EntitySystem;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.utils.ImmutableArray;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.spaceproject.components.CannonComponent;
import com.spaceproject.components.HealthComponent;
import com.spaceproject.components.MapComponent;
import com.spaceproject.components.PlayerFocusComponent;
import com.spaceproject.components.TransformComponent;
import com.spaceproject.utility.Mappers;
import com.spaceproject.utility.MyMath;
public class HUDSystem extends EntitySystem {
//rendering
private Matrix4 projectionMatrix = new Matrix4();
private ShapeRenderer shape = new ShapeRenderer();
//entity storage
private ImmutableArray<Entity> mapableObjects;
private ImmutableArray<Entity> player;
private ImmutableArray<Entity> killables;
private boolean drawHud = true;
private boolean drawMap = true; //draw edge map
@Override
public void addedToEngine(Engine engine) {
mapableObjects = engine.getEntitiesFor(Family.all(MapComponent.class, TransformComponent.class).get());
player = engine.getEntitiesFor(Family.one(PlayerFocusComponent.class).get());
killables = engine.getEntitiesFor(Family.all(HealthComponent.class, TransformComponent.class).get());
}
@Override
public void update(float delta) {
if (Gdx.input.isKeyJustPressed(Keys.H)) {
drawHud = !drawHud;
System.out.println("HUD: " + drawHud);
}
if (Gdx.input.isKeyJustPressed(Keys.M)) {
drawMap = !drawMap;
System.out.println("Edge map: " + drawMap);
}
if (!drawHud) return;
//set projection matrix so things render using correct coordinates
//TODO: only needs to be called when screen size changes
projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
shape.setProjectionMatrix(projectionMatrix);
//enable transparency
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
shape.begin(ShapeType.Filled);
drawAmmo();
if (drawMap) drawEdgeMap();
drawHealthBars();
shape.end();
Gdx.gl.glDisable(GL20.GL_BLEND);
}
/**
* Draw health bars on entities.
*/
private void drawHealthBars() {
int playerBarLength = 120;
int playerBarX = Gdx.graphics.getWidth()/2 - playerBarLength/2;
int playerBarY = 55;
//bar dimensions
int barLength = 40;
int barWidth = 8;
int yOffset = -20; //position from entity
Color barBackground = new Color(1,1,1,0.5f);
for (Entity entity : killables) {
Vector3 pos = RenderingSystem.getCam().project(Mappers.transform.get(entity).pos.cpy());
HealthComponent health = Mappers.health.get(entity);
//player bar
if (entity.equals(player.first())) {
shape.setColor(barBackground);
shape.rect(playerBarX, playerBarY, playerBarLength, barWidth);
float ratio = health.health/health.maxHealth;
shape.setColor(new Color(1 - ratio, ratio, 0, 0.7f));
shape.rect(playerBarX, playerBarY, playerBarLength * ratio, barWidth);
continue;
}
//ignore full health
if (health.health == health.maxHealth) {
continue;
}
//background
shape.setColor(barBackground);
shape.rect(pos.x-barLength/2, pos.y+yOffset, barLength, barWidth);
//health
float ratio = health.health/health.maxHealth;
shape.setColor(new Color(1 - ratio, ratio, 0, 0.7f));
shape.rect(pos.x-barLength/2, pos.y+yOffset, barLength * ratio, barWidth);
}
}
/**
* Draw the Ammo bar.
*/
private void drawAmmo() {
CannonComponent cannon = Mappers.cannon.get(player.first());
if (cannon == null) {
return;
}
Color bar = new Color(1, 1, 1, 0.4f);
Color on = new Color(0.15f, 0.5f, 0.9f, 0.9f);
Color off = new Color(0f, 0f, 0f, 0.6f);
int posY = 30; //pixels from bottom off screen
int posX = Gdx.graphics.getWidth() / 2;
int border = 5; //width of border on background bar
int padding = 4; //space between indicators
int indicatorSize = 15;
int barWidth = cannon.maxAmmo * (indicatorSize + (padding * 2));
//draw bar
shape.setColor(bar);
shape.rect(posX-barWidth/2+padding-border, posY-border, posX, (barWidth/2) + (border*2), (barWidth-padding*2) + (border*2), indicatorSize + (border*2), 1, 1, 0);
//draw indicators
for (int i = 0; i < cannon.maxAmmo; ++i) {
//Z = A * (B + (C * 2)) + X - ((D * (B + C * 2))/2) + C
//TODO: It works, but can this be simplified?
shape.setColor(cannon.curAmmo <= i ? off : on);
shape.rect((i * (indicatorSize + (padding * 2))) + posX - (barWidth/2) + padding, posY, indicatorSize/2, indicatorSize/2, indicatorSize, indicatorSize, 1, 1, 0);
}
}
/**
* Mark off-screen objects on edge of screen for navigation.
*/
private void drawEdgeMap() {
float markerSmall = 3.5f; //min marker size
float markerLarge = 8; //max marker size
float distSmall = 8000; //distance when marker is small
float distLarge = 2000; //distance when marker is large
//gain and offset for transfer function: map [3.5 - 8] to [8000 - 2000]
double gain = (markerSmall-markerLarge)/(distSmall-distLarge);
double offset = markerSmall - gain * distSmall;
int padding = 12; //how close to draw from edge of screen (in pixels)
int width = Gdx.graphics.getWidth();
int height = Gdx.graphics.getHeight();
int centerX = width/2;
int centerY = height/2;
int verticleEdge = (height - padding * 2) / 2;
int horizontalEdge = (width - padding * 2) / 2;
for (Entity mapable : mapableObjects) {
MapComponent map = Mappers.map.get(mapable);
Vector3 screenPos = Mappers.transform.get(mapable).pos.cpy();
if (MyMath.distance(RenderingSystem.getCam().position.x, RenderingSystem.getCam().position.y,
screenPos.x, screenPos.y) > map.distance) {
continue;
}
//set entity co'ords relative to center of screen
screenPos.x -= RenderingSystem.getCam().position.x;
screenPos.y -= RenderingSystem.getCam().position.y;
//skip on screen entities
int z = 100; //how close to edge of screen to ignore
if (screenPos.x + z > -centerX && screenPos.x - z < centerX && screenPos.y + z > -centerY && screenPos.y - z < centerY) {
continue;
}
//position to draw marker
float markerX = 0, markerY = 0;
//calculate slope of line (y = mx+b)
float slope = screenPos.y / screenPos.x;
//calculate where to position the marker
if (screenPos.y < 0) {
//top
markerX = -verticleEdge/slope;
markerY = -verticleEdge;
} else {
//bottom
markerX = verticleEdge/slope;
markerY = verticleEdge;
}
if (markerX < -horizontalEdge) {
//left
markerX = -horizontalEdge;
markerY = slope * -horizontalEdge;
} else if (markerX > horizontalEdge) {
//right
markerX = horizontalEdge;
markerY = slope * horizontalEdge;
}
//set co'ords relative to center screen
markerX += centerX;
markerY += centerY;
//calculate size of marker based on distance
float dist = MyMath.distance(screenPos.x, screenPos.y, centerX, centerY);
double size = gain * dist + offset;
if (size < markerSmall) size = markerSmall;
if (size > markerLarge) size = markerLarge;
//draw marker
shape.setColor(map.color);
shape.circle(markerX, markerY, (float)size);
}
/*
//I'm not sure how to make this look pretty or if borders should be added...
//Maybe research some UI design.
//draw borders
Color outer = new Color(0.6f, 1, 0.7f, 0.3f);
Color inner = new Color(1, 1, 1, 0.2f);
//left
shape.rect(0, 0, padding*2, height, outer, inner, inner, outer);
shape.line(padding*2, 0, padding*2, height);
//right
shape.rect(width - padding*2, 0, padding*2, height, inner, outer, outer, inner);
//bottom
shape.rect(0, 0, width, padding*2, outer, outer, inner, inner);
//top
shape.rect(0, height - padding*2, width, padding*2, inner, inner, outer, outer);
*/
}
}
|
package arez.annotations;
import arez.ComputableValue;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import javax.annotation.Nonnull;
@Documented
@Target( ElementType.METHOD )
public @interface Memoize
{
/**
* Return the root name of the element value relative to the component.
* If the method has parameters then the name will be used in combination with a sequence
* when naming the synthesized {@link ComputableValue} instances. The value must conform to
* the requirements of a java identifier. The name must also be unique across {@link Observable}s,
* {@link Memoize}s and {@link Action}s within the scope of the {@link ArezComponent} annotated element.
*
* @return the root name of the element relative to the component.
*/
@Nonnull
String name() default "<default>";
/**
* A flag indicating whether the computable should be "kept alive". A computable that is kept alive
* is activated on creation and never deactivates. This is useful if the computable property is only
* accessed from within actions but should be kept up to date and not recomputed on each access.
* This MUST not be set if the target method has any parameters as can not keep computed value active
* if parameter values are unknown.
*
* @return true to keep computable alive.
*/
boolean keepAlive() default false;
/**
* The priority of the underlying ComputableValue observer
*
* @return the priority of the ComputableValue observer.
*/
Priority priority() default Priority.NORMAL;
/**
* Flag controlling whether the underlying observer can observe ComputableValue instances with lower priorities.
* The default value of false will result in an invariant failure (in development mode) if a lower priority
* dependency is observed by the observer. This is to prevent priority inversion when scheduling a higher
* priority observer is dependent upon a lower priority computable value. If the value is true then the no
* invariant failure is triggered and the component relies on the component author to handle possible priority
* inversion.
*
* @return false if observing lower priority dependencies should result in invariant failure in development mode.
*/
boolean observeLowerPriorityDependencies() default false;
/**
* Enum indicating whether the value of the computable is derived from arez elements and/or external dependencies.
* If set to {@link DepType#AREZ} then Arez will verify that the method annotated by this annotation accesses arez
* elements (i.e. instances of {@link arez.ObservableValue} or instances of {@link ComputableValue}). If set to
* {@link DepType#AREZ_OR_NONE} then the runtime will allow computable to exist with no dependencies. If set
* to {@link DepType#AREZ_OR_EXTERNAL} then the component must define a {@link ComputableValueRef} method and should invoke
* {@link ComputableValue#reportPossiblyChanged()} when the non-arez dependencies are changed.
*
* @return the types of dependencies allowed on the computable.
*/
@Nonnull
DepType depType() default DepType.AREZ;
/**
* Return true if the return value of the memoized value should be reported to the Arez spy subsystem.
* It is useful to disable reporting for large, circular or just uninteresting parameters to the spy infrastructure.
*
* @return true to report the return value, false otherwise.
*/
boolean reportResult() default true;
}
|
package trikita.anvil;
public interface Renderable {
void view();
}
|
package com.android.deskclock;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.android.deskclock.timer.TimerView;
import java.util.ArrayList;
/**
* TODO: Insert description here. (generated by isaackatz)
*/
public class StopwatchFragment extends DeskClockFragment {
// Stopwatch states
private static final int STOPWATCH_RESET = 0;
private static final int STOPWATCH_RUNNING = 1;
private static final int STOPWATCH_STOPPED = 2;
private static final int MAX_LAPS = 99;
int mState = STOPWATCH_RESET;
// Stopwatch views that are accessed by the activity
Button mLeftButton, mRightButton;
CircleTimerView mTime;
TimerView mTimeText;
View mLapsTitle;
ListView mLapsList;
Button mShareButton;
View mButtonSeperator;
// Used for calculating the time from the start taking into account the pause times
long mStartTime = 0;
long mAccumulatedTime = 0;
// Lap information
class Lap {
Lap () {
mLapTime = 0;
mTotalTime = 0;
}
Lap (long time, long total) {
mLapTime = time;
mTotalTime = total;
}
public long mLapTime;
public long mTotalTime;
}
// Adapter for the ListView that shows the lap times.
class LapsListAdapter extends BaseAdapter {
Context mContext;
ArrayList<Lap> mLaps = new ArrayList<Lap>();
private final LayoutInflater mInflater;
public LapsListAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (mLaps.size() == 0 || position >= mLaps.size()) {
return null;
}
View lapInfo;
if (convertView != null) {
lapInfo = convertView;
} else {
lapInfo = mInflater.inflate(R.layout.lap_view, parent, false);
}
TextView count = (TextView)lapInfo.findViewById(R.id.lap_number);
TextView lapTime = (TextView)lapInfo.findViewById(R.id.lap_time);
TextView toalTime = (TextView)lapInfo.findViewById(R.id.lap_total);
lapTime.setText(getTimeText(mLaps.get(position).mLapTime));
toalTime.setText(getTimeText(mLaps.get(position).mTotalTime));
count.setText(getString(R.string.sw_current_lap_number, mLaps.size() - position));
return lapInfo;
}
@Override
public int getCount() {
return mLaps.size();
}
@Override
public Object getItem(int position) {
if (mLaps.size() == 0 || position >= mLaps.size()) {
return null;
}
return mLaps.get(position);
}
public void addLap(Lap l) {
mLaps.add(0, l);
notifyDataSetChanged();
}
public void clearLaps() {
mLaps.clear();
notifyDataSetChanged();
}
// Helper function used to get the lap data to be stored in the activitys's bundle
public long [] getLapTimes() {
int size = mLaps.size();
if (size == 0) {
return null;
}
long [] laps = new long[size];
for (int i = 0; i < size; i ++) {
laps[i] = mLaps.get(i).mLapTime;
}
return laps;
}
// Helper function to restore adapter's data from the activity's bundle
public void setLapTimes(long [] laps) {
if (laps == null || laps.length == 0) {
return;
}
int size = laps.length;
mLaps.clear();
for (int i = 0; i < size; i ++) {
mLaps.add(new Lap (laps[i], 0));
}
long totalTime = 0;
for (int i = size -1; i >= 0; i
totalTime += laps[i];
mLaps.get(i).mTotalTime = totalTime;
}
notifyDataSetChanged();
}
}
// Keys for data stored in the activity's bundle
private static final String START_TIME_KEY = "start_time";
private static final String ACCUM_TIME_KEY = "accum_time";
private static final String STATE_KEY = "state";
private static final String LAPS_KEY = "laps";
LapsListAdapter mLapsAdapter;
public StopwatchFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.stopwatch_fragment, container, false);
mLeftButton = (Button)v.findViewById(R.id.stopwatch_left_button);
mLeftButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonClicked(true);
switch (mState) {
case STOPWATCH_RUNNING:
// Save lap time
addLapTime(System.currentTimeMillis()/10);
showLaps();
setButtons(STOPWATCH_RUNNING);
break;
case STOPWATCH_STOPPED:
// do reset
mAccumulatedTime = 0;
mLapsAdapter.clearLaps();
showLaps();
mTime.stopIntervalAnimation();
mTime.reset();
mTimeText.setTime(mAccumulatedTime);
mTimeText.blinkTimeStr(false);
setButtons(STOPWATCH_RESET);
mState = STOPWATCH_RESET;
break;
default:
Log.wtf("Illegal state " + mState
+ " while pressing the left stopwatch button");
break;
}
}
});
mRightButton = (Button)v.findViewById(R.id.stopwatch_right_button);
mRightButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonClicked(true);
switch (mState) {
case STOPWATCH_RUNNING:
// do stop
stopUpdateThread();
mTime.pauseIntervalAnimation();
long curTime = System.currentTimeMillis()/10;
mAccumulatedTime += (curTime - mStartTime);
mTimeText.setTime(mAccumulatedTime);
mTimeText.blinkTimeStr(true);
updateCurrentLap(curTime, mAccumulatedTime);
setButtons(STOPWATCH_STOPPED);
mState = STOPWATCH_STOPPED;
break;
case STOPWATCH_RESET:
case STOPWATCH_STOPPED:
// do start
mStartTime = System.currentTimeMillis()/10;
startUpdateThread();
mTimeText.blinkTimeStr(false);
if (mTime.isAnimating()) {
mTime.startIntervalAnimation();
}
setButtons(STOPWATCH_RUNNING);
mState = STOPWATCH_RUNNING;
break;
default:
Log.wtf("Illegal state " + mState
+ " while pressing the right stopwatch button");
break;
}
}
});
mShareButton = (Button)v.findViewById(R.id.stopwatch_share_button);
mButtonSeperator = v.findViewById(R.id.stopwatch_button_seperator);
mShareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide what to
// do with it.
intent.putExtra(Intent.EXTRA_SUBJECT,
getActivity().getResources().getString(R.string.sw_share_title));
intent.putExtra(Intent.EXTRA_TEXT, buildShareResults());
startActivity(Intent.createChooser(intent, null));
}
});
mTime = (CircleTimerView)v.findViewById(R.id.stopwatch_time);
mTimeText = (TimerView)v.findViewById(R.id.stopwatch_time_text);
mLapsTitle = v.findViewById(R.id.laps_title);
mLapsList = (ListView)v.findViewById(R.id.laps_list);
mLapsList.setDividerHeight(0);
mLapsAdapter = new LapsListAdapter(getActivity());
if (mLapsList != null) {
mLapsList.setAdapter(mLapsAdapter);
}
if (savedInstanceState != null) {
mState = savedInstanceState.getInt(STATE_KEY, STOPWATCH_RESET);
mStartTime = savedInstanceState.getLong(START_TIME_KEY, 0);
mAccumulatedTime = savedInstanceState.getLong(ACCUM_TIME_KEY, 0);
mLapsAdapter.setLapTimes(savedInstanceState.getLongArray(LAPS_KEY));
}
return v;
}
@Override
public void onResume() {
setButtons(mState);
mTimeText.setTime(mAccumulatedTime);
if (mState == STOPWATCH_RUNNING) {
startUpdateThread();
}
showLaps();
super.onResume();
}
@Override
public void onPause() {
if (mState == STOPWATCH_RUNNING) {
stopUpdateThread();
}
super.onPause();
}
@Override
public void onSaveInstanceState (Bundle outState) {
outState.putInt(STATE_KEY, mState);
outState.putLong(START_TIME_KEY, mStartTime);
outState.putLong(ACCUM_TIME_KEY, mAccumulatedTime);
if (mLapsAdapter != null) {
long [] laps = mLapsAdapter.getLapTimes();
if (laps != null) {
outState.putLongArray(LAPS_KEY, laps);
}
}
super.onSaveInstanceState(outState);
}
private void showShareButton(boolean show) {
if (mShareButton != null) {
mShareButton.setVisibility(show ? View.VISIBLE : View.GONE);
mButtonSeperator.setVisibility(show ? View.VISIBLE : View.GONE);
mShareButton.setEnabled(show);
}
}
/***
* Update the buttons on the stopwatch according to the watch's state
*/
private void setButtons(int state) {
switch (state) {
case STOPWATCH_RESET:
setButton(mLeftButton, R.string.sw_lap_button, false, View.INVISIBLE);
setButton(mRightButton, R.string.sw_start_button, true, View.VISIBLE);
showShareButton(false);
break;
case STOPWATCH_RUNNING:
setButton(mLeftButton, R.string.sw_lap_button, !reachedMaxLaps(), View.VISIBLE);
setButton(mRightButton, R.string.sw_stop_button, true, View.VISIBLE);
showShareButton(false);
break;
case STOPWATCH_STOPPED:
setButton(mLeftButton, R.string.sw_reset_button, true, View.VISIBLE);
setButton(mRightButton, R.string.sw_start_button, true, View.VISIBLE);
showShareButton(true);
break;
default:
break;
}
}
private boolean reachedMaxLaps() {
return mLapsAdapter.getCount() >= MAX_LAPS;
}
/***
* Set a single button with the string and states provided.
* @param b - Button view to update
* @param text - Text in button
* @param enabled - enable/disables the button
* @param visibility - Show/hide the button
*/
private void setButton (Button b, int text, boolean enabled, int visibility) {
b.setText(text);
b.setVisibility(visibility);
b.setEnabled(enabled);
}
/***
* Sets the string of the time running on the stopwatch up to hundred of a second accuracy
* @param time - in hundreds of a second since the stopwatch started
*/
private String getTimeText(long time) {
if (time < 0) {
time = 0;
}
long hundreds, seconds, minutes, hours;
seconds = time / 100;
hundreds = (time - seconds * 100);
minutes = seconds / 60;
seconds = seconds - minutes * 60;
hours = minutes / 60;
minutes = minutes - hours * 60;
if (hours > 99) {
hours = 0;
}
// TODO: must build to account for localization
String timeStr;
if (hours >= 10) {
timeStr = String.format("%02dh %02dm %02ds .%02d", hours, minutes,
seconds, hundreds);
} else if (hours > 0) {
timeStr = String.format("%01dh %02dm %02ds .%02d", hours, minutes,
seconds, hundreds);
} else if (minutes >= 10) {
timeStr = String.format("%02dm %02ds .%02d", minutes, seconds,
hundreds);
} else {
timeStr = String.format("%02dm %02ds .%02d", minutes, seconds,
hundreds);
}
return timeStr;
}
/***
*
* @param time - in hundredths of a second
*/
private void addLapTime(long time) {
int size = mLapsAdapter.getCount();
long curTime = time - mStartTime + mAccumulatedTime;
if (size == 0) {
// Always show the ending lap and a new one
mLapsAdapter.addLap(new Lap(curTime, curTime));
mLapsAdapter.addLap(new Lap(0, curTime));
mTime.setIntervalTime(curTime * 10);
} else {
long lapTime = curTime - ((Lap) mLapsAdapter.getItem(1)).mTotalTime;
((Lap)mLapsAdapter.getItem(0)).mLapTime = lapTime;
((Lap)mLapsAdapter.getItem(0)).mTotalTime = curTime;
mLapsAdapter.addLap(new Lap(0, 0));
mTime.setMarkerTime(lapTime * 10);
// mTime.setIntervalTime(lapTime * 10);
}
mLapsAdapter.notifyDataSetChanged();
// Start lap animation starting from the second lap
mTime.stopIntervalAnimation();
if (!reachedMaxLaps()) {
mTime.startIntervalAnimation();
}
}
private void updateCurrentLap(long curTime, long totalTime) {
if (mLapsAdapter.getCount() > 0) {
Lap curLap = (Lap)mLapsAdapter.getItem(0);
curLap.mLapTime = totalTime - ((Lap)mLapsAdapter.getItem(1)).mTotalTime;
curLap.mTotalTime = totalTime;
mLapsAdapter.notifyDataSetChanged();
}
}
private void showLaps() {
if (mLapsAdapter.getCount() > 0) {
mLapsList.setVisibility(View.VISIBLE);
mLapsTitle.setVisibility(View.VISIBLE);
} else {
mLapsList.setVisibility(View.INVISIBLE);
mLapsTitle.setVisibility(View.INVISIBLE);
}
}
private void startUpdateThread() {
mTime.post(mTimeUpdateThread);
}
private void stopUpdateThread() {
mTime.removeCallbacks(mTimeUpdateThread);
}
Runnable mTimeUpdateThread = new Runnable() {
@Override
public void run() {
long curTime = System.currentTimeMillis()/10;
long totalTime = mAccumulatedTime + (curTime - mStartTime);
if (mTime != null) {
mTimeText.setTime(totalTime);
}
if (mLapsAdapter.getCount() > 0) {
updateCurrentLap(curTime, totalTime);
}
mTime.postDelayed(mTimeUpdateThread, 10);
}
};
private String buildShareResults() {
return getString(R.string.sw_share_main, mTimeText.getTimeString());
}
}
|
package com.createsend.util.jersey;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
/**
* An extension of the Jersey JacksonJsonProvider used to set Jackson
* serialisation/deserialisation properties
*/
public class JsonProvider extends JacksonJsonProvider {
public static final DateFormat ApiDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void writeTo(Object value, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException {
ObjectMapper mapper = locateMapper(type, mediaType);
mapper.setSerializationInclusion(Inclusion.NON_NULL);
super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders,
entityStream);
}
@Override
public Object readFrom(Class<Object> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException {
ObjectMapper mapper = locateMapper(type, mediaType);
mapper.setDateFormat(ApiDateFormat);
mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
return super.readFrom(type, genericType, annotations, mediaType, httpHeaders,
entityStream);
}
}
|
package com.example.skytrainvancouver;
import java.util.ArrayList;
public class Constants {
public static ArrayList<Station> stations = new ArrayList<Station>();
public static int NUM_STATIONS= 52;
/* VANCOUVER SKYTRAIN LINES */
public static String LINE_EXPO = "Expo Line";
public static String LINE_MILLENIUM = "Millenium Line";
public static String LINE_CANADA = "Canada Line";
public static String LINE_EVERGREEN = "Evergreen Line";
//
public static int WATERFRONT = 0; // * 1 32
public static int BURRARD = 1;
public static int GRANVILLE = 2;
public static int CHINATOWN = 3;
public static int MAINSTREET = 4;
//
|
package com.github.miachm.SODS.input;
import com.github.miachm.SODS.spreadsheet.Range;
import com.github.miachm.SODS.spreadsheet.Sheet;
import com.github.miachm.SODS.spreadsheet.SpreadSheet;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class OdsWritter {
private SpreadSheet spread;
private Compressor out;
private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
private OdsWritter(OutputStream o, SpreadSheet spread) throws IOException {
this.spread = spread;
this.out = new Compressor(o);
dbf.setNamespaceAware(true);
}
public static void save(OutputStream out,SpreadSheet spread) throws IOException {
new OdsWritter(out,spread).save();
}
private void save() throws IOException {
writeManifest();
writeSpreadsheet();
out.close();
}
private void writeManifest() {
Document dom;
Element e = null;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.newDocument();
Element rootEle = dom.createElementNS("manifest","manifest");
rootEle.setAttribute("version","1.2");
e = dom.createElementNS("manifest","file-entry");
e.setAttribute("full-path","/");
e.setAttribute("version","1.2");
e.setAttribute("media-type","application/vnd.oasis.opendocument.spreadsheet");
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
ByteArrayOutputStream o = new ByteArrayOutputStream();
tr.transform(new DOMSource(dom),
new StreamResult(o));
o.close();
out.addEntry(o.toByteArray(),"./META-INF/manifest.xml");
} catch (TransformerException te) {
System.err.println(te.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.err.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
private void writeSpreadsheet() {
Document dom;
Element e = null;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.newDocument();
Element rootEle = dom.createElementNS("office","document-content");
rootEle.setAttribute("version","1.2");
e = dom.createElementNS("office","body");
Element spreadsheet = dom.createElementNS("office","spreadsheet");
e.appendChild(spreadsheet);
rootEle.appendChild(e);
dom.appendChild(rootEle);
for (Sheet sheet : spread.getSheets()) {
Element table = dom.createElementNS("table", "table");
table.setAttributeNS("table","name",sheet.getName());
for (int i = 0;i < sheet.getMaxColumns();i++){
Element column = dom.createElementNS("table", "column");
table.appendChild(column);
}
for (int i = 0;i < sheet.getMaxRows();i++){
Element row = dom.createElementNS("table", "row");
Range r = sheet.getRange(i,0,1,sheet.getMaxColumns());
for (int j = 0;j < sheet.getMaxColumns();j++) {
Object v = r.getCell(0,j).getValue();
Element cell = dom.createElementNS("table", "table-cell");
cell.setAttributeNS("calcext","value-type","string"); // TODO change to correct type
Element value = dom.createElementNS("text","p");
value.setTextContent(""+v);
cell.appendChild(value);
row.appendChild(cell);
}
table.appendChild(row);
}
spreadsheet.appendChild(table);
}
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
ByteArrayOutputStream o = new ByteArrayOutputStream();
tr.transform(new DOMSource(dom),
new StreamResult(o));
o.close();
out.addEntry(o.toByteArray(),"./content.xml");
} catch (TransformerException te) {
System.err.println(te.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.err.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
}
|
package com.jme.test.effects;
import com.jme.app.SimpleGame;
import com.jme.effects.ParticleController;
import com.jme.effects.ParticleSystem;
import com.jme.image.Texture;
import com.jme.input.FirstPersonController;
import com.jme.input.InputController;
import com.jme.input.InputSystem;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Controller;
import com.jme.scene.Node;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.system.JmeException;
import com.jme.util.TextureManager;
import com.jme.util.Timer;
/**
* @author Ahmed
*/
public class TestParticleSystem extends SimpleGame {
private ParticleSystem ps;
private ParticleController pc;
private Node root;
private Camera cam;
private Timer timer;
private InputController input;
private KeyInput key;
public static void main(String[] args) {
TestParticleSystem app = new TestParticleSystem();
app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG);
app.start();
}
protected void update(float interpolation) {
timer.update();
System.out.println(timer.getFrameRate());
input.update(timer.getTimePerFrame() * 10);
ps.update(10f / timer.getFrameRate());
cam.update();
root.updateWorldData(0.005f);
if (KeyBindingManager
.getKeyBindingManager()
.isValidCommand("PrintScrn")) {
display.getRenderer().takeScreenShot("data/screeny");
}
}
protected void render(float interpolation) {
display.getRenderer().clearBuffers();
display.getRenderer().draw(root);
}
protected void initSystem() {
try {
display = DisplaySystem.getDisplaySystem(properties.getRenderer());
display.createWindow(
properties.getWidth(),
properties.getHeight(),
properties.getDepth(),
properties.getFreq(),
properties.getFullscreen());
cam =
display.getRenderer().getCamera(
properties.getWidth(),
properties.getHeight());
} catch (JmeException e) {
e.printStackTrace();
System.exit(1);
}
display.getRenderer().setBackgroundColor(new ColorRGBA(0, 0, 0, 1));
cam.setFrustum(1f, 1000f, -0.55f, 0.55f, 0.4125f, -0.4125f);
Vector3f loc = new Vector3f(10, 0, 0);
Vector3f left = new Vector3f(0, -1, 0);
Vector3f up = new Vector3f(0, 0, 1f);
Vector3f dir = new Vector3f(-1, 0, 0);
cam.setFrame(loc, left, up, dir);
display.getRenderer().setCamera(cam);
timer = Timer.getTimer(properties.getRenderer());
input = new FirstPersonController(this, cam, properties.getRenderer());
input.setMouseSpeed(0.2f);
input.setKeySpeed(1f);
InputSystem.createInputSystem(properties.getRenderer());
key = InputSystem.getKeyInput();
KeyBindingManager.getKeyBindingManager().setKeyInput(key);
KeyBindingManager.getKeyBindingManager().set(
"PrintScrn",
KeyInput.KEY_F1);
}
protected void initGame() {
root = new Node();
AlphaState as1 = display.getRenderer().getAlphaState();
as1.setBlendEnabled(true);
as1.setSrcFunction(AlphaState.SB_SRC_ALPHA);
as1.setDstFunction(AlphaState.DB_ONE);
as1.setTestEnabled(true);
as1.setTestFunction(AlphaState.TF_GREATER);
as1.setEnabled(true);
TextureState ts = display.getRenderer().getTextureState();
ts.setTexture(
TextureManager.loadTexture(
"data/texture/star.png",
Texture.MM_LINEAR,
Texture.FM_LINEAR,
true));
ts.setEnabled(true);
ps = new ParticleSystem(100);
ps.setStartColor(
new ColorRGBA(1f, 1f, 0f, 1f));
ps.setEndColor(new ColorRGBA(0f, 1f, 0f, 0f));
ps.setStartSize(10);
ps.setEndSize(1);
ps.setGravity(new Vector3f(0, 0, 40));
ps.setSpeed(1f);
ps.setFriction(1f);
ps.setFade(0.03f);
ps.setStartPosition(new Vector3f(-50, 0, 0));
pc = new ParticleController(ps);
pc.setRepeatType(Controller.RT_WRAP);
ps.addController(pc);
ps.setRenderState(as1);
ps.setRenderState(ts);
root.attachChild(ps);
root.updateGeometricState(0.0f, true);
}
protected void reinit() {
}
protected void cleanup() {
}
}
|
package com.redpois0n.gscrot.ui;
import iconlib.IconUtils;
import java.awt.Color;
import java.awt.Component;
import java.awt.GraphicsDevice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import nativewindowlib.NativeWindow;
import nativewindowlib.WindowUtils;
import com.redpois0n.gscrot.BinaryImageProcessor;
import com.redpois0n.gscrot.Capture.Type;
import com.redpois0n.gscrot.CaptureUploader;
import com.redpois0n.gscrot.Config;
import com.redpois0n.gscrot.GraphicsImageProcessor;
import com.redpois0n.gscrot.ImageProcessor;
import com.redpois0n.gscrot.Main;
import com.redpois0n.gscrot.ScreenshotHelper;
import com.redpois0n.gscrot.ui.components.CaptureUploaderCheckBoxMenuItem;
import com.redpois0n.gscrot.ui.components.ImageProcessorCheckBoxMenuItem;
import com.redpois0n.gscrot.ui.settings.FrameSettings;
import com.redpois0n.gscrot.utils.Utils;
import com.redpois0n.oslib.OperatingSystem;
public class GlobalPopupMenu {
public static final List<JMenuItem> SETTINGS_ITEMS = new ArrayList<JMenuItem>();
public static List<Component> getMenu() {
List<Component> list = new ArrayList<Component>();
// Capture
JDropDownButton btnCapture = new JDropDownButton("Capture", IconUtils.getIcon("camera"));
list.add(btnCapture);
JMenuItem mntmRegion = new JMenuItem("Region", IconUtils.getIcon("region-select"));
mntmRegion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Main.createBackground();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
btnCapture.getMenu().add(mntmRegion);
JMenuItem mntmAllMonitors = new JMenuItem("All Monitors");
mntmAllMonitors.setIcon(IconUtils.getIcon("monitor-all"));
mntmAllMonitors.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ScreenshotHelper.process(Type.FULL, ScreenshotHelper.capture(ScreenshotHelper.getWholeDesktop()));
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnCapture.getMenu().add(mntmAllMonitors);
JMenu mntmMonitor = new JMenu("Monitor");
mntmMonitor.setIcon(IconUtils.getIcon("monitor"));
GraphicsDevice[] devices = ScreenshotHelper.getScreens();
JMenuItem mntmPickMonitor = new JMenuItem("Pick Monitor...", IconUtils.getIcon("monitor-select"));
mntmPickMonitor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new MonitorPicker().setVisible(true);
}
});
mntmMonitor.add(mntmPickMonitor);
mntmMonitor.addSeparator();
for (int i = 0; i < devices.length; i++) {
final GraphicsDevice device = devices[i];
JMenuItem item = new JMenuItem("Monitor " + i, IconUtils.getIcon("monitor"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScreenshotHelper.captureScreen(device);
}
});
mntmMonitor.add(item);
}
if (OperatingSystem.getOperatingSystem().getType() == OperatingSystem.WINDOWS) {
// Windows item
final JMenu mntmWindows = new JMenu("Window");
mntmWindows.setIcon(IconUtils.getIcon("window"));
List<NativeWindow> windows = WindowUtils.getVisibleWindows();
for (final NativeWindow window : windows) {
JMenuItem item = new JMenuItem(window.getTitle(), window.getIcon());
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ScreenshotHelper.process(Type.WINDOW, ScreenshotHelper.capture(window));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
mntmWindows.add(item);
}
btnCapture.add(mntmWindows);
}
// Tools
JDropDownButton btnTools = new JDropDownButton("Tools", IconUtils.getIcon("toolbox"));
list.add(btnTools);
JMenuItem mntmScreenColorPicker = new JMenuItem("Screen Color Picker", IconUtils.getIcon("pipette-color"));
mntmScreenColorPicker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Main.createColorPicker();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
btnTools.add(mntmScreenColorPicker);
JMenuItem mntmColorPicker = new JMenuItem("Color Picker", IconUtils.getIcon("color"));
mntmColorPicker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(null, "Color Picker", Color.black);
Utils.setColorInClipboard(color);
}
});
btnTools.add(mntmColorPicker);
list.add(new JSeparator());
// Image Uploaders
ButtonGroup group = new ButtonGroup();
JDropDownButton btnImageUploaders = new JDropDownButton("Image Uploaders", IconUtils.getIcon("drive-upload"));
list.add(btnImageUploaders);
CaptureUploader selectedUploader = CaptureUploader.getSelected();
for (CaptureUploader uploader : CaptureUploader.getAllUploaders()) {
CaptureUploaderCheckBoxMenuItem mntmUploader = new CaptureUploaderCheckBoxMenuItem(uploader);
mntmUploader.setIcon(uploader.getIcon());
mntmUploader.setSelected(uploader == selectedUploader);
btnImageUploaders.add(mntmUploader);
group.add(mntmUploader);
}
// Image processors
JDropDownButton btnImageProcessors = new JDropDownButton("Image Processors", IconUtils.getIcon("image-processor"));
list.add(btnImageProcessors);
for (BinaryImageProcessor processor: ImageProcessor.getBinaryProcessors()) {
ImageProcessorCheckBoxMenuItem mntmProcessor = new ImageProcessorCheckBoxMenuItem(processor);
mntmProcessor.setIcon(processor.getIcon());
btnImageProcessors.add(mntmProcessor);
}
for (GraphicsImageProcessor processor: ImageProcessor.getGraphicsProcessors()) {
ImageProcessorCheckBoxMenuItem mntmProcessor = new ImageProcessorCheckBoxMenuItem(processor);
mntmProcessor.setIcon(processor.getIcon());
btnImageProcessors.add(mntmProcessor);
}
list.add(new JSeparator());
// After upload
JDropDownButton btnAfterCapture = new JDropDownButton("After Capture", IconUtils.getIcon("after-capture"));
list.add(btnAfterCapture);
JCheckBoxMenuItem mntmImageClipboard = new JCheckBoxMenuItem("Copy Image to clipboard");
mntmImageClipboard.setSelected(Config.get(Config.KEY_COPY_IMAGE_TO_CLIPBOARD, "true").equalsIgnoreCase("true"));
mntmImageClipboard.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean b = ((JCheckBoxMenuItem) e.getSource()).isSelected();
Config.put(Config.KEY_COPY_IMAGE_TO_CLIPBOARD, b + "");
}
});
btnAfterCapture.add(mntmImageClipboard);
// After upload
JDropDownButton btnAfterUpload = new JDropDownButton("After Upload", IconUtils.getIcon("after-upload"));
list.add(btnAfterUpload);
JCheckBoxMenuItem mntmURLClipboard = new JCheckBoxMenuItem("Copy URL to clipboard");
mntmURLClipboard.setSelected(Config.get(Config.KEY_COPY_URL_TO_CLIPBOARD, "true").equalsIgnoreCase("true"));
mntmURLClipboard.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean b = ((JCheckBoxMenuItem) e.getSource()).isSelected();
Config.put(Config.KEY_COPY_URL_TO_CLIPBOARD, b + "");
}
});
btnAfterUpload.add(mntmURLClipboard);
list.add(new JSeparator());
// Settings
JDropDownButton mnSettings = new JDropDownButton("Settings", IconUtils.getIcon("settings"));
list.add(mnSettings);
JMenuItem mntmApplicationSettings = new JMenuItem("Application Settings", IconUtils.getIcon("settings"));
mntmApplicationSettings.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new FrameSettings().setVisible(true);
}
});
mnSettings.add(mntmApplicationSettings);
if (SETTINGS_ITEMS.size() > 0) {
mnSettings.getMenu().addSeparator();
for (JMenuItem item : SETTINGS_ITEMS) {
mnSettings.add(item);
}
}
list.add(new JSeparator());
list.add(Box.createVerticalGlue());
// Exit
JDropDownButton mntmExit = new JDropDownButton("Exit", IconUtils.getIcon("cross"));
list.add(mntmExit);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return list;
}
public static JPopupMenu getPopupMenu() {
JPopupMenu popup = new JPopupMenu();
return popup;
}
}
|
package com.vaadin.data.fieldbinder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.ui.Field;
/**
* FIXME Javadoc
*/
public class FieldBinder implements Serializable {
private Item item;
private boolean fieldsBuffered = true;
private boolean fieldsEnabled = true;
private boolean fieldsReadOnly = false;
private HashMap<Object, Field<?>> propertyIdToField = new HashMap<Object, Field<?>>();
private LinkedHashMap<Field<?>, Object> fieldToPropertyId = new LinkedHashMap<Field<?>, Object>();
private List<CommitHandler> commitHandlers = new ArrayList<CommitHandler>();
/**
* Updates the item that is used by this FieldBinder. Rebinds all fields to
* the properties in the new item.
*
* @param item
* The new item to use
*/
public void setItemDataSource(Item item) {
this.item = item;
for (Field<?> f : fieldToPropertyId.keySet()) {
bind(f, fieldToPropertyId.get(f));
}
}
/**
* Gets the item used by this FieldBinder. Note that you must call
* {@link #commit()} for the item to be updated unless buffered mode has
* been switched off.
*
* @see #setFieldsBuffered(boolean)
* @see #commit()
*
* @return The item used by this FieldBinder
*/
public Item getItemDataSource() {
return item;
}
/**
* Checks the buffered mode for the bound fields.
* <p>
*
* @see #setFieldsBuffered(boolean) for more details on buffered mode
*
* @see Field#isFieldsBuffered()
* @return true if buffered mode is on, false otherwise
*
*/
public boolean isFieldsBuffered() {
return fieldsBuffered;
}
/**
* Sets the buffered mode for the bound fields.
* <p>
* When buffered mode is on the item will not be updated until
* {@link #commit()} is called. If buffered mode is off the item will be
* updated once the fields are updated.
* </p>
* <p>
* The default is to use buffered mode.
* </p>
*
* @see Field#setFieldsBuffered(boolean)
* @param fieldsBuffered
* true to turn on buffered mode, false otherwise
*/
public void setFieldsBuffered(boolean fieldsBuffered) {
if (fieldsBuffered == this.fieldsBuffered) {
return;
}
this.fieldsBuffered = fieldsBuffered;
for (Field<?> field : getFields()) {
// FIXME: Could use setBuffered if that was in Field
field.setReadThrough(!isFieldsBuffered());
field.setWriteThrough(!isFieldsBuffered());
}
}
/**
* Returns the enabled status for the fields.
* <p>
* Note that this will not accurately represent the enabled status of all
* fields if you change the enabled status of the fields through some other
* method than {@link #setFieldsEnabled(boolean)}.
*
* @return true if the fields are enabled, false otherwise
*/
public boolean isFieldsEnabled() {
return fieldsEnabled;
}
/**
* Updates the enabled state of all bound fields.
*
* @param fieldsEnabled
* true to enable all bound fields, false to disable them
*/
public void setFieldsEnabled(boolean fieldsEnabled) {
this.fieldsEnabled = fieldsEnabled;
for (Field<?> field : getFields()) {
field.setEnabled(fieldsEnabled);
}
}
/**
* Returns the read only status for the fields.
* <p>
* Note that this will not accurately represent the read only status of all
* fields if you change the read only status of the fields through some
* other method than {@link #setFieldsReadOnly(boolean)}.
*
* @return true if the fields are set to read only, false otherwise
*/
public boolean isFieldsReadOnly() {
return fieldsReadOnly;
}
/**
* Updates the read only state of all bound fields.
*
* @param fieldsReadOnly
* true to set all bound fields to read only, false to set them
* to read write
*/
public void setFieldsReadOnly(boolean fieldsReadOnly) {
this.fieldsReadOnly = fieldsReadOnly;
}
/**
* Returns a collection of all fields that have been bound.
* <p>
* The fields are not returned in any specific order.
* </p>
*
* @return A collection with all bound Fields
*/
public Collection<Field<?>> getFields() {
return fieldToPropertyId.keySet();
}
/**
* Binds the field with the given propertyId from the current item. If an
* item has not been set then the binding is postponed until the item is set
* using {@link #setItemDataSource(Item)}.
*
* @param field
* The field to bind
* @param propertyId
* The propertyId to bind to the field
*/
public void bind(Field<?> field, Object propertyId) {
if (propertyIdToField.containsKey(propertyId)
&& propertyIdToField.get(propertyId) != field) {
throw new BindException("Property id " + propertyId
+ " is already bound to another field");
}
fieldToPropertyId.put(field, propertyId);
propertyIdToField.put(propertyId, field);
if (item == null) {
// Will be bound when data source is set
return;
}
field.setPropertyDataSource(getItemProperty(propertyId));
configureField(field);
}
/**
* Gets the property with the given property id from the item.
*
* @param propertyId
* The id if the property to find
* @return The property with the given id from the item
* @throws BindException
* If the property was not found in the item or no item has been
* set
*/
protected Property<?> getItemProperty(Object propertyId)
throws BindException {
Item item = getItemDataSource();
if (item == null) {
throw new BindException("Could not lookup property with id "
+ propertyId + " as no item has been set");
}
Property<?> p = item.getItemProperty(propertyId);
if (p == null) {
throw new BindException("A property with id " + propertyId
+ " was not found in the item");
}
return p;
}
/**
* Detaches the field from its property id and removes it from this
* FieldBinder.
* <p>
* Note that the field is not detached from its property data source if it
* is no longer connected to the same property id it was bound to using this
* FieldBinder.
*
* @param field
* The field to detach
* @throws BindException
* If the field is not bound by this field binder or not bound
* to the correct property id
*/
public void remove(Field<?> field) throws BindException {
Object propertyId = fieldToPropertyId.get(field);
if (propertyId == null) {
throw new BindException(
"The given field is not part of this FieldBinder");
}
if (field.getPropertyDataSource() == getItemProperty(propertyId)) {
field.setPropertyDataSource(null);
}
fieldToPropertyId.remove(field);
propertyIdToField.remove(propertyId);
}
/**
* Configures a field with the settings set for this FieldBinder.
* <p>
* By default this updates the buffered, read only and enabled state of the
* field.
*
* @param field
* The field to update
*/
protected void configureField(Field<?> field) {
// FIXME: Could use setBuffered if that was in Field
field.setReadThrough(!isFieldsBuffered());
field.setWriteThrough(!isFieldsBuffered());
field.setEnabled(isFieldsEnabled());
field.setReadOnly(isFieldsReadOnly());
}
/**
* Gets the type of the property with the given property id.
*
* @param propertyId
* The propertyId. Must be find
* @return The type of the property
*/
protected Class<?> getPropertyType(Object propertyId) throws BindException {
if (getItemDataSource() == null) {
throw new BindException(
"Property type for '"
+ propertyId
+ "' could not be determined. No item data source has been set.");
}
Property<?> p = getItemDataSource().getItemProperty(propertyId);
if (p == null) {
throw new BindException(
"Property type for '"
+ propertyId
+ "' could not be determined. No property with that id was found.");
}
return p.getType();
}
/**
* Returns a collection of all property ids that have been bound to fields.
* <p>
* Note that this will return property ids even before the item has been
* set. In that case it returns the property ids that will be bound once the
* item is set.
* </p>
* <p>
* No guarantee is given for the order of the property ids
* </p>
*
* @return A collection of bound property ids
*/
public Collection<Object> getBoundPropertyIds() {
return Collections.unmodifiableCollection(propertyIdToField.keySet());
}
/**
* Returns a collection of all property ids that exist in the item set using
* {@link #setItemDataSource(Item)} but have not been bound to fields.
* <p>
* Will always return an empty collection before an item has been set using
* {@link #setItemDataSource(Item)}.
* </p>
* <p>
* No guarantee is given for the order of the property ids
* </p>
*
* @return A collection of property ids that have not been bound to fields
*/
protected Collection<Object> getUnboundPropertyIds() {
if (getItemDataSource() == null) {
return new ArrayList<Object>();
}
return Collections.unmodifiableCollection(propertyIdToField.keySet());
}
/**
* Commits all changes done to the bound fields.
* <p>
* Calls all {@link CommitHandler}s before and after committing the field
* changes to the item data source. The whole commit is aborted and state is
* restored to what it was before commit was called if any
* {@link CommitHandler} throws a CommitException or there is a problem
* committing the fields
*
* @throws CommitException
* If the commit was aborted
*/
public void commit() throws CommitException {
// FIXME #8094 begintransaction()
try {
firePreCommitEvent();
for (Field<?> f : fieldToPropertyId.keySet()) {
f.commit();
}
firePostCommitEvent();
} catch (CommitException e) {
// rollback
} catch (Exception e) {
// rollback
throw new CommitException("Commit failed", e);
}
// FIXME #8094 endtransaction()
}
/**
* Sends a preCommit event to all registered commit handlers
*
* @throws CommitException
* If the commit should be aborted
*/
private void firePreCommitEvent() throws CommitException {
CommitHandler[] handlers = commitHandlers
.toArray(new CommitHandler[commitHandlers.size()]);
for (CommitHandler handler : handlers) {
handler.preCommit(new CommitEvent(this));
}
}
/**
* Sends a postCommit event to all registered commit handlers
*
* @throws CommitException
* If the commit should be aborted
*/
private void firePostCommitEvent() throws CommitException {
CommitHandler[] handlers = commitHandlers
.toArray(new CommitHandler[commitHandlers.size()]);
for (CommitHandler handler : handlers) {
handler.postCommit(new CommitEvent(this));
}
}
/**
* Discards all changes done to the bound fields.
* <p>
* Only has effect if buffered mode is used.
*
*/
public void discard() {
for (Field<?> f : fieldToPropertyId.keySet()) {
try {
f.discard();
} catch (Exception e) {
// TODO: handle exception
// What can we do if discard fails other than try to discard all
// other fields?
}
}
}
/**
* Returns the field that is bound to the given property id
*
* @param propertyId
* The property id to use to lookup the field
* @return The field that is bound to the property id or null if no field is
* bound to that property id
*/
public Field<?> getFieldForPropertyId(Object propertyId) {
return propertyIdToField.get(propertyId);
}
/**
* Adds a commit handler.
* <p>
* The commit handler is called before the field values are committed to the
* item ( {@link CommitHandler#preCommit(CommitEvent)}) and after the item
* has been updated ({@link CommitHandler#postCommit(CommitEvent)}). If a
* {@link CommitHandler} throws a CommitException the whole commit is
* aborted and the fields retinas their old values.
*
* @param commitHandler
* The commit handler to add
*/
public void addCommitHandler(CommitHandler commitHandler) {
commitHandlers.add(commitHandler);
}
/**
* Removes the given commit handler.
*
* @see #addCommitHandler(CommitHandler)
*
* @param commitHandler
* The commit handler to remove
*/
public void removeCommitHandler(CommitHandler commitHandler) {
commitHandlers.remove(commitHandler);
}
/**
* Returns a list of all commit handlers for this {@link FieldBinder}.
* <p>
* Use {@link #addCommitHandler(CommitHandler)} and
* {@link #removeCommitHandler(CommitHandler)} to register or unregister a
* commit handler.
*
* @return A collection of commit handlers
*/
protected Collection<CommitHandler> getCommitHandlers() {
return Collections.unmodifiableCollection(commitHandlers);
}
/**
* FIXME Javadoc
*
*/
public interface CommitHandler extends Serializable {
/**
* Called before changes are committed to the field and the item is
* updated.
* <p>
* Throw a {@link CommitException} to abort the commit.
*
* @param commitEvent
* An event containing information regarding the commit
* @throws CommitException
* if the commit should be aborted
*/
public void preCommit(CommitEvent commitEvent) throws CommitException;
/**
* Called after changes are committed to the fields and the item is
* updated..
* <p>
* Throw a {@link CommitException} to abort the commit.
*
* @param commitEvent
* An event containing information regarding the commit
* @throws CommitException
* if the commit should be aborted
*/
public void postCommit(CommitEvent commitEvent) throws CommitException;
}
/**
* FIXME javadoc
*
*/
public static class CommitEvent implements Serializable {
private FieldBinder fieldBinder;
private CommitEvent(FieldBinder fieldBinder) {
this.fieldBinder = fieldBinder;
}
/**
* Returns the field binder that this commit relates to
*
* @return The FieldBinder that is being committed.
*/
protected FieldBinder getFieldBinder() {
return fieldBinder;
}
}
/**
* Checks the validity of the bound fields.
* <p>
* Call the {@link Field#validate()} for the fields to get the individual
* error messages.
*
* @return true if all bound fields are valid, false otherwise.
*/
public boolean isAllFieldsValid() {
try {
for (Field<?> field : getFields()) {
field.validate();
}
return true;
} catch (InvalidValueException e) {
return false;
}
}
/**
* Checks if any bound field has been modified.
*
* @return true if at least on field has been modified, false otherwise
*/
public boolean isAnyFieldModified() {
for (Field<?> field : getFields()) {
if (field.isModified()) {
return true;
}
}
return false;
}
public static class CommitException extends Exception {
public CommitException() {
super();
// TODO Auto-generated constructor stub
}
public CommitException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public CommitException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public CommitException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
public class BindException extends RuntimeException {
public BindException(String message) {
super(message);
}
public BindException(String message, Throwable t) {
super(message, t);
}
}
}
|
package com.vaadin.terminal.gwt.client.ui;
import java.util.Set;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderInformation;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VErrorMessage;
public class VForm extends ComplexPanel implements Container {
private String height = "";
private String width = "";
public static final String CLASSNAME = "v-form";
private Container lo;
private Element legend = DOM.createLegend();
private Element caption = DOM.createSpan();
private Element errorIndicatorElement = DOM.createDiv();
private Element desc = DOM.createDiv();
private Icon icon;
private VErrorMessage errorMessage = new VErrorMessage();
private Element fieldContainer = DOM.createDiv();
private Element footerContainer = DOM.createDiv();
private Element fieldSet = DOM.createFieldSet();
private Container footer;
private ApplicationConnection client;
private RenderInformation renderInformation = new RenderInformation();
private int borderPaddingHorizontal;
private int borderPaddingVertical;
private boolean rendering = false;
public VForm() {
setElement(DOM.createDiv());
DOM.appendChild(getElement(), fieldSet);
setStyleName(CLASSNAME);
DOM.appendChild(fieldSet, legend);
DOM.appendChild(legend, caption);
DOM.setElementProperty(errorIndicatorElement, "className",
"v-errorindicator");
DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
DOM.setInnerText(errorIndicatorElement, " "); // needed for IE
DOM.setElementProperty(desc, "className", "v-form-description");
DOM.appendChild(fieldSet, desc);
DOM.appendChild(fieldSet, fieldContainer);
errorMessage.setVisible(false);
errorMessage.setStyleName(CLASSNAME + "-errormessage");
DOM.appendChild(fieldSet, errorMessage.getElement());
DOM.appendChild(fieldSet, footerContainer);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
boolean measure = false;
if (this.client == null) {
this.client = client;
measure = true;
}
if (client.updateComponent(this, uidl, false)) {
rendering = false;
return;
}
if (measure) {
// Measure the border when the style names have been set
borderPaddingVertical = getOffsetHeight();
int ow = getOffsetWidth();
int dow = desc.getOffsetWidth();
borderPaddingHorizontal = ow - dow;
}
boolean legendEmpty = true;
if (uidl.hasAttribute("caption")) {
DOM.setInnerText(caption, uidl.getStringAttribute("caption"));
legendEmpty = false;
} else {
DOM.setInnerText(caption, "");
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.insertChild(legend, icon.getElement(), 0);
}
icon.setUri(uidl.getStringAttribute("icon"));
legendEmpty = false;
} else {
if (icon != null) {
DOM.removeChild(legend, icon.getElement());
}
}
if (legendEmpty) {
DOM.setStyleAttribute(legend, "display", "none");
} else {
DOM.setStyleAttribute(legend, "display", "");
}
if (uidl.hasAttribute("error")) {
final UIDL errorUidl = uidl.getErrors();
errorMessage.updateFromUIDL(errorUidl);
errorMessage.setVisible(true);
} else {
errorMessage.setVisible(false);
}
if (uidl.hasAttribute("description")) {
DOM.setInnerHTML(desc, uidl.getStringAttribute("description"));
} else {
DOM.setInnerHTML(desc, "");
}
updateSize();
// TODO Check if this is needed
client.runDescendentsLayout(this);
final UIDL layoutUidl = uidl.getChildUIDL(0);
Container newLo = (Container) client.getPaintable(layoutUidl);
if (lo == null) {
lo = newLo;
add((Widget) lo, fieldContainer);
} else if (lo != newLo) {
client.unregisterPaintable(lo);
remove((Widget) lo);
lo = newLo;
add((Widget) lo, fieldContainer);
}
lo.updateFromUIDL(layoutUidl, client);
if (uidl.getChildCount() > 1) {
// render footer
Container newFooter = (Container) client.getPaintable(uidl
.getChildUIDL(1));
if (footer == null) {
add((Widget) newFooter, footerContainer);
footer = newFooter;
} else if (newFooter != footer) {
remove((Widget) footer);
client.unregisterPaintable(footer);
add((Widget) newFooter, footerContainer);
}
footer = newFooter;
footer.updateFromUIDL(uidl.getChildUIDL(1), client);
} else {
if (footer != null) {
remove((Widget) footer);
client.unregisterPaintable(footer);
}
}
rendering = false;
}
public void updateSize() {
renderInformation.updateSize(getElement());
renderInformation.setContentAreaHeight(renderInformation
.getRenderedSize().getHeight()
- borderPaddingVertical);
if (BrowserInfo.get().isIE6()) {
getElement().getStyle().setProperty("overflow", "hidden");
}
renderInformation.setContentAreaWidth(renderInformation
.getRenderedSize().getWidth()
- borderPaddingHorizontal);
}
public RenderSpace getAllocatedSpace(Widget child) {
if (child == lo) {
int hPixels = 0;
if (!"".equals(height)) {
hPixels = getOffsetHeight();
hPixels -= borderPaddingVertical;
hPixels -= footerContainer.getOffsetHeight();
hPixels -= errorMessage.getOffsetHeight();
hPixels -= desc.getOffsetHeight();
}
return new RenderSpace(renderInformation.getContentAreaSize()
.getWidth(), hPixels);
} else if (child == footer) {
return new RenderSpace(renderInformation.getContentAreaSize()
.getWidth(), 0);
} else {
ApplicationConnection.getConsole().error(
"Invalid child requested RenderSpace information");
return null;
}
}
public boolean hasChildComponent(Widget component) {
return component != null && (component == lo || component == footer);
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
if (!hasChildComponent(oldComponent)) {
throw new IllegalArgumentException(
"Old component is not inside this Container");
}
remove(oldComponent);
if (oldComponent == lo) {
lo = (Container) newComponent;
add((Widget) lo, fieldContainer);
} else {
footer = (Container) newComponent;
add((Widget) footer, footerContainer);
}
}
public boolean requestLayout(Set<Paintable> child) {
if (height != null && !"".equals(height) && width != null
&& !"".equals(width)) {
/*
* If the height and width has been specified the child components
* cannot make the size of the layout change
*/
return true;
}
if (renderInformation.updateSize(getElement())) {
return false;
} else {
return true;
}
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP form don't render caption for neither field layout nor footer
// layout
}
@Override
public void setHeight(String height) {
if (this.height.equals(height)) {
return;
}
this.height = height;
super.setHeight(height);
updateSize();
}
@Override
public void setWidth(String width) {
if (Util.equals(this.width, width)) {
return;
}
this.width = width;
super.setWidth(width);
updateSize();
if (!rendering && height.equals("")) {
// Width might affect height
Util.updateRelativeChildrenAndSendSizeUpdateEvent(client, this);
}
}
}
|
package org.intermine.web.logic.config;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.servlet.ServletContext;
import org.apache.commons.digester.Digester;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig;
import org.intermine.web.logic.widget.config.GraphWidgetConfig;
import org.intermine.web.logic.widget.config.HTMLWidgetConfig;
import org.intermine.web.logic.widget.config.TableWidgetConfig;
import org.intermine.web.logic.widget.config.WidgetConfig;
import org.xml.sax.SAXException;
/**
* Configuration object for web site
*
* @author Andrew Varley
*/
public class WebConfig
{
private static final Logger LOG = Logger.getLogger(WebConfig.class);
private final Map<String, Type> types = new TreeMap<String, Type>();
private final Map<String, TableExportConfig> tableExportConfigs =
new TreeMap<String, TableExportConfig>();
private final Map<String, WidgetConfig> widgets = new HashMap<String, WidgetConfig>();
private final List<ReportDisplayerConfig> reportDisplayerConfigs =
new ArrayList<ReportDisplayerConfig>();
/**
* Parse a WebConfig XML file
*
* @param context The servlet context we are in.
* @param model the Model to use when reading - used for checking class names and for finding
* sub and super classes
* @return a WebConfig object
* @throws SAXException if there is an error in the XML file
* @throws IOException if there is an error reading the XML file
* @throws FileNotFoundException if the XML file doesn't exist
* @throws ClassNotFoundException if a class is mentioned in the XML that isn't in the model
*/
public static WebConfig parse(final ServletContext context, final Model model)
throws IOException, FileNotFoundException, SAXException, ClassNotFoundException {
BasicConfigurator.configure();
final InputStream webconfXML = context.getResourceAsStream("/WEB-INF/webconfig-model.xml");
if (webconfXML == null) {
throw new FileNotFoundException("Could not find webconfig-model.xml");
}
final Digester digester = new Digester();
digester.setValidating(false);
digester.addObjectCreate("webconfig", WebConfig.class);
digester.addObjectCreate("webconfig/class", Type.class);
digester.addSetProperties("webconfig/class", "className", "className");
digester.addSetProperties("webconfig/class", "fieldName", "fieldName");
/* configure how the "title" of an object is displayed on Type */
digester.addObjectCreate("webconfig/class/headerconfig/titles", HeaderConfigTitle.class);
digester.addSetProperties("webconfig/class/headerconfig/titles/title",
"mainTitles", "mainTitles");
digester.addSetProperties("webconfig/class/headerconfig/titles/title",
"subTitles", "subTitles");
digester.addSetProperties("webconfig/class/headerconfig/titles/title",
"numberOfMainTitlesToShow", "numberOfMainTitlesToShow");
digester.addSetProperties("webconfig/class/headerconfig/titles/title",
"appendConfig", "appendConfig");
digester.addSetNext("webconfig/class/headerconfig/titles", "addHeaderConfigTitle");
digester.addObjectCreate("webconfig/class/headerconfig/customlinks",
HeaderConfigLink.class);
digester.addSetProperties("webconfig/class/headerconfig/customlinks/customlink",
"url", "url");
digester.addSetProperties("webconfig/class/headerconfig/customlinks/customlink",
"text", "text");
digester.addSetProperties("webconfig/class/headerconfig/customlinks/customlink",
"image", "image");
digester.addSetNext("webconfig/class/headerconfig/customlinks", "addHeaderConfigLink");
digester.addObjectCreate("webconfig/class/tabledisplayer", Displayer.class);
digester.addSetProperties("webconfig/class/tabledisplayer", "src", "src");
digester.addSetNext("webconfig/class/tabledisplayer", "setTableDisplayer");
digester.addCallMethod("webconfig/class/tabledisplayer/param", "addParam", 2);
digester.addCallParam("webconfig/class/tabledisplayer/param", 0, "name");
digester.addCallParam("webconfig/class/tabledisplayer/param", 1, "value");
digester.addObjectCreate("webconfig/class/fields/fieldconfig", FieldConfig.class);
digester.addSetProperties("webconfig/class/fields/fieldconfig", "fieldExpr", "fieldExpr");
digester.addSetProperties("webconfig/class/fields/fieldconfig", "name", "name");
digester.addSetProperties("webconfig/class/fields/fieldconfig", "displayer", "displayer");
digester.addSetProperties("webconfig/class/fields/fieldconfig",
"showInListAnalysisPreviewTable", "showInListAnalysisPreviewTable");
digester.addSetNext("webconfig/class/fields/fieldconfig", "addFieldConfig");
digester.addObjectCreate("webconfig/class/longdisplayers/displayer", Displayer.class);
digester.addSetProperties("webconfig/class/longdisplayers/displayer");
digester.addSetNext("webconfig/class/longdisplayers/displayer", "addLongDisplayer");
digester.addCallMethod("webconfig/class/longdisplayers/displayer/param", "addParam", 2);
digester.addCallParam("webconfig/class/longdisplayers/displayer/param", 0, "name");
digester.addCallParam("webconfig/class/longdisplayers/displayer/param", 1, "value");
/* display inline tables as inline lists instead */
digester.addObjectCreate("webconfig/class/inlinelist/table", InlineList.class);
digester.addSetProperties("webconfig/class/inlinelist/table");
digester.addSetNext("webconfig/class/inlinelist/table", "addInlineList");
digester.addSetProperties("webconfig/class/inlinelist/table", "path", "path");
digester.addSetProperties("webconfig/class/inlinelist/table",
"showLinksToObjects", "showLinksToObjects");
digester.addSetProperties("webconfig/class/inlinelist/table",
"showInHeader", "showInHeader");
digester.addSetProperties("webconfig/class/inlinelist/table", "lineLength", "lineLength");
digester.addObjectCreate("webconfig/class/bagdisplayers/displayer", Displayer.class);
digester.addSetProperties("webconfig/class/bagdisplayers/displayer");
digester.addSetNext("webconfig/class/bagdisplayers/displayer", "addBagDisplayer");
digester.addCallMethod("webconfig/class/bagdisplayers/displayer/param", "addParam", 2);
digester.addCallParam("webconfig/class/bagdisplayers/displayer/param", 0, "name");
digester.addCallParam("webconfig/class/bagdisplayers/displayer/param", 1, "value");
digester.addObjectCreate("webconfig/widgets/graphdisplayer", GraphWidgetConfig.class);
digester.addSetProperties("webconfig/widgets/graphdisplayer");
digester.addSetNext("webconfig/widgets/graphdisplayer", "addWidget");
digester.addObjectCreate("webconfig/widgets/enrichmentwidgetdisplayer",
EnrichmentWidgetConfig.class);
digester.addSetProperties("webconfig/widgets/enrichmentwidgetdisplayer");
digester.addSetNext("webconfig/widgets/enrichmentwidgetdisplayer", "addWidget");
digester.addObjectCreate("webconfig/widgets/bagtabledisplayer", TableWidgetConfig.class);
digester.addSetProperties("webconfig/widgets/bagtabledisplayer");
digester.addSetNext("webconfig/widgets/bagtabledisplayer", "addWidget");
digester.addObjectCreate("webconfig/widgets/htmldisplayer", HTMLWidgetConfig.class);
digester.addSetProperties("webconfig/widgets/htmldisplayer");
digester.addSetNext("webconfig/widgets/htmldisplayer", "addWidget");
digester.addSetNext("webconfig/class", "addType");
digester.addObjectCreate("webconfig/tableExportConfig", TableExportConfig.class);
digester.addSetProperties("webconfig/tableExportConfig", "id", "id");
digester.addSetProperties("webconfig/tableExportConfig", "className", "className");
digester.addSetNext("webconfig/tableExportConfig", "addTableExportConfig");
digester.addObjectCreate("webconfig/reportdisplayers/reportdisplayer",
ReportDisplayerConfig.class);
digester.addSetProperties("webconfig/reportdisplayers/reportdisplayer");
digester.addSetNext("webconfig/reportdisplayers/reportdisplayer", "addReportDisplayer");
final WebConfig webConfig = (WebConfig) digester.parse(webconfXML);
webConfig.validate(model);
webConfig.setSubClassConfig(model);
webConfig.loadLabelsFromMappingsFile(context, model);
return webConfig;
}
/**
* Get all the file names of properties files that configure class name mappings.
* @param props the main configuration to look in.
*/
private static List<String> getClassMappingFileNames(final Properties props) {
return getMappingFileNames(props, "web.config.classname.mappings");
}
/**
* Get all the file names of properties files that configure field name mappings.
* @param props the main configuration to look in.
*/
private static List<String> getFieldMappingFileNames(final Properties props) {
return getMappingFileNames(props, "web.config.fieldname.mappings");
}
/**
* Get all the files configured in a properties file with a certain prefix.
* @param prefix The prefix to use to get the list of values.
*/
private static List<String> getMappingFileNames(final Properties props, final String prefix) {
final List<String> returnVal = new ArrayList<String>();
for (@SuppressWarnings("rawtypes")
final Enumeration e = props.propertyNames(); e.hasMoreElements();) {
final String key = (String) e.nextElement();
if (key.startsWith(prefix)) {
returnVal.add(props.getProperty(key));
}
}
return returnVal;
}
private static Properties loadMergedProperties(final List<String> fileNames,
final ServletContext context)
throws IOException {
final Properties props = new Properties();
for (final String fileName : fileNames) {
LOG.info("Loading properties from " + fileName);
final Properties theseProps = new Properties();
final InputStream is = context.getResourceAsStream("/WEB-INF/" + fileName);
if (is == null) {
throw new FileNotFoundException("Could not find mappings file: " + fileName);
}
try {
theseProps.load(is);
} catch (final IOException e) {
throw new Error("Problem reading from " + fileName, e);
}
if (!props.isEmpty()) {
for (@SuppressWarnings("rawtypes")
final Enumeration e = props.propertyNames(); e.hasMoreElements();) {
final String key = (String) e.nextElement();
if (theseProps.containsKey(key)) {
throw new IllegalStateException(
"Duplicate label found for " + key + " in " + fileName);
}
}
}
if (theseProps.isEmpty()) {
LOG.info("No properties loaded from " + fileName);
} else {
LOG.info("Merging in " + theseProps.size() + " mappings from " + fileName);
props.putAll(theseProps);
}
}
return props;
}
/**
* Load labels specified in any configured mapping files, and apply them to the
* configuration for the appropriate classes and fields.
* @param context The servlet context to use to find configuration with.
* @param model The data model which lists our classes and fields.
*/
private void loadLabelsFromMappingsFile(
final ServletContext context,
final Model model)
throws IOException {
final Properties webProperties = SessionMethods.getWebProperties(context);
final List<String> classFileNames = getClassMappingFileNames(webProperties);
final List<String> fieldFileNames = getFieldMappingFileNames(webProperties);
final Properties fieldNameProperties = loadMergedProperties(fieldFileNames, context);
final Properties classNameProperties = loadMergedProperties(classFileNames, context);
for (final ClassDescriptor cd : model.getClassDescriptors()) {
labelClass(cd, classNameProperties, fieldNameProperties);
}
}
/**
* Apply any labels configured in the property files to the class. This means
* a label for the class itself, and labels for any of its fields.
* @param cd a class descriptor specifying the class.
* @param classNameProperties The mapping from our class names to a readable version
* @param fieldNameProperties The mapping from our field names to a readable version
*/
private void labelClass(
final ClassDescriptor cd,
final Properties classNameProperties,
final Properties fieldNameProperties) {
final String originalName = cd.getUnqualifiedName();
if ("InterMineObject".equals(originalName)) {
return;
}
Type classConfig = getTypes().get(cd.getName());
if (classConfig == null) {
classConfig = new Type();
classConfig.setClassName(cd.getName());
addType(classConfig);
}
if (classNameProperties.containsKey(originalName)) {
final String classNameLabel = classNameProperties.getProperty(originalName);
final String label = deSlashify(classNameLabel);
if (classConfig.getLabel() == null) {
LOG.info("Setting label as " + label + " on " + originalName);
classConfig.setLabel(label);
}
}
for (final FieldDescriptor fd : cd.getAllFieldDescriptors()) {
if (fieldNameProperties.containsKey(fd.getName())) {
final String fieldNameLabel = fieldNameProperties.getProperty(fd.getName());
final String label = deSlashify(fieldNameLabel);
FieldConfig fc = classConfig.getFieldConfigMap().get(fd.getName());
if (fc == null) {
fc = new FieldConfig();
fc.setFieldExpr(fd.getName());
fc.setShowInSummary(false);
fc.setShowInInlineCollection(false);
fc.setShowInResults(false);
classConfig.addFieldConfig(fc);
}
if (fc.getLabel() == null) {
LOG.info("Setting label as " + label + " on " + fd.getName()
+ " in " + originalName);
fc.setLabel(label);
}
}
}
}
/**
* Format strings in a SO format to be more human readable. For example,
* transcription_factor becomes "Transcription Factor", and "U11_snRNA" becomes
* "U11 snRNA".
* @param input the string to format
* @return A reformatted version of the string.
*/
private static String deSlashify(final String input) {
final String[] parts = StringUtils.split(input, "_");
final String[] outputParts = new String[parts.length];
for (int i = 0; i < parts.length; i++) {
final String part = parts[i];
if (part.equals(StringUtils.lowerCase(part))) {
outputParts[i] = StringUtils.capitalize(part);
} else {
outputParts[i] = part;
}
}
return StringUtils.join(outputParts, " ");
}
/**
* Validate web config according to the model. Test that configured classes exist in
* model and configured fields in web config exist in model.
* @param model model used for validation
*/
void validate(final Model model) {
final StringBuffer invalidClasses = new StringBuffer();
final StringBuffer badFieldExpressions = new StringBuffer();
for (final String typeName : types.keySet()) {
if (!model.getClassNames().contains(typeName)) {
invalidClasses.append(" " + typeName);
continue;
}
final Type type = types.get(typeName);
for (final FieldConfig fieldConfig : type.getFieldConfigs()) {
String pathString;
try {
pathString = Class.forName(typeName).getSimpleName()
+ "." + fieldConfig.getFieldExpr();
} catch (final ClassNotFoundException e) {
final String msg = "Invalid web config. '"
+ typeName + "' doesn't exist in the " + "model.";
LOG.warn(msg);
continue;
}
try {
new Path(model, pathString);
} catch (final PathException e) {
badFieldExpressions.append(" " + pathString);
continue;
}
}
}
if (invalidClasses.length() > 0 || badFieldExpressions.length() > 0) {
final String msg = "Invalid web config. "
+ (invalidClasses.length() > 0
? "Classes specified in web config that don't exist in model: "
+ invalidClasses.toString() + ". " : "")
+ (badFieldExpressions.length() > 0
? "Path specified in a fieldExpr does note exist in model: "
+ badFieldExpressions + ". " : "");
LOG.error(msg);
}
}
public String validateWidgetsConfig(final Model model) {
WidgetConfig widget = null;
StringBuffer validationMessage = new StringBuffer();
for (String widgetId : widgets.keySet()) {
widget = widgets.get(widgetId);
//verify startClass
String startClass = model.getPackageName() + "." + widget.getStartClass();
if (!model.getClassNames().contains(startClass)) {
validationMessage = validationMessage.append("The attribute startClass for the"
+ "widget " + widgetId + " is not in the model.");
}
//verify typeClass
if (!model.getClassNames().contains(widget.getTypeClass())) {
validationMessage = validationMessage.append("The attribute typeClass for the "
+ "widget " + widgetId + " is not in the model.");
}
//verify constraints (only path)
List<PathConstraint> pathConstraints = widget.getPathConstraints();
for (PathConstraint pathConstraint : pathConstraints) {
try {
new Path(model, widget.getStartClass() + "." + pathConstraint.getPath());
} catch (final PathException e) {
validationMessage.append("The path " + pathConstraint.getPath() + " set in the"
+ " constraints for the widget " + widgetId + " is not in the model.");
}
}
//verify views
String[] views = widget.getViews().split("\\s*,\\s*");
for (String viewPath : views) {
viewPath = widget.getStartClass() + "." + viewPath;
try {
new Path(model, viewPath);
} catch (final PathException e) {
validationMessage.append("The path " + viewPath + " set in the views for the "
+ "widget " + widgetId + " is not in the model.");
}
}
//verify enrich and enrichId for enrichement widgets
if (widget instanceof EnrichmentWidgetConfig) {
String enrich = ((EnrichmentWidgetConfig) widget).getEnrich();
validatePath(model, widget.getStartClass(), enrich, "enrich", widgetId,
validationMessage);
String enrichId = ((EnrichmentWidgetConfig) widget).getEnrichIdentifier();
if (enrichId != null) {
validatePath(model, widget.getStartClass(), enrichId, "enrichIdentifier",
widgetId, validationMessage);
}
}
//verify categoryPath and seriesPath for graph widgets
if (widget instanceof GraphWidgetConfig) {
String categoryPath = ((GraphWidgetConfig) widget).getCategoryPath();
validatePath(model, widget.getStartClass(), categoryPath, "categoryPath", widgetId,
validationMessage);
String seriesPath = ((GraphWidgetConfig) widget).getSeriesPath();
if (!"".equals(seriesPath) && !"ActualExpectedCriteria".equals(seriesPath)) {
validatePath(model, widget.getStartClass(), seriesPath, "seriesPath", widgetId,
validationMessage);
}
}
}
return validationMessage.toString();
}
private void validatePath(Model model, String startClass, String pathToValidate, String label,
String widgetId, StringBuffer validationMessage) {
try {
new Path(model, startClass + "." + pathToValidate);
} catch (final PathException e) {
validationMessage.append("The attribute " + label + " " + pathToValidate
+ " set for the widget " + widgetId + " is not in the model.");
}
}
/**
* Add a type to the WebConfig Map. Use className as the key of the Map if fieldName of the
* Type is null, otherwise use the class name, a space, and the field name.
*
* @param type the Type to add
*/
public void addType(final Type type) {
String typeString = type.getClassName();
if (types.containsKey(typeString)) {
throw new IllegalArgumentException("Type " + typeString
+ " defined more that once in webconfig-model.xml");
} else {
types.put(type.getClassName(), type);
}
}
/**
* Get a map from fully qualified class name to the Type config for that class
* @return the types
*/
public Map<String, Type> getTypes() {
return types;
}
/**
* Return a FieldConfigs for a particular class or an empty list if no config is defined.
* @param clsName the class to fetch field configs for
* @return the FieldConfigs or an empty collection
*/
public Collection<FieldConfig> getFieldConfigs(String clsName) {
Type type = types.get(clsName);
if (type != null) {
return type.getFieldConfigs();
}
return Collections.emptyList();
}
/**
* Return the FieldConfig for a particular field of the specified field, or null if field not
* configured.
* @param clsName the class to fetch field config for
* @param fieldName the field to fetch config for
* @return Collection<FieldConfig>
*/
public FieldConfig getFieldConfig(String clsName, String fieldName) {
Type type = types.get(clsName);
if (type != null) {
return type.getFieldConfig(fieldName);
}
return null;
}
/**
* @return the widgets - a map from widget name to config details.
*/
public Map<String, WidgetConfig> getWidgets() {
return widgets;
}
/**
* @param widget the widget
*/
public void addWidget(final WidgetConfig widget) {
widgets.put(widget.getId(), widget);
final String[] widgetTypes = widget.getTypeClass().split(",");
for (final String widgetType: widgetTypes) {
final Type type = types.get(widgetType);
if (type == null) {
final String msg = "Invalid web config. " + widgetType + " is not a valid class. "
+ "Please correct the entry in the webconfig-model.xml for the "
+ widget.getId() + " widget.";
LOG.warn(msg);
} else {
type.addWidget(widget);
}
}
}
/**
* Add config for a report page displayer. This checks that a type has been specified
* before adding the config.
* @param reportDisplayerConfig config for an individual report page displayer
*/
public void addReportDisplayer(final ReportDisplayerConfig reportDisplayerConfig) {
final Set<String> displayForTypes = reportDisplayerConfig.getConfiguredTypes();
if (displayForTypes.isEmpty()) {
LOG.error("Report displayer: " + reportDisplayerConfig.getJavaClass() + "/"
+ reportDisplayerConfig.getJspName() + " is not configured for any types");
} else {
reportDisplayerConfigs.add(reportDisplayerConfig);
}
}
/**
* Fetch config for the report page displayers.
* @return report page displayer config in the order specified in the config file
*/
public List<ReportDisplayerConfig> getReportDisplayerConfigs() {
return reportDisplayerConfigs;
}
/**
* Add an TableExportConfig to the Map of TableExportConfig objects using
* tableExportConfig.getId() as the Map key.
* @param tableExportConfig the TableExportConfig to add
*/
public void addTableExportConfig(final TableExportConfig tableExportConfig) {
tableExportConfigs.put(tableExportConfig.getId(), tableExportConfig);
}
/**
* Return a Map of TableExportConfig.id to TableExportConfig objects.
* @return the TableExportConfig Map
*/
public Map<String, TableExportConfig> getTableExportConfigs() {
return tableExportConfigs;
}
/**
* {@inheritDoc}
*
* @param obj the Object to compare with
* @return true if this is equal to obj
*/
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof WebConfig)) {
return false;
}
final WebConfig webConfigObj = (WebConfig) obj;
return types.equals(webConfigObj.types)
&& tableExportConfigs.equals(webConfigObj.tableExportConfigs);
}
/**
* {@inheritDoc}
*
* @return the hashCode for this WebConfig object
*/
@Override
public int hashCode() {
return types.hashCode();
}
/**
* For each class/Type mentioned in XML files, copy its displayers and FieldConfigs to all
* subclasses that don't already have any configuration and sometimes when they do.
* This method has package scope so that it can be called from the tests.
*
* @param model the Model to use to find sub-classes
* @throws ClassNotFoundException if any of the classes mentioned in the XML file aren't in the
* Model
*/
void setSubClassConfig(final Model model) throws ClassNotFoundException {
for (final Iterator<ClassDescriptor> modelIter
= model.getTopDownLevelTraversal().iterator(); modelIter.hasNext();) {
final ClassDescriptor cld = modelIter.next();
Type thisClassType = types.get(cld.getName());
if (thisClassType == null) {
thisClassType = new Type();
thisClassType.setClassName(cld.getName());
types.put(cld.getName(), thisClassType);
}
final Set<ClassDescriptor> cds
= model.getClassDescriptorsForClass(Class.forName(cld.getName()));
for (final ClassDescriptor cd : cds) {
if (cld.getName().equals(cd.getName())) {
continue;
}
final Type superClassType = types.get(cd.getName());
if (superClassType != null) {
// set title config, the setter itself only adds configs that have not been set
// before, see setTitles() in HeaderConfig
final HeaderConfigTitle hc = superClassType.getHeaderConfigTitle();
if (hc != null) {
// set the HeaderConfig titles as HeaderConfig for thisClassType might have
// been configured
final HashMap<String, List<HeaderConfigTitle.TitlePart>> titles =
hc.getTitles();
if (titles != null) {
// new childish HeaderConfig
final HeaderConfigTitle subclassHc =
thisClassType.getHeaderConfigTitle();
if (subclassHc != null) {
// type A behavior: inherit titles from the parent and append
if (subclassHc.getAppendConfig()) {
subclassHc.addTitleParts(hc.getTitles());
}
} else {
// type B behavior: inherit from parent if we are null
thisClassType.addHeaderConfigTitle(hc);
}
}
}
if (thisClassType.getFieldConfigs().size() == 0) {
// copy any FieldConfigs from the super class
for (final FieldConfig fc : superClassType.getFieldConfigs()) {
thisClassType.addFieldConfig(fc);
}
} else {
// Set labels on overridden field-configs without labels
for (final FieldConfig superfc : superClassType.getFieldConfigs()) {
for (final FieldConfig thisfc : thisClassType.getFieldConfigs()) {
if (thisfc.getFieldExpr().equals(superfc.getFieldExpr())) {
if (superfc.getLabel() != null && thisfc.getLabel() == null) {
thisfc.setLabel(superfc.getLabel());
}
}
}
}
}
if (thisClassType.getLongDisplayers().size() == 0) {
@SuppressWarnings("rawtypes")
final Iterator longDisplayerIter
= superClassType.getLongDisplayers().iterator();
while (longDisplayerIter.hasNext()) {
final Displayer ld = (Displayer) longDisplayerIter.next();
thisClassType.addLongDisplayer(ld);
}
}
if (thisClassType.getTableDisplayer() == null) {
thisClassType.setTableDisplayer(superClassType.getTableDisplayer());
}
if (thisClassType.getWidgets().size() == 0
&& superClassType.getWidgets() != null
&& superClassType.getWidgets().size() > 0) {
@SuppressWarnings("rawtypes")
final Iterator widgetIter = superClassType.getWidgets().iterator();
while (widgetIter.hasNext()) {
final WidgetConfig wi = (WidgetConfig) widgetIter.next();
thisClassType.addWidget(wi);
}
}
}
}
}
}
/**
* Return an XML String of this WebConfig object
*
* @return a String version of this WebConfig object
*/
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append("<webconfig>");
final Iterator<Type> typesIter = types.values().iterator();
while (typesIter.hasNext()) {
sb.append(typesIter.next().toString() + "\n");
}
final Iterator<TableExportConfig> tableExportConfigIter
= tableExportConfigs.values().iterator();
while (tableExportConfigIter.hasNext()) {
sb.append(tableExportConfigIter.next().toString());
}
sb.append("</webconfig>");
return sb.toString();
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.font.Font;
import lombok.Getter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class Screen extends Component {
/** The non-layer components displayed on the screen. */
private final Set<Component> components = new HashSet<>();
/** The layer components displayed on the screen. */
private final Set<Layer> layerComponents = new HashSet<>();
/** The screen components displayed on the screen. */
private final Set<Screen> screenComponents = new HashSet<>();
/**
* Constructs a new AsciiScreen.
*
* @param columnIndex
* The x-axis (column) coordinate of the top-left character.
*
* @param rowIndex
* The y-axis (row) coordinate of the top-left character.
*
* @param width
* Thw width, in characters.
*
* @param height
* The height, in characters.
*/
public Screen(final int columnIndex, final int rowIndex, final int width, final int height) {
super(columnIndex, rowIndex, width, height);
}
@Override
public void draw(final Screen screen) {
throw new UnsupportedOperationException("A Screen must be drawn using the draw(canvas, font) method.");
}
/**
* Draws the screen onto the specified canvas using the specified font.
*
* @param gc
* The graphics context to draw with.
*
* @param font
* The font to draw with.
*/
public void draw(final Graphics2D gc, final Font font) {
// Draw non-layer components onto the screen:
components.forEach(component -> component.draw(this));
// Draw the screen onto the canvas:
for (int row = 0 ; row < height ; row++) {
strings[row].draw(gc, font, row);
}
// Draw layer components onto the screen:
layerComponents.forEach(layer -> layer.draw(gc, font));
// Draw screen components onto the screen:
screenComponents.forEach(screen -> screen.draw(gc, font));
}
/**
* Clears the entire screen.
*
* @param character
* The character to replace every character on the screen with.
*
* @return
* If all characters within the screen were cleared.
*/
public void clear(final char character) {
clear(character, 0, 0, super.getWidth(), super.getHeight());
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param columnIndex
* The x-axis (column) coordinate of the cell to clear.
*
* @param rowIndex
* The y-axis (row) coordinate of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*/
public void clear(final char character, final int columnIndex, final int rowIndex, int width, int height) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= width >= 0;
canProceed &= height >= 0;
if (canProceed) {
width += columnIndex;
height += rowIndex;
for (int column = columnIndex ; column < width ; column++) {
for (int row = rowIndex ; row < height ; row++) {
write(character, column, row);
}
}
}
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*
* @return
* If the write was successful.
*/
public boolean write(final AsciiCharacter character, final int columnIndex, final int rowIndex) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= character != null;
if (canProceed) {
strings[rowIndex].setCharacter(columnIndex, character);
}
return canProceed;
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*/
public void write(final char character, final int columnIndex, final int rowIndex) {
if (isPositionValid(columnIndex, rowIndex)) {
strings[rowIndex].setCharacter(columnIndex, character);
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param columnIndex
* The x-axis (column) coordinate to begin writing from.
*
* @param rowIndex
* The y-axis (row) coordinate to begin writing from.
*/
public void write(final AsciiString string, final int columnIndex, final int rowIndex) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= string != null;
if (canProceed) {
final AsciiCharacter[] characters = string.getCharacters();
for (int i = 0; i < characters.length && i < super.getWidth(); i++) {
write(characters[i], columnIndex + i, rowIndex);
}
}
}
/**
* Draws the screen onto an image.
*
* This calls the draw function, so the screen may look a
* little different if there are blink effects or new updates
* to characters that haven't yet been drawn.
*
* This is an expensive operation as it essentially creates
* an in-memory screen and draws each AsciiCharacter onto
* that screen.
*
* @param asciiFont
* The font to render the screen with.
*
* @return
* An image of the screen.
*/
public BufferedImage screenshot(final Font asciiFont) {
final BufferedImage img = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
final Graphics2D gc = img.createGraphics();
for (final AsciiString string : strings) {
string.setAllCharactersToBeRedrawn();
}
draw(gc, asciiFont);
gc.dispose();
return img;
}
/**
* Sets the background color of all characters.
*
* @param color
* The new background color.
*/
public void setBackgroundColor(final Color color) {
if (color == null) {
return;
}
for (final AsciiString string : strings) {
string.setBackgroundColor(color);
}
}
/**
* Sets the foreground color of all characters.
*
* @param color
* The new foreground color.
*/
public void setForegroundColor(final Color color) {
if (color == null) {
return;
}
for (final AsciiString string : strings) {
string.setForegroundColor(color);
}
}
/**
* Sets the background and foreground color of all characters.
*
* @param background
* The new background color.
*
* @param foreground
* The new foreground color.
*/
public void setBackgroundAndForegroundColor(final Color background, final Color foreground) {
if (background == null || foreground == null) {
return;
}
for (final AsciiString string : strings) {
string.setBackgroundAndForegroundColor(background, foreground);
}
}
/**
* Adds a component to the screen.
*
* @param component
* The component.
*/
public void addComponent(final Component component) {
if (component == null) {
return;
}
if (component == this) {
return;
}
if (component instanceof Layer) {
layerComponents.add((Layer) component);
} else if (component instanceof Screen) {
// Prevent an endless draw-loop by ensuring that
// a screen cannot be added if it's contained
// within any of this screen's sub-screens.
if (recursiveContainsComponent(component) == false) {
screenComponents.add((Screen) component);
}
} else {
components.add(component);
}
}
/**
* Removes a component from the screen.
*
* @param component
* The component.
*/
public void removeComponent(final Component component) {
if (component == null) {
return;
}
if (component == this) {
return;
}
if (component instanceof Layer) {
layerComponents.remove(component);
} else if (component instanceof Screen) {
screenComponents.remove(component);
} else{
components.remove(component);
}
}
/**
* Determines whether or not the screen contains a specific
* component.
*
* @param component
* The component.
*
* @return
* Whether or not the screen contains the component.
*/
public boolean containsComponent(final Component component) {
if (component == null) {
return false;
}
if (component == this) {
return false;
}
if (component instanceof Layer) {
if (layerComponents.contains(component)) {
return true;
}
}
if (component instanceof Screen) {
if (screenComponents.contains(component)) {
return true;
}
}
if (components.contains(component)) {
return true;
}
return false;
}
/**
* Determines whether or not the screen, or any sub-screen of
* the screen, contains a specific component.
*
* @param component
* The component.
*
* @return
* Whether or not the component is contained within the
* screen or any sub-screen.
*/
public boolean recursiveContainsComponent(final Component component) {
if (component == null) {
return false;
}
if (component == this) {
return false;
}
if (containsComponent(component)) {
return true;
}
if (component instanceof Screen) {
if (((Screen) component).containsComponent(this)) {
return true;
}
}
for (final Screen screen : screenComponents) {
if (screen.containsComponent(component)) {
return true;
}
}
return false;
}
/**
* Determines the total number of components.
*
* @return
* The total number of components.
*/
public int totalComponents() {
int sum = components.size();
sum += layerComponents.size();
sum += screenComponents.size();
return sum;
}
}
|
package com.veggiespam.imagelocationscanner;
import java.io.File;
import java.io.FileInputStream;
//import java.io.FileOutputStream; // Only needed when debugging the code
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Collection;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.lang.GeoLocation;
import com.drew.metadata.exif.GpsDirectory;
import com.drew.metadata.iptc.IptcDirectory;
import com.drew.metadata.iptc.IptcDescriptor;
import com.drew.metadata.exif.makernotes.PanasonicMakernoteDirectory;
import com.drew.metadata.exif.makernotes.PanasonicMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.LeicaMakernoteDirectory;
import com.drew.metadata.exif.makernotes.LeicaMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.ReconyxUltraFireMakernoteDirectory;
import com.drew.metadata.exif.makernotes.ReconyxUltraFireMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.ReconyxHyperFireMakernoteDirectory;
import com.drew.metadata.exif.makernotes.ReconyxHyperFireMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.CanonMakernoteDirectory;
import com.drew.metadata.exif.makernotes.CanonMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.SigmaMakernoteDirectory;
import com.drew.metadata.exif.makernotes.SigmaMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.NikonType2MakernoteDirectory;
import com.drew.metadata.exif.makernotes.NikonType2MakernoteDescriptor;
import com.drew.metadata.exif.makernotes.OlympusMakernoteDirectory;
import com.drew.metadata.exif.makernotes.OlympusMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.OlympusEquipmentMakernoteDirectory;
import com.drew.metadata.exif.makernotes.OlympusEquipmentMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.FujifilmMakernoteDirectory;
import com.drew.metadata.exif.makernotes.FujifilmMakernoteDescriptor;
public class ILS {
/** A bunch of static strings that are used by both ZAP and Burp plug-ins. */
public static final String pluginName = "Image Location and Privacy Scanner";
public static final String pluginVersion = "1.0";
public static final String alertTitle = "Image Exposes Location or Privacy Data";
public static final String alertDetailPrefix = "This image embeds a location or leaks privacy-related data: ";
public static final String alertBackground
= "The image was found to contain embedded location information, such as GPS coordinates, or "
+ "another privacy exposure, such as camera serial number. "
+ "Depending on the context of the image in the website, "
+ "this information may expose private details of the users of a site. For example, a site that allows "
+ "users to upload profile pictures taken in the home may expose the home's address. ";
public static final String remediationBackground
= "Before allowing images to be stored on the server and/or transmitted to the browser, strip out the "
+ "embedded location information from image. This could mean removing all Exif data or just the GPS "
+ "component. Other data, like serial numbers, should also be removed.";
public static final String remediationDetail = null;
public static final String referenceURL = "https:
public static final String pluginAuthor = "Jay Ball (veggiespam)";
private static final String EmptyString = "";
private static final String TextSubtypeEnd = ": "; // colon space for plain text results
private static final String HTML_subtype_begin = "<li>";
private static final String HTML_subtype_title_end = "\n\t<ul>\n";
private static final String HTML_subtype_end = "\t</ul></li>\n";
private static final String HTML_finding_begin = "\t<li>";
private static final String HTML_finding_end = "</li>\n";
public ILS() {
// blank constructor
super();
}
public String getAuthor() {
return pluginAuthor;
}
/** Tests a data blob for Location or GPS information and returns the image location
* information as a string. If no location is present or there is an error,
* the function will return an empty string of "".
*
* @param data is a byte array that is an image file to test, such as entire jpeg file.
* @return String containing the Location data or an empty String indicating no GPS data found.
*/
public static String[] scanForLocationInImageBoth(byte[] data) {
String[] results = { EmptyString, EmptyString };
try {
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data, 0, data.length));
Metadata md = ImageMetadataReader.readMetadata(is);
String[] tmp = { EmptyString, EmptyString };
tmp = scanForLocation(md);
results = scanForPrivacy(md);
if (tmp[0].length() > 0) {
// minor formatting if we have both.
results[0] = tmp[0] + "\n\n" + results[0];
results[1] = "<ul>" + tmp[1] + results[1] + "</ul>";
// AGAIN: this is for extreme debugging
// results[0] = "DBG: " + t[0] + "\n\n" + results[0];
// results[1] = "DBG: " + t[1] + "\n\n" + results[1];
}
} catch (ImageProcessingException e) {
// bad image, just ignore processing exceptions
// DEBUG: return new String("ImageProcessingException " + e.toString());
} catch (IOException e) {
// bad file or something, just ignore
// DEBUG: return new String("IOException " + e.toString());
}
return results;
}
/** Returns ILS information as HTML formatting string.
*
* @see scanForLocationInImageBoth
*/
public static String scanForLocationInImageHTML(byte[] data) {
return scanForLocationInImageBoth(data)[1];
}
/** Returns ILS information as Text formatting string.
*
* @see scanForLocationInImageBoth
*/
public static String scanForLocationInImageText(byte[] data) {
return scanForLocationInImageBoth(data)[0];
}
/**
* @deprecated Use the HTML / Text calls directly or use boolean construct.
*/
@Deprecated
public static String scanForLocationInImage(byte[] data) {
return scanForLocationInImageHTML(data);
}
/** Returns ILS informtion in Text or HTML depending on usehtml flag.
*
* @param data is a byte array that is an image file to test, such as entire jpeg file.
* @param usehtml output as html (true) or plain txt (false)
* @return String containing the Location data or an empty String indicating no GPS data found.
* @see scanForLocationInImageBoth
*/
public static String scanForLocationInImage(byte[] data, boolean usehtml) {
if (usehtml) {
return scanForLocationInImageHTML(data);
} else {
return scanForLocationInImageText(data);
}
}
private static String[] appendResults(String current[], String bigtype, String subtype, ArrayList<String> exposure) {
String[] tmp = formatResults(bigtype, subtype, exposure);
if (tmp[0].length() > 0) {
current[0] = current[0] + tmp[0];
current[1] = current[1] + tmp[1];
}
return current;
}
/** Tiny chance of XSS inside of Burp/ZAP, return properly escaped HTML. */
private static String escapeHTML(String s) {
return s.replace("&","&").replace("<",">");
}
/** Do this for completeness, even if a no-op for now. */
private static String escapeTEXT(String s) {
return s; // might want to do more here someday, like binary data as hex codes, etc...
}
private static String[] formatResults(String bigtype, String subtype, ArrayList<String> exposure) {
StringBuffer ret = new StringBuffer(200);
StringBuffer retHTML = new StringBuffer(200);
String[] retarr = { EmptyString, EmptyString };
if (exposure.size() > 0) {
retHTML.append(HTML_subtype_begin).append(bigtype).append(" / ").append(subtype).append(HTML_subtype_title_end);
for (String finding : exposure) {
ret.append(subtype).append(TextSubtypeEnd).append(escapeTEXT(finding)).append("\n");
retHTML.append(HTML_finding_begin).append(escapeHTML(finding)).append(HTML_finding_end);
}
retHTML.append(HTML_subtype_end);
}
retarr[0] = ret.toString();
retarr[1] = retHTML.toString();
return retarr;
}
public static String[] scanForLocation(Metadata md) {
ArrayList<String> exposure = new ArrayList<String>();
String[] results = { EmptyString, EmptyString };
String bigtype = "Location"; // Overall category type. Location or Privacy
String subtype = EmptyString;
// ** Standard Exif GPS
subtype = "Exif_GPS";
Collection<GpsDirectory> gpsDirColl = md.getDirectoriesOfType(GpsDirectory.class);
if (gpsDirColl != null) {
exposure.clear();
for (GpsDirectory gpsDir : gpsDirColl) {
final GeoLocation geoLocation = gpsDir.getGeoLocation();
if ( ! (geoLocation == null || geoLocation.isZero()) ) {
String finding = geoLocation.toDMSString();
exposure.add(finding);
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
// ** IPTC testing
subtype = "IPTC";
Collection<IptcDirectory> iptcDirColl = md.getDirectoriesOfType(IptcDirectory.class);
int iptc_tag_list[] = {
IptcDirectory.TAG_CITY,
IptcDirectory.TAG_CONTENT_LOCATION_CODE,
IptcDirectory.TAG_CONTENT_LOCATION_NAME,
IptcDirectory.TAG_COUNTRY_OR_PRIMARY_LOCATION_CODE,
IptcDirectory.TAG_COUNTRY_OR_PRIMARY_LOCATION_NAME,
IptcDirectory.TAG_DESTINATION,
};
if (iptcDirColl != null) {
exposure.clear();
for (IptcDirectory iptcDir : iptcDirColl) {
IptcDescriptor iptcDesc = new IptcDescriptor(iptcDir);
for (int i=0; i< iptc_tag_list.length; i++) {
String tag = iptcDesc.getDescription(iptc_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add( iptcDir.getTagName(iptc_tag_list[i]) + " = " + tag );
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Panasonic";
Collection<PanasonicMakernoteDirectory> panasonicDirColl = md.getDirectoriesOfType(PanasonicMakernoteDirectory.class);
int panasonic_tag_list[] = {
PanasonicMakernoteDirectory.TAG_CITY,
PanasonicMakernoteDirectory.TAG_COUNTRY,
PanasonicMakernoteDirectory.TAG_LANDMARK,
PanasonicMakernoteDirectory.TAG_LOCATION,
PanasonicMakernoteDirectory.TAG_STATE
};
if (panasonicDirColl != null) {
exposure.clear();
for (PanasonicMakernoteDirectory panasonicDir : panasonicDirColl) {
PanasonicMakernoteDescriptor descriptor = new PanasonicMakernoteDescriptor(panasonicDir);
for (int i=0; i< panasonic_tag_list.length; i++) {
String tag = descriptor.getDescription(panasonic_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(panasonicDir.getTagName(panasonic_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
// For Text, add the big type in the final entry
if (results[0].length() > 0) {
results[0] = bigtype + ":: " + results[0];
}
return results;
}
public static String[] scanForPrivacy(Metadata md) {
String bigtype = "Privacy"; // Overall category type.
String subtype = EmptyString;
ArrayList<String> exposure = new ArrayList<String>();
String[] results = { EmptyString, EmptyString };
// ** IPTC testing
subtype = "IPTC";
Collection<IptcDirectory> iptcDirColl = md.getDirectoriesOfType(IptcDirectory.class);
int iptc_tag_list[] = {
IptcDirectory.TAG_KEYWORDS,
IptcDirectory.TAG_LOCAL_CAPTION
// what about CREDIT BY_LINE ...
};
if (iptcDirColl != null) {
exposure.clear();
for (IptcDirectory iptcDir : iptcDirColl) {
IptcDescriptor iptcDesc = new IptcDescriptor(iptcDir);
for (int i=0; i< iptc_tag_list.length; i++) {
String tag = iptcDesc.getDescription(iptc_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add( iptcDir.getTagName(iptc_tag_list[i]) + " = " + tag );
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Panasonic";
Collection<PanasonicMakernoteDirectory> panasonicDirColl = md.getDirectoriesOfType(PanasonicMakernoteDirectory.class);
int panasonic_tag_list[] = {
PanasonicMakernoteDirectory.TAG_BABY_AGE,
PanasonicMakernoteDirectory.TAG_BABY_AGE_1,
PanasonicMakernoteDirectory.TAG_BABY_NAME,
PanasonicMakernoteDirectory.TAG_FACE_RECOGNITION_INFO,
PanasonicMakernoteDirectory.TAG_INTERNAL_SERIAL_NUMBER,
PanasonicMakernoteDirectory.TAG_LENS_SERIAL_NUMBER
// What about TAG_TEXT_STAMP_* TAG_TITLE
};
if (panasonicDirColl != null) {
exposure.clear();
for (PanasonicMakernoteDirectory panasonicDir : panasonicDirColl) {
PanasonicMakernoteDescriptor descriptor = new PanasonicMakernoteDescriptor(panasonicDir);
for (int i=0; i< panasonic_tag_list.length; i++) {
String tag = descriptor.getDescription(panasonic_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(panasonicDir.getTagName(panasonic_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Leica";
Collection<LeicaMakernoteDirectory> leicaDirColl = md.getDirectoriesOfType(LeicaMakernoteDirectory.class);
int leica_tag_list[] = {
LeicaMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (leicaDirColl != null) {
exposure.clear();
for (LeicaMakernoteDirectory leicaDir : leicaDirColl) {
LeicaMakernoteDescriptor descriptor = new LeicaMakernoteDescriptor(leicaDir);
for (int i=0; i< leica_tag_list.length; i++) {
String tag = descriptor.getDescription(leica_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(leicaDir.getTagName(leica_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "ReconyxHyperFire";
Collection<ReconyxHyperFireMakernoteDirectory> reconyxHyperFireDirColl = md.getDirectoriesOfType(ReconyxHyperFireMakernoteDirectory.class);
int reconyxHyperFire_tag_list[] = {
ReconyxHyperFireMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (reconyxHyperFireDirColl != null) {
exposure.clear();
for (ReconyxHyperFireMakernoteDirectory reconyxHyperFireDir : reconyxHyperFireDirColl) {
ReconyxHyperFireMakernoteDescriptor descriptor = new ReconyxHyperFireMakernoteDescriptor(reconyxHyperFireDir);
for (int i=0; i< reconyxHyperFire_tag_list.length; i++) {
String tag = descriptor.getDescription(reconyxHyperFire_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(reconyxHyperFireDir.getTagName(reconyxHyperFire_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "ReconyxUltraFire";
Collection<ReconyxUltraFireMakernoteDirectory> reconyxUltraFireDirColl = md.getDirectoriesOfType(ReconyxUltraFireMakernoteDirectory.class);
int reconyxUltraFire_tag_list[] = {
ReconyxUltraFireMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (reconyxUltraFireDirColl != null) {
exposure.clear();
for (ReconyxUltraFireMakernoteDirectory reconyxUltraFireDir : reconyxUltraFireDirColl) {
ReconyxUltraFireMakernoteDescriptor descriptor = new ReconyxUltraFireMakernoteDescriptor(reconyxUltraFireDir);
for (int i=0; i< reconyxUltraFire_tag_list.length; i++) {
String tag = descriptor.getDescription(reconyxUltraFire_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(reconyxUltraFireDir.getTagName(reconyxUltraFire_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Olympus";
Collection<OlympusMakernoteDirectory> olympusDirColl = md.getDirectoriesOfType(OlympusMakernoteDirectory.class);
int olympus_tag_list[] = {
OlympusMakernoteDirectory.TAG_SERIAL_NUMBER_1
};
if (olympusDirColl != null) {
exposure.clear();
for (OlympusMakernoteDirectory olympusDir: olympusDirColl) {
OlympusMakernoteDescriptor descriptor = new OlympusMakernoteDescriptor(olympusDir);
for (int i=0; i< olympus_tag_list.length; i++) {
String tag = descriptor.getDescription(olympus_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(olympusDir.getTagName(olympus_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "OlympusEquipment";
Collection<OlympusEquipmentMakernoteDirectory> olympusEquipmentDirColl = md.getDirectoriesOfType(OlympusEquipmentMakernoteDirectory.class);
int olympusEquipment_tag_list[] = {
OlympusEquipmentMakernoteDirectory.TAG_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_INTERNAL_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_LENS_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_EXTENDER_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_FLASH_SERIAL_NUMBER
};
if (olympusEquipmentDirColl != null) {
exposure.clear();
for (OlympusEquipmentMakernoteDirectory olympusEquipmentDir: olympusEquipmentDirColl) {
OlympusEquipmentMakernoteDescriptor descriptor = new OlympusEquipmentMakernoteDescriptor(olympusEquipmentDir);
for (int i=0; i< olympusEquipment_tag_list.length; i++) {
String tag = descriptor.getDescription(olympusEquipment_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(olympusEquipmentDir.getTagName(olympusEquipment_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Canon";
Collection<CanonMakernoteDirectory> canonDirColl = md.getDirectoriesOfType(CanonMakernoteDirectory.class);
int canon_tag_list[] = {
CanonMakernoteDirectory.TAG_CANON_OWNER_NAME,
CanonMakernoteDirectory.TAG_CANON_SERIAL_NUMBER
};
if (canonDirColl != null) {
exposure.clear();
for (CanonMakernoteDirectory canonDir: canonDirColl) {
CanonMakernoteDescriptor descriptor = new CanonMakernoteDescriptor(canonDir);
for (int i=0; i< canon_tag_list.length; i++) {
String tag = descriptor.getDescription(canon_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(canonDir.getTagName(canon_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Sigma";
Collection<SigmaMakernoteDirectory> sigmaDirColl = md.getDirectoriesOfType(SigmaMakernoteDirectory.class);
int sigma_tag_list[] = {
SigmaMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (sigmaDirColl != null) {
exposure.clear();
for (SigmaMakernoteDirectory sigmaDir: sigmaDirColl) {
SigmaMakernoteDescriptor descriptor = new SigmaMakernoteDescriptor(sigmaDir);
for (int i=0; i< sigma_tag_list.length; i++) {
String tag = descriptor.getDescription(sigma_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(sigmaDir.getTagName(sigma_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Nikon";
Collection<NikonType2MakernoteDirectory> nikonDirColl = md.getDirectoriesOfType(NikonType2MakernoteDirectory.class);
int nikon_tag_list[] = {
NikonType2MakernoteDirectory.TAG_CAMERA_SERIAL_NUMBER,
NikonType2MakernoteDirectory.TAG_CAMERA_SERIAL_NUMBER_2
};
if (nikonDirColl != null) {
exposure.clear();
for (NikonType2MakernoteDirectory nikonDir: nikonDirColl) {
NikonType2MakernoteDescriptor descriptor = new NikonType2MakernoteDescriptor(nikonDir);
for (int i=0; i< nikon_tag_list.length; i++) {
String tag = descriptor.getDescription(nikon_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(nikonDir.getTagName(nikon_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "FujiFilm";
Collection<FujifilmMakernoteDirectory> fujifilmDirColl = md.getDirectoriesOfType(FujifilmMakernoteDirectory.class);
int fujifilm_tag_list[] = {
FujifilmMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (fujifilmDirColl != null) {
exposure.clear();
for (FujifilmMakernoteDirectory fujifilmDir: fujifilmDirColl) {
FujifilmMakernoteDescriptor descriptor = new FujifilmMakernoteDescriptor(fujifilmDir);
for (int i=0; i< fujifilm_tag_list.length; i++) {
String tag = descriptor.getDescription(fujifilm_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(fujifilmDir.getTagName(fujifilm_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
if (results[0].length() > 0) {
results[0] = bigtype + ":: " + results[0];
}
return results;
}
public static void main(String[] args) throws Exception {
boolean html = false;
if (args.length == 0){
System.out.println("Java Image Location & Privacy Scanner");
System.out.println("Usage: java ILS.class [-h|-t] file1.jpg file2.png file3.txt [...]");
System.out.println("\t-h : optional specifer to output results in HTML format");
System.out.println("\t-t : optional specifer to output results in plain text format (default)");
return;
}
for (String s: args) {
if (s.equals("-h")) {
html=true;
continue;
}
if (s.equals("-t")) {
html=false;
continue;
}
try {
System.out.print("Processing " + s + " : ");
File f = new File(s);
FileInputStream fis = new FileInputStream(f);
long size = f.length();
byte[] data = new byte[(int) size];
fis.read(data);
fis.close();
String res = scanForLocationInImage(data, html);
if (0 == res.length()) {
res = "None";
}
System.out.println(res);
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// vim: autoindent noexpandtab tabstop=4 shiftwidth=4
|
package com.wimbli.onlineusers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;
public class OnlineUsersMySQL extends OnlineUsersDataSource {
private String name = "OnlineUsers";
protected static final Logger log = Logger.getLogger("Minecraft");
private static String sqlTruncateTable = "TRUNCATE `"+OnlineUsers.table+"`";
private static String sqlMakeTable = "CREATE TABLE IF NOT EXISTS `"+OnlineUsers.table+"` ("+
"`name` varchar(32) NOT NULL, " +
"`time` datetime DEFAULT NULL, " +
"`time_total` int DEFAULT 0, " +
"PRIMARY KEY (`name`))";
private static String sqlOnlineUser = "INSERT INTO `"+OnlineUsers.table+"` (`name`, `time`, `online`) VALUES (?, NOW(), 1) ON DUPLICATE KEY UPDATE `time`=NOW(), `online`=1";
private static String sqlOfflineUser = "UPDATE `"+OnlineUsers.table+"` SET `time_total` = IF(`online`=1, `time_total` + TIMESTAMPDIFF(SECOND, `time`, NOW()), `time_total`), `online`=0 WHERE `name`=?";
private static String sqlDeleteOfflineUser = "DELETE FROM `"+OnlineUsers.table+"` WHERE `name`=?";
private static String sqlSetAllOffline = "UPDATE `"+OnlineUsers.table+"` SET `time_total` = IF(`online`=1, `time_total` + TIMESTAMPDIFF(SECOND, `time`, NOW()), `time_total`), `online`=0";
// these are run see if update for older databases is needed, and then update them if so
private static String sqlCheckTableExist = "SHOW TABLES LIKE '"+OnlineUsers.table+"'";
private static String sqlCheckTableTimeTt = "SHOW COLUMNS FROM `"+OnlineUsers.table+"` WHERE `Field` = 'time_total'";
private static String sqlAlterTableOnline = "ALTER TABLE `"+OnlineUsers.table+"` ADD `online` bit(1) NOT NULL DEFAULT 0";
private static String sqlAlterTableOnline2 = "ALTER TABLE `"+OnlineUsers.table+"` CHANGE `online` `online` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT 0";
private static String sqlAlterTableTimeTtA = "ALTER TABLE `"+OnlineUsers.table+"` ADD `time_total` INT NOT NULL DEFAULT 0";
private static String sqlAlterTableTimeTt1 = "ALTER TABLE `"+OnlineUsers.table+"` CHANGE `time_total` `time_total_old` TIME NOT NULL DEFAULT '00:00:00'";
private static String sqlAlterTableTimeTt2 = "ALTER TABLE `"+OnlineUsers.table+"` ADD `time_total` INT NOT NULL DEFAULT 0";
private static String sqlAlterTableTimeTt3 = "UPDATE `"+OnlineUsers.table+"` SET `time_total` = TIME_TO_SEC(`time_total_old`)";
private static String sqlAlterTableTimeTt4 = "ALTER TABLE `"+OnlineUsers.table+"` DROP `time_total_old`";
@Override
public boolean init() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {};
return createTable();
}
@Override
public boolean addUser(String username) {
return execute(sqlOnlineUser,username);
}
@Override
public boolean removeUser(String username) {
return execute (sqlDeleteOfflineUser, username);
}
@Override
public boolean setUserOffline(String username) {
return execute (sqlOfflineUser, username);
}
@Override
public boolean setAllOffline() {
return execute (sqlSetAllOffline);
}
@Override
public boolean removeAllUsers() {
return execute (sqlTruncateTable);
}
private Connection getConnection() throws SQLException {
Connection conn = null;
try{
conn = DriverManager.getConnection(OnlineUsers.db,OnlineUsers.user,OnlineUsers.pass);
} catch (Exception e) {
log.severe(name + ": " + e.getMessage());
}
checkConnection(conn);
return conn;
}
private boolean checkConnection (Connection conn) throws SQLException {
if (conn == null) {
log.severe("Could not connect to the database. Check your credentials in online-users.settings");
throw new SQLException();
}
if (!conn.isValid(5)) {
log.severe("Could not connect to the database.");
throw new SQLException();
}
return true;
}
private boolean execute(String sql) {
return execute(sql, null);
}
private boolean execute(String sql, String player) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if (player != null && !player.equalsIgnoreCase("")) {
ps.setString(1, player);
}
if (ps.execute()) {
return true;
}
} catch (SQLException ex) {
log.severe(name + ": " + ex.getMessage());
String msg = name + ": could not execute the sql \"" + sql + "\"";
if (player != null ) {
msg += " ?=" +player;
}
log.severe(msg);
} finally {
try {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
log.severe(name + ": " + ex.getMessage());
}
}
return false;
}
private boolean createTable() {
Connection conn = null;
Statement s = null;
ResultSet rs = null;
try {
conn = getConnection();
s = conn.createStatement();
s.executeUpdate(sqlMakeTable);
// Run sqlCheckTableTimeTt query to see if time_total column exists, and check column type
try {
rs = s.executeQuery(sqlCheckTableTimeTt);
if (rs.first()) {
// `time_total` column exists, but does it need to be altered from TIME to INT?
if (!rs.getString("Type").toLowerCase().startsWith("int"))
{
log.info(name + ": Updating Table, changing time_total column from TIME to INT");
// sadly altering a column directly from TIME to INT will reset all values to 0, so out of necessity,
// we first rename the column, then create a new one with the new type, then translate the values over, then delete the original column to clean up
s.executeUpdate(sqlAlterTableTimeTt1);
s.executeUpdate(sqlAlterTableTimeTt2);
s.executeUpdate(sqlAlterTableTimeTt3);
s.executeUpdate(sqlAlterTableTimeTt4);
}
rs.close();
s.close();
conn.close();
return true;
}
log.info(name + ": Updating Table");
s.executeUpdate(sqlAlterTableTimeTtA);
s.executeUpdate(sqlAlterTableOnline);
s.executeUpdate(sqlAlterTableOnline2);
} catch (SQLException ex2){}
rs = s.executeQuery(sqlCheckTableExist);
if (rs.first()) {
rs.close();
s.close();
conn.close();
return true;
}
} catch (SQLException ex) {
log.severe(name + ": " + ex.getMessage());
} finally {
try {
if (rs != null)
rs.close();
if (s != null)
s.close();
if (conn != null)
conn.close();
} catch (SQLException ex) {
log.severe(name + ": " + ex.getMessage());
}
}
return false;
}
}
|
package com.zencher.app.dailysomething;
import android.app.AlarmManager;
import android.app.Fragment;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.sql.Time;
import java.util.Calendar;
import java.util.TimeZone;
import android.widget.Button;
import com.zencher.app.dailysomething.activity.Sample1Activity;
import com.zencher.app.dailysomething.util.LogUtil;
public class Settings extends Fragment implements TimePickerDialog.OnTimeSetListener{
private View v;
private Button bt,bt2, lovekevin;
private TextView tv;
Switch sw;
int savedHour,savedMin;
SharedPreferences settingsActivity,settingsActivity2,settingsActivity3;
int notificationId;
private PendingIntent alarmIntent;
boolean swex;
public static final long DAY = 1000 * 60 * 60 * 24;
void check(TextView tv, int hour, int min){
if (min<10){
tv.setVisibility(View.VISIBLE);
tv.setText(Integer.toString(hour) + ":" + "0" + Integer.toString(min));
SharedPreferences.Editor editor = settingsActivity.edit();
editor.putString("mystring", Integer.toString(hour) + ":" + "0" + Integer.toString(min));
editor.commit();
}else{
tv.setVisibility(View.VISIBLE);
tv.setText(Integer.toString(hour) + ":" + Integer.toString(min));
SharedPreferences.Editor editor = settingsActivity.edit();
editor.putString("mystring", Integer.toString(hour) + ":" + Integer.toString(min));
editor.commit();
}
}
private static final String KEY_PASSWORD = "key_password";
public static Intent createIntent(Context context) {
Intent intent = new Intent(context, Settings.class);
return intent;
}
public static Intent createIntent(Context context, int password) {
Intent intent = new Intent(context, Settings.class);
intent.putExtra(KEY_PASSWORD, password);
return intent;
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LogUtil.d("onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
settingsActivity = this.getActivity().getSharedPreferences("pref", Context.MODE_APPEND);
settingsActivity2 = this.getActivity().getSharedPreferences("pref2",Context.MODE_APPEND);
settingsActivity3 = this.getActivity().getSharedPreferences("pref3", Context.MODE_APPEND);
boolean getState = settingsActivity2.getBoolean("swSt",false);
String mystring = settingsActivity.getString("mystring", "");
int timeSaver = settingsActivity3.getInt("timeS", 0);
int timeSaver2 = settingsActivity3.getInt("timeS2",0);
v = inflater.inflate(R.layout.setting, container, false);
bt = (Button) v.findViewById(R.id.button7);
bt2 = (Button)v.findViewById(R.id.button13);
lovekevin = (Button)v.findViewById(R.id.buttonlovekevin);
tv = (TextView)v.findViewById(R.id.textView5);
sw = (Switch)v.findViewById(R.id.switch1);
sw.setChecked(getState);
swex = getState;
tv.setText(mystring);
savedHour = timeSaver;
savedMin = timeSaver2;
if (tv.getText() != null){
tv.setVisibility(View.VISIBLE);
}
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new TimePickerDialog(getActivity(), Settings.this, 0, 0, true).show();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = settingsActivity.edit();
editor.clear();
editor.commit();
tv.setVisibility(View.GONE);
tv.setText(null);
if(sw.isChecked()){
sw.toggle();
}
SharedPreferences.Editor editor2 = settingsActivity2.edit();
editor2.putBoolean("swSt", sw.isChecked());
editor2.commit();
AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
am.cancel(alarmIntent);
}
});
lovekevin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getActivity(), Sample1Activity.class);
startActivity(intent);
}
});
getActivity().setTitle("Setting");
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor2 = settingsActivity2.edit();
editor2.putBoolean("swSt", isChecked);
editor2.commit();
if (tv.getVisibility() == View.VISIBLE) {
if (isChecked) {
Intent bootIntent = new Intent(getActivity(), AlarmBroadcastReceiver.class);
bootIntent.putExtra("notificationId", notificationId);
alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, bootIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
long firstTime = SystemClock.elapsedRealtime();
long systemTime = System.currentTimeMillis();
Calendar startTime = Calendar.getInstance();
startTime.setTimeZone(TimeZone.getTimeZone("GMT+8"));
startTime.set(Calendar.HOUR_OF_DAY, savedHour);
startTime.set(Calendar.MINUTE, savedMin);
startTime.set(Calendar.SECOND, 0);
long alarmStartTime = startTime.getTimeInMillis();
if (systemTime > alarmStartTime) {
Toast.makeText(getActivity(), "Alarm set! (Next Day)", Toast.LENGTH_SHORT).show();
startTime.add(Calendar.DAY_OF_MONTH, 1);
alarmStartTime = startTime.getTimeInMillis();
} else {
Toast.makeText(getActivity(), "Alarm Set!", Toast.LENGTH_SHORT).show();
}
long time = alarmStartTime - systemTime;
firstTime += time;
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, DAY, alarmIntent);
notificationId++;
} else {
AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
am.cancel(alarmIntent);
Toast.makeText(getActivity(), "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
}
}
});
return v;
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (sw.isChecked() != true){
sw.toggle();
SharedPreferences.Editor editor2 = settingsActivity2.edit();
editor2.putBoolean("swSt", sw.isChecked());
editor2.commit();
}
check(tv, hourOfDay, minute);
Intent bootIntent = new Intent(getActivity(), AlarmBroadcastReceiver.class);
bootIntent.putExtra("notificationId", notificationId);
alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, bootIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
long firstTime = SystemClock.elapsedRealtime();
long systemTime = System.currentTimeMillis();
Calendar startTime = Calendar.getInstance();
startTime.setTimeZone(TimeZone.getTimeZone("GMT+8"));
startTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
startTime.set(Calendar.MINUTE, minute);
startTime.set(Calendar.SECOND, 0);
savedHour = hourOfDay;
savedMin = minute;
SharedPreferences.Editor editor3 = settingsActivity3.edit();
editor3.putInt("timeSaver", hourOfDay);
editor3.putInt("timeSaver2",minute);
editor3.commit();
long alarmStartTime = startTime.getTimeInMillis();
if (systemTime > alarmStartTime) {
Toast.makeText(getActivity(), "Alarm set! (Next Day)", Toast.LENGTH_SHORT).show();
startTime.add(Calendar.DAY_OF_MONTH, 1);
alarmStartTime = startTime.getTimeInMillis();
}else{
Toast.makeText(getActivity(), "Alarm Set!", Toast.LENGTH_SHORT).show();
}
long time = alarmStartTime - systemTime;
firstTime += time;
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, DAY, alarmIntent);
notificationId++;
}
}
|
package org.monkeyscript.lite;
import java.util.Arrays;
import org.mozilla.javascript.*;
// org.mozilla.javascript.NativeString was used as a reference for implementation of this
final class NativeBlob extends IdScriptableObject {
static final long serialVersionUID = 1248149631L;
private static final Object BLOB_TAG = "Blob";
static void init(Scriptable scope, boolean sealed) {
NativeBlob obj = NativeBlob.newEmpty();
obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
}
static NativeBlob newEmpty() {
byte[] b = new byte[0];
return new NativeBlob(b);
}
private NativeBlob(byte b) {
bytes = new byte[1];
bytes[0] = b;
}
private NativeBlob(byte[] b) {
bytes = b;
}
@Override
public String getClassName() {
return "Blob";
}
private static final int
Id_length = 1,
MAX_INSTANCE_ID = 1;
@Override
protected int getMaxInstanceId() {
return MAX_INSTANCE_ID;
}
@Override
protected int findInstanceIdInfo(String s) {
if (s.equals("length")) {
return instanceIdInfo(DONTENUM | READONLY | PERMANENT, Id_length);
}
return super.findInstanceIdInfo(s);
}
@Override
protected String getInstanceIdName(int id) {
if (id == Id_length) { return "length"; }
return super.getInstanceIdName(id);
}
@Override
protected Object getInstanceIdValue(int id) {
if (id == Id_length) {
return ScriptRuntime.wrapInt(bytes.length);
}
return super.getInstanceIdValue(id);
}
@Override
protected void fillConstructorProperties(IdFunctionObject ctor) {
addIdFunctionProperty(ctor, BLOB_TAG, ConstructorId_byteAt, "byteAt", 2);
addIdFunctionProperty(ctor, BLOB_TAG, ConstructorId_intAt, "intAt", 2);
addIdFunctionProperty(ctor, BLOB_TAG, ConstructorId_indexOf, "indexOf", 2);
addIdFunctionProperty(ctor, BLOB_TAG, ConstructorId_lastIndexOf, "lastIndexOf", 2);
addIdFunctionProperty(ctor, BLOB_TAG, ConstructorId_split, "split", 3);
addIdFunctionProperty(ctor, BLOB_TAG, ConstructorId_concat, "concat", 2);
addIdFunctionProperty(ctor, BLOB_TAG, ConstructorId_slice, "slice", 3);
super.fillConstructorProperties(ctor);
}
@Override
protected void initPrototypeId(int id) {
String s;
int arity;
switch (id) {
case Id_constructor: arity=1; s="constructor"; break;
case Id_toString: arity=0; s="toString"; break;
case Id_toSource: arity=0; s="toSource"; break;
case Id_valueOf: arity=0; s="valueOf"; break;
case Id_byteAt: arity=1; s="byteAt"; break;
case Id_intAt: arity=1; s="intAt"; break;
case Id_indexOf: arity=1; s="indexOf"; break;
case Id_lastIndexOf: arity=1; s="lastIndexOf"; break;
case Id_split: arity=2; s="split"; break;
case Id_concat: arity=1; s="concat"; break;
case Id_slice: arity=2; s="slice"; break;
case Id_equals: arity=1; s="equals"; break;
default: throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(BLOB_TAG, id, s, arity);
}
@Override
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
if (!f.hasTag(BLOB_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
again:
for(;;) {
switch (id) {
case ConstructorId_byteAt:
case ConstructorId_intAt:
case ConstructorId_indexOf:
case ConstructorId_lastIndexOf:
case ConstructorId_split:
case ConstructorId_concat:
case ConstructorId_slice: {
thisObj = realThis(args[0], f);
Object[] newArgs = new Object[args.length-1];
for (int i=0; i < newArgs.length; i++)
newArgs[i] = args[i+1];
args = newArgs;
id = -id;
continue again;
}
case Id_constructor: {
if ( args.length > 0 ) {
/*if ( args[0] instanceof NativeNumber ) {
byte b = (byte) ScriptRuntime.toInt32( args[0] )-Byte.MIN_VALUE;
return new NativeString(b);
} else if ( args[0] instanceof NativeArray ) {
byte[] ba = new byte[#];
for (long i = 0; i < ba.length; i++) {
Object bo = NativeArray.getElm(cx, args[0], i);
if (!(bo instanceof NativeNumber))
break;
byte b = (byte) ScriptRuntime.toInt32( bo )-Byte.MIN_VALUE;
return new NativeBlob(b);
}
}*/
byte[] b = nativeConvert( args[0] );
return new NativeBlob(b);
} else {
return NativeBlob.newEmpty();
}
}
case Id_toString:
return thisObj.toString();
case Id_valueOf:
return realThis(thisObj, f);
case Id_toSource: {
byte[] b = realThis(thisObj, f).bytes;
StringBuffer sb = new StringBuffer("(new Blob([]))");
for (int i = 0; i < b.length; i++) {
if (i > 0)
sb.insert(sb.length()-3, ", ");
sb.insert(sb.length()-3, Integer.toString(byteToInt(b[i])));
}
return sb.toString();
}
case Id_byteAt:
case Id_intAt: {
byte[] target = realThis(thisObj, f).bytes;
double pos = ScriptRuntime.toInteger(args, 0);
if (pos < 0 || pos >= target.length) {
if (id == Id_byteAt) return NativeBlob.newEmpty();
else return ScriptRuntime.NaNobj;
}
byte b = target[(int)pos];
if (id == Id_byteAt) return new NativeBlob(b);
else return ScriptRuntime.wrapInt(byteToInt(b));
}
case Id_indexOf:
case Id_lastIndexOf:
if ( args.length == 0 )
break;
byte[] needle = nativeConvert(args[0]);
int offset = 0;
if ( args.length > 1 )
offset = ScriptRuntime.toInt32( args[1] );
if ( id != Id_lastIndexOf )
return ScriptRuntime.wrapInt(js_indexOf(realThis(thisObj, f).bytes, needle, offset));
return ScriptRuntime.wrapInt(js_lastIndexOf(realThis(thisObj, f).bytes, needle, offset));
case Id_split:
return js_split(cx, scope, realThis(thisObj, f).bytes, args);
case Id_concat:
return new NativeBlob(js_concat(realThis(thisObj, f).bytes, args));
case Id_slice:
return js_slice(realThis(thisObj, f).bytes, args);
case Id_equals: {
boolean eq = false;
byte[] b1 = realThis(thisObj, f).bytes;
byte[] b2;
if(args[0] instanceof NativeBlob) {
b2 = ((NativeBlob)args[0]).bytes;
if (b1.length != b2.length)
break; // short circut if different byte lengths
for (int i = 0; i < b2.length; i++)
if ( b1[i] != b2[i] )
break;
eq = true;
}
return ScriptRuntime.wrapBoolean(eq);
}
}
throw new IllegalArgumentException(String.valueOf(id));
}
}
private static NativeBlob realThis(Object thisObj, IdFunctionObject f) {
if (!(thisObj instanceof NativeBlob))
throw incompatibleCallError(f);
return (NativeBlob)thisObj;
}
private static byte[] nativeConvert(Object o) {
if(o instanceof NativeBlob)
return ((NativeBlob)o).bytes;
//if(o instanceof NativeNumber) {
if( ScriptRuntime.typeof(o).equals("number") ) {
int ii = ScriptRuntime.toInt32( o );
byte[] b = new byte[1];
b[0] = intToByte(ii);
return b;
}
//if(o instanceof NativeArray) {
if( ScriptRuntime.isArrayObject(o) ) {
Object[] a = ScriptRuntime.getArrayElements((Scriptable)o);
//NativeArray a = (NativeArray) o;
byte[] ba = new byte[a.length];
for (int i = 0; i < a.length; i++) {
//Object bo = ScriptRuntime.getObjectIndex(o, i, cx);//NativeArray.getElm(cx, (Scriptable)a, (long)i);
Object bo = a[i];
if ( !ScriptRuntime.typeof(bo).equals("number") )
throw ScriptRuntime.typeError("Contents of data array used as argument to blob method was not entirely numbers");
int ii = ScriptRuntime.toInt32( bo );
byte b = intToByte(ii);
ba[i] = b;
}
return ba;
}
throw ScriptRuntime.typeError("Invalid data type used as argument to a blob method");
}
private static int byteToInt(byte b) {
Byte bb = new Byte(b);
int bi = bb.intValue();
Byte byteMin = new Byte(Byte.MIN_VALUE);
int bmin = byteMin.intValue();
return bi-bmin;
}
private static byte intToByte(int i) {
int bmax = Byte.MAX_VALUE-Byte.MIN_VALUE;//(new Byte(Byte.MAX_VALUE-Byte.MIN_VALUE)).intValue();
int bmin = (new Byte(Byte.MIN_VALUE)).intValue();
if ( i > bmax )
throw ScriptRuntime.typeError("Integer representation of byte to high.");
byte b = (byte)(i+bmin);
return b;
}
@Override
public String toString() {
return "[Blob length=" + bytes.length + "]";
}
@Override
public Object get(int index, Scriptable start) {
if (0 <= index && index < bytes.length) {
return new NativeBlob(bytes[index]);
}
return super.get(index, start);
}
@Override
public void put(int index, Scriptable start, Object value) {
if (0 <= index && index < bytes.length) {
return;
}
super.put(index, start, value);
}
private static int js_indexOf(byte[] target, byte[] search, int begin2) {
double begin = (double) begin2;
if (begin > target.length - search.length) {
return -1;
} else {
if (begin < 0)
begin = 0;
// byte arrays have no indexOf like Strings to
// Enter long byte searching code
look:
for (int a = (int)begin; a < (int)target.length - search.length; a++) {
for (int b = 0; b < (int)search.length; b++ ) {
if ( target[a+b] != search[b] )
continue look; // Not a match, move on
}
// This code is only reached if the loop above finds a complete match
return a;
}
return -1;
}
}
private static int js_lastIndexOf(byte[] target, byte[] search, int end2) {
double end = (double) end2;
if (end != end || end > target.length)
end = target.length;
else if (end < 0)
end = 0;
look:
for (int a = (int)(end-search.length); a >= 0; a
for (int b = 0; b < (int)search.length; b++ ) {
if ( target[a+b] != search[b] )
continue look; // Not a match, move on
}
// This code is only reached if the loop above finds a complete match
return a;
}
return -1;
}
private static Object js_split(Context cx, Scriptable scope, byte[] target, Object[] args) {
// Mostly based on NativeString#js_split
// create an empty Array to return;
Scriptable top = getTopLevelScope(scope);
Scriptable result = ScriptRuntime.newObject(cx, top, "Array", null);
// return an array consisting of the target if no separator given
// don't check against undefined, because we want
// 'fooundefinedbar'.split(void 0) to split to ['foo', 'bar']
if (args.length < 1) {
result.put(0, result, new NativeBlob(target));
return result;
}
// Use the second argument as the split limit, if given.
boolean limited = (args.length > 1) && (args[1] != Undefined.instance);
long limit = 0; // Initialize to avoid warning.
if (limited) {
/* Clamp limit between 0 and 1 + string length. */
limit = ScriptRuntime.toUint32(args[1]);
if (limit > target.length)
limit = 1 + target.length;
}
byte[] separator = nativeConvert(args[0]);
int[] matchlen = new int[1];
matchlen[0] = separator.length;
// split target with separator
int[] ip = { 0 };
int match;
int len = 0;
boolean[] matched = { false };
byte[][][] parens = { null };
// ToDo: split isn't finished, this portion is majorly different than string split code
*//*
/*
* Deviate from ECMA to imitate Perl, which omits a final
* split unless a limit argument is given and big enough.
if (!limited && ip[0] == target.length)
break;
}
}*/
return result;
}
private static byte[] js_concat(byte[] target, Object[] args) {
int N = args.length;
if (N == 0) { return target; }
else if (N == 1) {
byte[] arg = nativeConvert(args[0]);
byte[] newblob = Arrays.copyOf(target, target.length+arg.length);
for (int i = 0; i != arg.length; ++i)
newblob[target.length+i] = arg[i];
return newblob;
}
// Find total capacity for the final blob
int size = target.length;
byte[][] argsAsBytes = new byte[N][];
for (int i = 0; i != N; ++i) {
byte[] b = nativeConvert(args[i]);
argsAsBytes[i] = b;
size += b.length;
}
byte[] result = Arrays.copyOf(target, size);
int index = target.length;
for (int byteArrayN = 0; byteArrayN != N; ++byteArrayN) {
byte[] b = argsAsBytes[byteArrayN];
for (int i = 0; i != b.length; ++i, ++index)
result[index] = b[i];
}
return result;
}
private static byte[] js_slice(byte[] target, Object[] args) {
// Based on NativeString#js_slice
if (args.length != 0) {
double begin = ScriptRuntime.toInteger(args[0]);
double end;
int length = target.length;
if (begin < 0) {
begin += length;
if (begin < 0)
begin = 0;
} else if (begin > length) {
begin = length;
}
if (args.length == 1) {
end = length;
} else {
end = ScriptRuntime.toInteger(args[1]);
if (end < 0) {
end += length;
if (end < 0)
end = 0;
} else if (end > length) {
end = length;
}
if (end < begin)
end = begin;
}
return Arrays.copyOfRange(target, (int)begin, (int)(end-begin));
}
return target;
}
// #string_id_map#
@Override
protected int findPrototypeId(String s) {
int id;
//
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 5: c=s.charAt(1);
if (c=='l') { X="slice";id=Id_slice; }
else if (c=='n') { X="intAt";id=Id_intAt; }
else if (c=='p') { X="split";id=Id_split; }
break L;
case 6: c=s.charAt(0);
if (c=='b') { X="byteAt";id=Id_byteAt; }
else if (c=='c') { X="concat";id=Id_concat; }
else if (c=='e') { X="equals";id=Id_equals; }
break L;
case 7: c=s.charAt(0);
if (c=='i') { X="indexOf";id=Id_indexOf; }
else if (c=='v') { X="valueOf";id=Id_valueOf; }
break L;
case 8: c=s.charAt(3);
if (c=='o') { X="toSource";id=Id_toSource; }
else if (c=='t') { X="toString";id=Id_toString; }
break L;
case 11: c=s.charAt(0);
if (c=='c') { X="constructor";id=Id_constructor; }
else if (c=='l') { X="lastIndexOf";id=Id_lastIndexOf; }
break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
break L0;
}
// #/generated#
return id;
}
private static final int
Id_constructor = 1,
Id_toString = 2,
Id_toSource = 3,
Id_valueOf = 4,
Id_byteAt = 5,
Id_intAt = 6,
Id_indexOf = 7,
Id_lastIndexOf = 8,
Id_split = 9,
Id_concat = 10,
Id_slice = 11,
Id_equals = 12,
MAX_PROTOTYPE_ID = 12;
// #/string_id_map#
private static final int
ConstructorId_byteAt = -Id_byteAt,
ConstructorId_intAt = -Id_intAt,
ConstructorId_indexOf = -Id_indexOf,
ConstructorId_lastIndexOf = -Id_lastIndexOf,
ConstructorId_split = -Id_split,
ConstructorId_concat = -Id_concat,
ConstructorId_slice = -Id_slice;
private byte[] bytes;
}
|
package com.onyx.util;
import com.onyx.descriptor.EntityDescriptor;
import com.onyx.exception.EntityException;
import com.onyx.exception.InvalidDataTypeForOperator;
import com.onyx.helpers.RelationshipHelper;
import com.onyx.persistence.IManagedEntity;
import com.onyx.persistence.context.SchemaContext;
import com.onyx.persistence.query.QueryCriteria;
import com.onyx.persistence.query.QueryCriteriaOperator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Set;
public class CompareUtil
{
/**
* This method compares but suppresses the error if values do not match
* @param object First object to compare
* @param object2 second object to compare
* @param throwError ignored, by virtue of this method being called we assume to suppress errors
* @return Whether the values are equal
*/
@SuppressWarnings("unused")
public static boolean compare(Object object, Object object2, boolean throwError)
{
try {
return compare(object, object2);
} catch (InvalidDataTypeForOperator invalidDataTypeForOperator) {
return false;
}
}
/**
* This method runs a compare but, swallows the errors.
*
* @param object First object
* @param object2 Second object to compare
* @return Whether they are equal or not
*/
public static boolean forceCompare(Object object, Object object2)
{
try {
return compare(object ,object2);
} catch (InvalidDataTypeForOperator invalidDataTypeForOperator) {
return false;
}
}
@SuppressWarnings("unchecked WeakerAccess")
public static Object castObject(Class clazz, Object object) {
Method method = null;
if(object == null)
{
if(clazz == int.class)
return 0;
else if(clazz == long.class)
return 0L;
else if(clazz == double.class)
return 0.0d;
else if(clazz == float.class)
return 0.0f;
else if(clazz == boolean.class)
return false;
else if(clazz == char.class)
return (char)0;
else if(clazz == byte.class)
return (byte)0;
else if(clazz == short.class)
return (short)0;
}
Class objectClass = object.getClass();
if(clazz == int.class && objectClass == Integer.class)
return object;
else if(clazz == long.class && objectClass == Long.class)
return object;
else if(clazz == double.class && objectClass == Double.class)
return object;
else if(clazz == float.class && objectClass == Float.class)
return object;
else if(clazz == boolean.class && objectClass == Boolean.class)
return object;
else if(clazz == char.class && objectClass == Character.class)
return object;
else if(clazz == byte.class && objectClass == Byte.class)
return object;
else if(clazz == short.class && objectClass == Short.class)
return object;
else if(clazz == int.class && objectClass == Long.class)
return ((Long)object).intValue();
else if(clazz == long.class && objectClass == Integer.class)
return ((Integer)object).longValue();
try {
if (clazz == Integer.class || clazz == int.class)
return Integer.valueOf(""+object);
else if (clazz == Long.class || clazz == long.class)
return Long.valueOf(""+object);
else if (clazz == Short.class || clazz == short.class)
return Short.valueOf(""+object);
else if (clazz == Byte.class || clazz == byte.class)
return Byte.valueOf(""+object);
else if (clazz == Boolean.class || clazz == boolean.class)
return Boolean.valueOf(""+object);
else if (clazz == Float.class || clazz == int.class)
return Float.valueOf(""+object);
else if (clazz == Double.class || clazz == double.class)
return Double.valueOf(""+object);
else if (clazz == Character.class || clazz == char.class) {
String stringVal = ""+object;
if(stringVal.length() > 0)
return stringVal.charAt(0);
return (char)0;
}
else if (clazz == String.class)
method = objectClass.getMethod("toString");
if (method == null)
return object;
return method.invoke(object);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
{
if (clazz == String.class)
return "" + object;
return object;
}
}
/**
* Compare 2 objects, they can be any data type supported by the database
*
* @param object First object to compare
* @param object2 second object to compare
* @return Whether the values are equal
*/
@SuppressWarnings({"unchecked", "WeakerAccess"})
public static boolean compare(Object object, Object object2) throws InvalidDataTypeForOperator
{
if(object == object2)
return true;
// If the objects do not match, cast it to the correct object
if(object2 != null
&& object != null
&& !object2.getClass().isAssignableFrom(object.getClass()))
object2 = castObject(object.getClass(), object2);
// This was added because string.equals is much more efficient than using comparable.
// Comparable iterated through the entire character array whereas .equals does not.
if(object instanceof String &&
object2 instanceof String)
return object.equals(object2);
else if(object instanceof Comparable
&& object2 instanceof Comparable)
return ((Comparable) object).compareTo(object2) == 0;
// Null checkers
else if(object instanceof String && object == QueryCriteria.NULL_STRING_VALUE)
return object2 == null;
else if(object instanceof Double && (Double)object == QueryCriteria.NULL_DOUBLE_VALUE)
return object2 == null;
else if(object instanceof Long && (Long)object == QueryCriteria.NULL_LONG_VALUE)
return object2 == null;
else if(object instanceof Integer && (Integer)object == QueryCriteria.NULL_INTEGER_VALUE)
return object2 == null;
else if(object instanceof Boolean && object == QueryCriteria.NULL_BOOLEAN_VALUE && (object2 instanceof Boolean || object2 == null))
return object2 == null;
else if(object instanceof Date && object == QueryCriteria.NULL_DATE_VALUE)
return object2 == null;
else if(object2 == null && object instanceof Date && ((Date)object).getTime() == QueryCriteria.NULL_DATE_VALUE.getTime())
return true;
else if(object == null && object2 != null)
return false;
else if(object != null && object2 == null)
return false;
else if(object != null && object2 != null)
return object.equals(object2);
// Comparison operator was not found, we should throw an exception because the data types are not supported
throw new InvalidDataTypeForOperator(InvalidDataTypeForOperator.INVALID_DATA_TYPE_FOR_OPERATOR);
}
/**
* Compare without throwing exception
*
* @param object First object to compare
* @param object2 Second object to compare
* @param operator Operator to compare against
*
* @return If the critieria meet return true
*/
public static boolean forceCompare(Object object, Object object2, QueryCriteriaOperator operator)
{
try {
return compare(object, object2, operator);
} catch (InvalidDataTypeForOperator invalidDataTypeForOperator) {
return false;
}
}
/**
* Generic method use to compare values with a given operator
*
* @param object First object to compare
* @param object2 second object to compare
* @param operator Any QueryCriteriaOperator
* @return whether the objects meet the criteria of the operator
* @throws InvalidDataTypeForOperator If the values cannot be compared
*/
@SuppressWarnings("unchecked")
public static boolean compare(Object object, Object object2, QueryCriteriaOperator operator) throws InvalidDataTypeForOperator
{
// If the objects do not match, cast it to the correct object
if(object2 != null
&& object != null
&& !object2.getClass().isAssignableFrom(object.getClass()))
object2 = castObject(object.getClass(), object2);
if(operator == QueryCriteriaOperator.NOT_NULL)
return (object2 != null);
else if (operator == QueryCriteriaOperator.IS_NULL)
return (object2 == null);
// Equal - this should take a generic object key
else if(operator == QueryCriteriaOperator.EQUAL)
return compare(object, object2);
// Not equal - this should take a generic object key
else if(operator == QueryCriteriaOperator.NOT_EQUAL)
return !compare(object, object2);
// In, the first parameter must be a list of items if using the list key
else if(operator == QueryCriteriaOperator.IN && object instanceof List)
{
List values = (List)object;
for(Object value : values)
{
if(compare(value, object2))
{
return true;
}
}
return false;
}
// Not in, the first parameter must be a list of items if using the list key
else if(operator == QueryCriteriaOperator.NOT_IN && object instanceof List)
{
List values = (List)object;
for(Object value : values)
{
if(compare(value, object2))
{
return false;
}
}
return true;
}
// Contains , only valid for strings
else if ((operator == QueryCriteriaOperator.CONTAINS || operator == QueryCriteriaOperator.NOT_CONTAINS)
&& object instanceof String
&& (object2 instanceof String || object2 == null))
{
if(object2 == null && object == QueryCriteria.NULL_STRING_VALUE)
{
return (operator == QueryCriteriaOperator.CONTAINS);
}
else if(object2 == null)
{
return !(operator == QueryCriteriaOperator.CONTAINS);
}
boolean retVal = ((String) object2).contains((String) object);
return (operator == QueryCriteriaOperator.CONTAINS) == retVal;
}
// Like, only valid for strings
else if ((operator == QueryCriteriaOperator.LIKE || operator == QueryCriteriaOperator.NOT_LIKE)
&& object instanceof String && (object2 instanceof String || object2 == null))
{
if(object2 == null && object == QueryCriteria.NULL_STRING_VALUE)
{
return (operator == QueryCriteriaOperator.LIKE);
}
else if(object2 == null)
{
return !(operator == QueryCriteriaOperator.LIKE);
}
boolean retVal = ((String) object2).equalsIgnoreCase((String) object);
return (operator == QueryCriteriaOperator.LIKE) == retVal;
}
// Starts with, only valid for strings
else if ((operator == QueryCriteriaOperator.STARTS_WITH || operator == QueryCriteriaOperator.NOT_STARTS_WITH)
&& (object instanceof String || object == null)
&& (object2 instanceof String || object2 == null))
{
if(object2 == null && object == QueryCriteria.NULL_STRING_VALUE)
{
return (operator == QueryCriteriaOperator.STARTS_WITH);
}
else if(object2 == null)
{
return !(operator == QueryCriteriaOperator.STARTS_WITH);
}
else if(object == null)
{
return !(operator == QueryCriteriaOperator.STARTS_WITH);
}
boolean retVal = ((String) object2).startsWith((String) object);
return (operator == QueryCriteriaOperator.STARTS_WITH) == retVal;
}
// Not in, the first parameter must be a list of items if using the list key
else if (operator == QueryCriteriaOperator.STARTS_WITH || operator == QueryCriteriaOperator.NOT_STARTS_WITH)
{
List values = (List)object;
boolean startsWith = false;
for(Object value : values)
{
if(object2 == null && object == QueryCriteria.NULL_STRING_VALUE)
{
return (operator == QueryCriteriaOperator.STARTS_WITH);
}
else if(object2 == null)
{
return !(operator == QueryCriteriaOperator.STARTS_WITH);
}
else if(object == null)
{
return !(operator == QueryCriteriaOperator.STARTS_WITH);
}
if (((String) object2).startsWith((String) value))
{
startsWith = true;
}
}
return (operator == QueryCriteriaOperator.STARTS_WITH) == startsWith;
}
// Matches, Use a regex, only valid with strings
else if ((operator == QueryCriteriaOperator.MATCHES || operator == QueryCriteriaOperator.NOT_MATCHES)
&& object instanceof String && (object2 instanceof String || object2 == null))
{
if(object2 == null && object == QueryCriteria.NULL_STRING_VALUE)
{
return (operator == QueryCriteriaOperator.MATCHES);
}
else if(object2 == null)
{
return !(operator == QueryCriteriaOperator.MATCHES);
}
return (operator == QueryCriteriaOperator.MATCHES) == ((String) object2).matches((String) object);
}
// Greater than, valid for strings, Long, long, Integer, int, Double, double
else if(operator == QueryCriteriaOperator.GREATER_THAN)
{
if(object == null && object2 == null)
{
return false;
}
if(object2 == null)
{
return false;
}
else if(object == null)
{
return true;
}
else if(object instanceof Comparable
&& object2 instanceof Comparable)
{
return ((Comparable) object2).compareTo(object) > 0;
}
return false;
}
// Greater than, valid for strings, Long, long, Integer, int, Double, double
else if(operator == QueryCriteriaOperator.LESS_THAN)
{
if(object == null && object2 == null)
{
return false;
}
if(object2 == null)
{
return true;
}
else if(object == null)
{
return false;
}
else if(object instanceof Comparable
&& object2 instanceof Comparable)
{
return ((Comparable) object).compareTo(object2) > 0;
}
return false;
}
// Greater than, valid for strings, Long, long, Integer, int, Double, double
else if(operator == QueryCriteriaOperator.LESS_THAN_EQUAL)
{
if(object == null && object2 == null)
{
return true;
}
if(object2 == null)
{
return false;
}
else if(object == null)
{
return true;
}
else if(object instanceof Comparable
&& object2 instanceof Comparable)
{
return ((Comparable) object).compareTo(object2) >= 0;
}
return false;
}
// Greater than, valid for strings, Long, long, Integer, int, Double, double
else if(operator == QueryCriteriaOperator.GREATER_THAN_EQUAL)
{
if(object == null && object2 == null)
{
return true;
}
if(object2 == null)
{
return false;
}
else if(object == null)
{
return true;
}
else if(object instanceof Comparable
&& object2 instanceof Comparable)
{
return ((Comparable) object2).compareTo(object) >= 0;
}
return false;
}
// Comparison operator was not found, we should throw an exception because the data types are not supported
throw new InvalidDataTypeForOperator(InvalidDataTypeForOperator.INVALID_DATA_TYPE_FOR_OPERATOR);
}
/**
* Relationship meets critieria. This method will hydrate a relationship for an entity and
* check its critieria to ensure the critieria is met
*
* @param entity Original entity containing the relationship. This entity may or may not have
* hydrated relationships. For that reason we have to go back to the store to
* retrieve the relationship entitities.
*
* @param entityReference Used for quick reference so we do not have to retrieve the entitiies
* reference before retrieving the relationship.
*
* @param criteria Critieria to check for to see if we meet the requirements
*
* @param context Schem context used to pull entity descriptors and record controllers and such
*
* @return Whether the relationship value has met all of the critieria
*
* @throws EntityException Something bad happened.
*
* @since 1.3.0 - Used to remove the dependency on relationship scanners and to allow query caching
* to do a quick reference to see if newly saved entities meet the critieria
*/
private static boolean relationshipMeetsCritieria(IManagedEntity entity, Object entityReference, QueryCriteria criteria, SchemaContext context) throws EntityException
{
boolean meetsCritiera = false;
final QueryCriteriaOperator operator = criteria.getOperator();
// Grab the relationship from the store
final List<IManagedEntity> relationshipEntities = RelationshipHelper.getRelationshipForValue(entity, entityReference, criteria.getAttribute(), context);
// If there are relationship values, check to see if they meet critieria
if(relationshipEntities.size() > 0)
{
String[] items = criteria.getAttribute().split("\\.");
String attribute = items[items.length - 1];
final OffsetField offsetField = ReflectionUtil.getOffsetField(relationshipEntities.get(0).getClass(), attribute);
// All we need is a single match. If there is a relationship that meets the criteria, move along
for(IManagedEntity relationshipEntity : relationshipEntities)
{
meetsCritiera = CompareUtil.compare(criteria.getValue(), ReflectionUtil.getAny(relationshipEntity, offsetField), operator);
if(meetsCritiera)
break;
}
}
return meetsCritiera;
}
/**
* Entity meets the query critieria. This method is used to determine whether the entity meets all the
* critieria of the query. It was implemented so that we no longer have logic in the query controller
* to sift through scans. We can now only perform a full table scan once.
*
* @param allCritieria Contribed list of criteria to
* @param rootCriteria Critieria to verify whether the entity meets
* @param entity Entity to check for criteria
* @param entityReference The entities reference
* @param context Schema context used to pull entity descriptors, and such
* @param descriptor Quick reference to the entities descriptor so we do not have to pull it from the schema context
* @return Whether the entity meets all the critieria.
* @throws EntityException Cannot hydrate or pull an attribute from an entity
*
* @since 1.3.0 Simplified query criteria management
*/
public static boolean meetsCriteria(Set<QueryCriteria> allCritieria, QueryCriteria rootCriteria, IManagedEntity entity, Object entityReference, SchemaContext context, EntityDescriptor descriptor) throws EntityException {
boolean subCreriaMet;
// Iterate through
for(QueryCriteria criteria1 : allCritieria)
{
if(criteria1.getAttribute().contains("."))
{
// Compare operator for relationship object
subCreriaMet = relationshipMeetsCritieria(entity, entityReference, criteria1, context);
}
else
{
// Compare operator for attribute object
if(criteria1.getAttributeDescriptor() == null)
criteria1.setAttributeDescriptor(descriptor.getAttributes().get(criteria1.getAttribute()));
final OffsetField offsetField = criteria1.getAttributeDescriptor().getField();
subCreriaMet = CompareUtil.compare(criteria1.getValue(), ReflectionUtil.getAny(entity, offsetField), criteria1.getOperator());
}
criteria1.meetsCritieria = subCreriaMet;
}
return calculateCritieriaMet(rootCriteria);
}
/**
* Calculates the result of the parent critieria and correlates
* its set of children criteria. A pre-requisite to invoking this method
* is that all of the criteria have the meet criteria field set and
* it does NOT take into account the not modifier in the pre-requisite.
*
*
* @param criteria Root critiera to check. This maintains the order of operations
* @return Whether all the crierita are met taking into account the order of operations
* and the not() modifier
*
* @since 1.3.0 Added to enhance insertion based criteria checking
*/
private static boolean calculateCritieriaMet(QueryCriteria criteria)
{
boolean meetsCritieria = criteria.meetsCritieria;
if(criteria.getSubCriteria().size() > 0) {
for (QueryCriteria subCritieria : criteria.getSubCriteria()) {
if (subCritieria.isOr()) {
meetsCritieria = (calculateCritieriaMet(subCritieria) || meetsCritieria);
} else {
meetsCritieria = (calculateCritieriaMet(subCritieria) && meetsCritieria);
}
}
}
if(criteria.isNot())
meetsCritieria = !meetsCritieria;
return meetsCritieria;
}
}
|
package org.javarosa.user.view;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import org.javarosa.core.JavaRosaServiceProvider;
import org.javarosa.core.api.IActivity;
import org.javarosa.core.api.IView;
import org.javarosa.user.model.User;
import org.javarosa.user.storage.UserRMSUtility;
import org.javarosa.user.utility.LoginContext;
import de.enough.polish.ui.FramedForm;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TextField;
public class LoginForm extends FramedForm implements IView {
private final static int DEFAULT_COMMAND_PRIORITY = 1;
// #if javarosa.login.demobutton
private StringItem demoButton;
public final static Command CMD_DEMO_BUTTON = new Command(JavaRosaServiceProvider.instance().localize("menu.Demo"),
Command.ITEM, DEFAULT_COMMAND_PRIORITY);
// #endif
public final static Command CMD_CANCEL_LOGIN = new Command(JavaRosaServiceProvider.instance().localize("menu.Exit"),
Command.SCREEN, DEFAULT_COMMAND_PRIORITY);
public final static Command CMD_LOGIN_BUTTON = new Command(JavaRosaServiceProvider.instance().localize("menu.Login"),
Command.ITEM, DEFAULT_COMMAND_PRIORITY);
private StringItem loginButton;
private TextField usernameField;
private TextField passwordField;
private UserRMSUtility userRMS;
private User loggedInUser;
private IActivity parent;
// context attributes
private final static String CTX_USERNAME = "username";
private final static String CTX_PASSWORD = "password";
private final static String CTX_COMMCARE_VERSION = "COMMCARE_VERSION";
private final static String CTX_COMMCARE_BUILD = "COMMCARE_BUILD";
private final static String CTX_JAVAROSA_BUILD = "JAVAROSA_BUILD";
/**
* @param loginActivity
* @param title
*/
private final static int DEFAULT_ADMIN_USERID = -1;
public LoginForm(IActivity loginActivity) {
super(JavaRosaServiceProvider.instance().localize("form.login.login"));
init(loginActivity);
}
/**
* @param loginActivity
* @param title
*/
public LoginForm(IActivity loginActivity, String title) {
super(title);
init(loginActivity);
}
/**
* @param loginActivity
*/
private void init(IActivity loginActivity) {
this.parent = loginActivity;
this.userRMS = new UserRMSUtility(UserRMSUtility.getUtilityName());
// #debug debug
System.out.println("userRMS:" + this.userRMS);
boolean recordsExist = this.userRMS.getNumberOfRecords() > 0;
// #debug debug
System.out.println("records in RMS:" + recordsExist);
if (!recordsExist && (loginActivity != null)) {
this.loggedInUser = getLoggedInUser(loginActivity);
this.userRMS.writeToRMS(this.loggedInUser);
}
User tempUser = new User();
tempUser.setUsername("");// ? needed
if (recordsExist) {
// get first username from RMS
int userId = this.userRMS.getNextRecordID() - 1;
try {
this.userRMS.retrieveFromRMS(userId, tempUser);
} catch (Exception e) {
e.printStackTrace();
// do nothing for the user
}
}
initLoginControls(tempUser.getUsername());
showVersions();
}
/**
* @param username
*/
private void initLoginControls(String username) {
// create the username and password input fields
this.usernameField = new TextField(JavaRosaServiceProvider.instance().localize("form.login.username"), username, 50,
TextField.ANY);
this.passwordField = new TextField(JavaRosaServiceProvider.instance().localize("form.login.password"), "", 10,
TextField.PASSWORD);
// TODO:what this?
addCommand(CMD_CANCEL_LOGIN);
append(this.usernameField);
append(this.passwordField);
// set the focus on the password field
this.focus(this.passwordField);
this.passwordField.setDefaultCommand(CMD_LOGIN_BUTTON);
// add the login button
this.loginButton = new StringItem(null, JavaRosaServiceProvider.instance().localize("form.login.login"), Item.BUTTON);
append(this.loginButton);
this.loginButton.setDefaultCommand(CMD_LOGIN_BUTTON);
// #if javarosa.login.demobutton
this.demoButton = new StringItem(null, "DEMO", Item.BUTTON);
append(this.demoButton);
this.demoButton.setDefaultCommand(CMD_DEMO_BUTTON);
// #endif
}
private void showVersions() {
//#if javarosa.login.showbuild
String ccv = (String) this.parent.getActivityContext().getElement(
CTX_COMMCARE_VERSION);
String ccb = (String) this.parent.getActivityContext().getElement(
CTX_COMMCARE_BUILD);
String jrb = (String) this.parent.getActivityContext().getElement(
CTX_JAVAROSA_BUILD);
if (ccv != null && !ccv.equals("")) {
this.append(JavaRosaServiceProvider.instance().localize("form.login.commcareversion") + " " + ccv);
}
if ((ccb != null && !ccb.equals(""))
&& (jrb != null && !jrb.equals(""))) {
this.append(JavaRosaServiceProvider.instance().localize("form.login.buildnumber") + " " + ccb + "-" + jrb);
}
//#endif
}
/**
* @param loginActivity
* @return
*/
private User getLoggedInUser(IActivity loginActivity) {
String username = (String) loginActivity.getActivityContext()
.getElement(CTX_USERNAME);
String password = (String) loginActivity.getActivityContext()
.getElement(CTX_PASSWORD);
User user = new User(username, password, DEFAULT_ADMIN_USERID,
User.ADMINUSER);
return user;
}
/**
*
* After login button is clicked, activity asks form to validate user
*
* @return
*/
public boolean validateUser() {
String usernameEntered = this.usernameField.getString().trim();
String passwordEntered = this.passwordField.getString().trim();
// /find user in RMS:
User userInRMS = new User();
int index = 1;
while (index <= this.userRMS.getNumberOfRecords()) {
try {
this.userRMS.retrieveFromRMS(index, userInRMS);
} catch (Exception ioe) {
ioe.printStackTrace();
}
if (userInRMS.getUsername().equalsIgnoreCase(usernameEntered)) {
if (userInRMS.getPassword().equals(passwordEntered)) {
setLoggedInUser(userInRMS);
return true;
}
}
index++;
}
return false;
}
/**
* @param passwordMode
*/
public void setPasswordMode(String passwordMode) {
if (LoginContext.PASSWORD_FORMAT_NUMERIC.equals(passwordMode)) {
this.passwordField.setConstraints(TextField.PASSWORD
| TextField.NUMERIC);
} else if (LoginContext.PASSWORD_FORMAT_ALPHA_NUMERIC
.equals(passwordMode)) {
this.passwordField.setConstraints(TextField.PASSWORD);
}
}
/**
* @return
*/
public Alert successfulLoginAlert() {
// Clayton Sims - May 27, 2009 : I changed this back to not force it to be a J2ME Alert,
// so that polish could style it and it wouldn't look terrible. Is there a reason it
// was hardcoded to do that? I've seen this happen a few times before, so someone's clearly
// doing this for a reason.
//#style mailAlert
return new Alert(JavaRosaServiceProvider.instance().localize("form.login.login.successful"),
JavaRosaServiceProvider.instance().localize("form.login.loading.profile"), null, AlertType.CONFIRMATION);
}
public UserRMSUtility getUserRMS() {
return this.userRMS;
}
public String getPassWord() {
return this.passwordField.getString();
}
public String getUserName() {
return this.usernameField.getString();
}
public User getLoggedInUser() {
return this.loggedInUser;
}
public void setLoggedInUser(User loggedInUser) {
this.loggedInUser = loggedInUser;
}
public Object getScreenObject() {
return this;
}
public TextField getPasswordField() {
return this.passwordField;
}
public StringItem getLoginButton() {
return this.loginButton;
}
}
|
package jacobi.core.spatial.sort;
import static org.hamcrest.CoreMatchers.instanceOf;
import java.util.Arrays;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author Y.K. Chan
*
*/
public class HilbertSort3DTest {
@Test
public void shouldBeAbleToGenerateLowerBasis() {
IntFunction<String> toStr = i -> IntStream.range(0, 4)
.map(k -> (i >> 3 * k) % 8)
.mapToObj(j -> (j / 2 == 0 ? "L" : "U") + (j % 2 == 0 ? "L" : "U"))
.collect(Collectors.joining(","));
int base = this.curve();
int[] curves = new int[4];
for(int i = 0; i < 4; i++) {
int basis = this.rotate(base, i);
curves[basis % 8] = basis;
}
Assert.assertEquals("LU,LL,UL,UU", toStr.apply(curves[1]));
Assert.assertEquals("LL,UL,UU,LU", toStr.apply(curves[0]));
Assert.assertEquals("UL,UU,LU,LL", toStr.apply(curves[2]));
Assert.assertEquals("UU,LU,LL,UL", toStr.apply(curves[3]));
}
@Test
public void shouldBeAbleToReverseLowerBasis() {
IntFunction<String> toStr = i -> IntStream.range(0, 4)
.map(k -> (i >> 3 * k) % 8)
.mapToObj(j -> (j / 2 == 0 ? "L" : "U") + (j % 2 == 0 ? "L" : "U"))
.collect(Collectors.joining(","));
int base = this.curve();
int[] curves = new int[4];
for(int i = 0; i < 4; i++) {
int basis = this.rotate(base, i);
curves[basis % 8] = this.reverse(basis);
}
Assert.assertEquals("UU,UL,LL,LU", toStr.apply(curves[1]));
Assert.assertEquals("LU,UU,UL,LL", toStr.apply(curves[0]));
Assert.assertEquals("LL,LU,UU,UL", toStr.apply(curves[2]));
Assert.assertEquals("UL,LL,LU,UU", toStr.apply(curves[3]));
}
@Test
public void shouldBeAbleToGenerateAllBasisCurves() {
final int prime = this.curve();
final int[] basis = new int[16];
for(int i = 0; i < 4; i++){
int elevate = this.rotate(prime, i);
int start = elevate % 8;
// elevate stay
basis[2 * start] = this.duplex(elevate, false);
// elevate across
basis[2 * start + 1] = this.duplex(elevate, true);
int demote = this.rotate(prime + ELEVATE, i);
start = demote % 8;
// demote stay
basis[2 * start] = this.duplex(demote, false);
// demote across
basis[2 * start + 1] = this.duplex(demote, true);
}
for(int i = 0; i < basis.length; i++) {
String octal = Integer.toOctalString(basis[i]);
Assert.assertTrue(octal.endsWith(String.valueOf(i / 2)));
}
}
protected int duplex(int floor, boolean diag) {
int dir = floor % 8 < 4 ? 1 : -1;
int next = diag ? this.rotate(floor, 3) : this.reverse(floor);
return floor + ((next + dir * ELEVATE ) << 12);
}
protected int reverse(int code) {
int rev = 0;
for(int i = 0; i < 4; i++) {
rev += ( (code >> (9 - 3 * i)) % 8 ) << 3 * i ;
}
return rev;
}
protected int rotate(int code, int delta) {
for(int i = 0; i < delta; i++){
int mod = code % 8;
code = (code / 8) + (mod << 9);
}
return code;
}
protected int curve() {
return 1 + (0 << 3) + (2 << 6) + (3 << 9);
}
protected static final int ELEVATE = 4 + (4 << 3) + (4 << 6) + (4 << 9);
}
|
package net.jhoogland.jautomata.io;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import net.jhoogland.jautomata.ArrayAutomaton;
import net.jhoogland.jautomata.Automata;
import net.jhoogland.jautomata.Automaton;
import net.jhoogland.jautomata.HashTransducer;
import net.jhoogland.jautomata.ReverselyAccessibleAutomaton;
import net.jhoogland.jautomata.TLabel;
import net.jhoogland.jautomata.Transducer;
import net.jhoogland.jautomata.io.AcceptorIO.LoadedAutomaton;
import net.jhoogland.jautomata.operations.Operations;
import net.jhoogland.jautomata.semirings.BooleanSemiring;
import net.jhoogland.jautomata.semirings.RealSemiring;
import net.jhoogland.jautomata.semirings.Semiring;
/**
* This class contains static methods to read and write (weighted) transducers.
*
* @author Jasper Hoogland
*/
public class TransducerIO
{
/**
* Creates and returns a transducer from the specified reader.
* The semiring and input and output label formats are specified by the arguments.
*/
public static <I, O, K> Transducer<I, O, K> read(Reader reader, Semiring<K> semiring, Format<I> inputLabelFormat, Format<O> outputLabelFormat) throws IOException
{
return readATT(reader, semiring, inputLabelFormat, outputLabelFormat);
}
/**
* Creates and returns a transducer from the specified reader.
* The semiring is specified by the argument.
* An instance of {@link CharacterFormat} is used as input and output label formats.
*/
public static <K> Transducer<Character, Character, K> read(Reader reader, Semiring<K> semiring) throws IOException
{
return read(reader, semiring, new CharacterFormat(), new CharacterFormat());
}
/**
* Creates and returns an unweighted transducer from the specified reader.
* The input and output label formats are specified by the arguments.
*/
public static <I, O> Transducer<I, O, Boolean> readUnweighted(Reader reader, Format<I> inputLabelFormat, Format<O> outputLabelFormat) throws IOException
{
return read(reader, new BooleanSemiring(), inputLabelFormat, outputLabelFormat);
}
/**
* Creates and returns an unweighted transducer from the specified reader.
* An instance of {@link CharacterFormat} is used as input and output label formats.
*/
public static Transducer<Character, Character, Boolean> readUnweighted(Reader reader) throws IOException
{
return readUnweighted(reader, new CharacterFormat(), new CharacterFormat());
}
/**
* Creates and returns a weighted transducer over the real semiring from the specified reader.
* The input and output label formats are specified by the arguments.
*/
public static <I, O> Transducer<I, O, Double> readWeighted(Reader reader, Format<I> inputLabelFormat, Format<O> outputLabelFormat) throws IOException
{
return read(reader, new RealSemiring(), inputLabelFormat, outputLabelFormat);
}
/**
* Creates and returns a weighted transducer over the real semiring from the specified reader.
* An instance of {@link CharacterFormat} is used as input and output label formats.
*/
public static Transducer<Character, Character, Double> readWeighted(Reader reader) throws IOException
{
return readWeighted(reader, new CharacterFormat(), new CharacterFormat());
}
/**
* Writes the specified transducer to the specified writer.
* The input and output label formats are specified by the arguments.
*/
public static <I, O, K> void write(Automaton<TLabel<I, O>, K> transducer, Writer writer, Format<I> inputLabelFormat, Format<O> outputLabelFormat) throws FileNotFoundException
{
ReverselyAccessibleAutomaton<TLabel<I, O>, K> a = new ArrayAutomaton<TLabel<I, O>, K>(transducer.initialStates().size() > 1 ? Operations.singleInitialState(transducer) : transducer);
PrintWriter pw = writer instanceof PrintWriter ? (PrintWriter) writer : new PrintWriter(writer);
K one = transducer.semiring().one();
for (Object t : Automata.transitions(a))
{
String from = a.previousState(t).toString();
String iLabel = inputLabelFormat.format(a.label(t).in());
String oLabel = outputLabelFormat.format(a.label(t).out());
K weight = a.transitionWeight(t);
String weightStr = weight.equals(one) ? "" : " " + weight;
String to = a.nextState(t).toString();
pw.println(from + " " + to + " " + iLabel + " " + oLabel + weightStr);
}
for (Object s : a.finalStates())
{
K weight = a.finalWeight(s);
pw.println(s + (weight.equals(one) ? "" : " " + weight));
}
pw.close();
}
/**
* Writes the specified transducer to the specified writer.
* An instance of {@link CharacterFormat} is used as input and output label formats.
*/
public static <K> void write(Automaton<TLabel<Character, Character>, K> transducer, Writer writer, String format) throws FileNotFoundException
{
write(transducer, writer, new CharacterFormat(), new CharacterFormat());
}
private static <I, O, K> Transducer<I, O, K> readATT(Reader reader, Semiring<K> semiring, Format<I> inputLabelFormat, Format<O> outputLabelFormat) throws IOException
{
BufferedReader br = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
String line = br.readLine();
LoadedAutomaton<TLabel<I, O>, K> la = new LoadedAutomaton<TLabel<I, O>, K>(semiring);
while (line != null)
{
String[] fields = line.split(" ");
if (fields.length > 3)
{
Object weight = fields.length == 4 ? semiring.one() : Double.parseDouble(fields[4]);
I iLabel = inputLabelFormat.parse(fields[2]);
O oLabel = outputLabelFormat.parse(fields[3]);
String from = fields[0];
String to = fields[1];
la.addTransition(from, new TLabel<I, O>(iLabel, oLabel), (K) weight, to);
if (la.initialWeights.isEmpty())
la.addInitialState(from, semiring.one());
}
else
{
String state = fields[0];
Object weight = fields.length == 1 ? semiring.one() : Double.parseDouble(fields[1]);
la.addFinalState(state, (K) weight);
}
line = br.readLine();
}
br.close();
return new HashTransducer<I, O, K>(la);
}
}
|
package org.jbehave.core.model;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.jbehave.core.annotations.Parameter;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.model.TableTransformers.TableTransformer;
import org.jbehave.core.steps.ChainedRow;
import org.jbehave.core.steps.ConvertedParameters;
import org.jbehave.core.steps.ParameterControls;
import org.jbehave.core.steps.ParameterConverters;
import org.jbehave.core.steps.Parameters;
import org.jbehave.core.steps.Row;
import static java.lang.Boolean.parseBoolean;
import static java.util.regex.Pattern.DOTALL;
import static org.apache.commons.lang3.StringUtils.isEmpty;
public class ExamplesTable {
private static final Map<String, String> EMPTY_MAP = Collections.emptyMap();
private static final String EMPTY_VALUE = "";
public static final Pattern INLINED_PROPERTIES_PATTERN = Pattern.compile("\\{(.*?[^\\\\])\\}\\s*(.*)", DOTALL);
public static final ExamplesTable EMPTY = new ExamplesTable("");
private static final String HEADER_SEPARATOR = "|";
private static final String VALUE_SEPARATOR = "|";
private static final String IGNORABLE_SEPARATOR = "|
private final ParameterConverters parameterConverters;
private final Row defaults;
private final TableRows tableRows;
private final Deque<TableProperties> tablePropertiesQueue = new LinkedList<>();
private Map<String, String> namedParameters = new HashMap<>();
private ParameterControls parameterControls;
public ExamplesTable(String tableAsString) {
this(tableAsString, HEADER_SEPARATOR, VALUE_SEPARATOR,
new ParameterConverters(new LoadFromClasspath(), new TableTransformers()), new ParameterControls(),
new TableParsers(), new TableTransformers());
}
public ExamplesTable(String tableAsString, String headerSeparator, String valueSeparator,
ParameterConverters parameterConverters, ParameterControls parameterControls,
TableParsers tableParsers, TableTransformers tableTransformers) {
this(tableAsString, headerSeparator, valueSeparator, IGNORABLE_SEPARATOR, parameterConverters,
parameterControls, tableParsers, tableTransformers);
}
public ExamplesTable(String tableAsString, String headerSeparator, String valueSeparator,
String ignorableSeparator, ParameterConverters parameterConverters, ParameterControls parameterControls,
TableParsers tableParsers, TableTransformers tableTransformers) {
this.parameterConverters = parameterConverters;
this.parameterControls = parameterControls;
this.defaults = new ConvertedParameters(EMPTY_MAP, parameterConverters);
TablePropertiesQueue data = tableParsers.parseProperties(tableAsString, headerSeparator, valueSeparator, ignorableSeparator);
this.tablePropertiesQueue.addAll(data.getProperties());
String transformedTable = applyTransformers(tableTransformers, data.getTable(), tableParsers);
this.tableRows = tableParsers.parseRows(transformedTable, lastTableProperties());
}
ExamplesTable(TablePropertiesQueue tablePropertiesQueue, String headerSeparator, String valueSeparator,
String ignorableSeparator, ParameterConverters parameterConverters, ParameterControls parameterControls,
TableParsers tableParsers, TableTransformers tableTransformers) {
this.parameterConverters = parameterConverters;
this.parameterControls = parameterControls;
this.defaults = new ConvertedParameters(EMPTY_MAP, parameterConverters);
this.tablePropertiesQueue.addAll(tablePropertiesQueue.getProperties());
String transformedTable = applyTransformers(tableTransformers, tablePropertiesQueue.getTable(), tableParsers);
this.tableRows = tableParsers.parseRows(transformedTable, lastTableProperties());
}
private TableProperties lastTableProperties() {
return tablePropertiesQueue.getLast();
}
private ExamplesTable(ExamplesTable other, Row defaults) {
this.tableRows = new TableRows(other.tableRows.getHeaders(),
other.tableRows.getRows());
this.parameterConverters = other.parameterConverters;
this.tablePropertiesQueue.addAll(other.tablePropertiesQueue);
this.defaults = defaults;
}
private String applyTransformers(TableTransformers tableTransformers, String tableAsString,
TableParsers tableParsers) {
String transformedTable = tableAsString;
for (TableProperties properties : tablePropertiesQueue) {
String transformer = properties.getTransformer();
if (transformer != null) {
transformedTable = tableTransformers.transform(transformer, transformedTable, tableParsers, properties);
}
}
return transformedTable;
}
public ExamplesTable withDefaults(Parameters defaults) {
return new ExamplesTable(this, new ChainedRow(defaults, this.defaults));
}
public ExamplesTable withNamedParameters(Map<String, String> namedParameters) {
this.namedParameters = namedParameters;
return this;
}
public ExamplesTable withRowValues(int row, Map<String, String> values) {
getRow(row).putAll(values);
for (String header : values.keySet()) {
if (!getHeaders().contains(header)) {
getHeaders().add(header);
}
}
return this;
}
public ExamplesTable withRows(List<Map<String, String>> values) {
getHeaders().clear();
getHeaders().addAll(values.get(0).keySet());
tableRows.getRows().clear();
tableRows.getRows().addAll(values);
return this;
}
public Properties getProperties() {
return lastTableProperties().getProperties();
}
public List<String> getHeaders() {
return tableRows.getHeaders();
}
public Map<String, String> getRow(int row) {
if (row > tableRows.getRows().size() - 1) {
throw new RowNotFound(row);
}
Map<String, String> values = tableRows.getRows().get(row);
if (getHeaders().size() != values.keySet().size()) {
for (String header : getHeaders()) {
if (!values.containsKey(header)) {
values.put(header, EMPTY_VALUE);
}
}
}
return values;
}
public Parameters getRowAsParameters(int row) {
return getRowAsParameters(row, false);
}
public Parameters getRowAsParameters(int row, boolean replaceNamedParameters) {
Map<String, String> rowValues = getRow(row);
return createParameters(replaceNamedParameters ? replaceNamedParameters(rowValues) : rowValues);
}
private Map<String, String> replaceNamedParameters(Map<String, String> row) {
Map<String, String> replaced = new LinkedHashMap<>();
for (Entry<String, String> rowEntry : row.entrySet()) {
String replacedValue = rowEntry.getValue();
for (Entry<String, String> namedParameter : namedParameters.entrySet()) {
replacedValue = parameterControls.replaceAllDelimitedNames(replacedValue, namedParameter.getKey(),
namedParameter.getValue());
}
replaced.put(rowEntry.getKey(), replacedValue);
}
return replaced;
}
public int getRowCount() {
return tableRows.getRows().size();
}
public boolean metaByRow(){
return lastTableProperties().isMetaByRow();
}
public List<Map<String, String>> getRows() {
List<Map<String, String>> rows = new ArrayList<>();
for (int row = 0; row < getRowCount(); row++) {
rows.add(getRow(row));
}
return rows;
}
public List<Parameters> getRowsAsParameters() {
return getRowsAsParameters(false);
}
public List<Parameters> getRowsAsParameters(boolean replaceNamedParameters) {
List<Parameters> rows = new ArrayList<>();
for (int row = 0; row < getRowCount(); row++) {
rows.add(getRowAsParameters(row, replaceNamedParameters));
}
return rows;
}
public <T> List<T> getRowsAs(Class<T> type) {
return getRowsAs(type, new HashMap<String, String>());
}
public <T> List<T> getRowsAs(Class<T> type, Map<String, String> fieldNameMapping) {
List<T> rows = new ArrayList<>();
for (Parameters parameters : getRowsAsParameters()) {
rows.add(mapToType(parameters, type, fieldNameMapping));
}
return rows;
}
private <T> T mapToType(Parameters parameters, Class<T> type, Map<String, String> fieldNameMapping) {
try {
T instance = type.newInstance();
Map<String, String> values = parameters.values();
for (String name : values.keySet()) {
Field field = findField(type, name, fieldNameMapping);
Type fieldType = field.getGenericType();
Object value = parameters.valueAs(name, fieldType);
field.setAccessible(true);
field.set(instance, value);
}
return instance;
} catch (Exception e) {
throw new ParametersNotMappableToType(parameters, type, e);
}
}
private <T> Field findField(Class<T> type, String name, Map<String, String> fieldNameMapping)
throws NoSuchFieldException {
// Get field name from mapping, if specified
String fieldName = fieldNameMapping.get(name);
if (fieldName == null) {
fieldName = name;
}
// First look for fields annotated by @Parameter specifying the name
for (Field field : type.getDeclaredFields()) {
if (field.isAnnotationPresent(Parameter.class)) {
Parameter parameter = field.getAnnotation(Parameter.class);
if (fieldName.equals(parameter.name())) {
return field;
}
}
}
// Default to field matching given name
return findField(type, fieldName);
}
private Field findField(Class<?> type, String fieldName) throws NoSuchFieldException {
for (Field field : type.getDeclaredFields()) {
if (field.getName().equals(fieldName)) {
return field;
}
}
if (type.getSuperclass() != null) {
return findField(type.getSuperclass(), fieldName);
}
throw new NoSuchFieldException(fieldName);
}
private Parameters createParameters(Map<String, String> values) {
return new ConvertedParameters(new ChainedRow(new ConvertedParameters(values, parameterConverters), defaults),
parameterConverters);
}
public String getHeaderSeparator() {
return lastTableProperties().getHeaderSeparator();
}
public String getValueSeparator() {
return lastTableProperties().getValueSeparator();
}
public String asString() {
if (tableRows.getRows().isEmpty()) {
return EMPTY_VALUE;
}
return format();
}
public void outputTo(PrintStream output) {
output.print(asString());
}
private String format() {
StringBuilder sb = new StringBuilder();
for (TableProperties properties : tablePropertiesQueue) {
String propertiesAsString = properties.getPropertiesAsString();
if (!propertiesAsString.isEmpty()) {
sb.append("{").append(propertiesAsString).append("}").append(lastTableProperties().getRowSeparator());
}
}
for (String header : getHeaders()) {
sb.append(getHeaderSeparator()).append(header);
}
sb.append(getHeaderSeparator()).append(lastTableProperties().getRowSeparator());
for (Map<String, String> row : getRows()) {
for (String header : getHeaders()) {
sb.append(getValueSeparator()).append(row.get(header));
}
sb.append(getValueSeparator()).append(lastTableProperties().getRowSeparator());
}
return sb.toString();
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
@SuppressWarnings("serial")
public static class RowNotFound extends RuntimeException {
public RowNotFound(int row) {
super(Integer.toString(row));
}
}
@SuppressWarnings("serial")
public static class ParametersNotMappableToType extends RuntimeException {
public ParametersNotMappableToType(Parameters parameters, Class<?> type, Exception e) {
super(parameters.values() + " not mappable to type " + type, e);
}
}
public static final class TableProperties {
private static final String HEADER_SEPARATOR = "|";
private static final String VALUE_SEPARATOR = "|";
private static final String IGNORABLE_SEPARATOR = "|
private static final String COMMENT_SEPARATOR = "
private static final String HEADER_SEPARATOR_KEY = "headerSeparator";
private static final String VALUE_SEPARATOR_KEY = "valueSeparator";
private static final String IGNORABLE_SEPARATOR_KEY = "ignorableSeparator";
private static final String COMMENT_SEPARATOR_KEY = "commentSeparator";
private static final String ROW_SEPARATOR = "\n";
private final Properties properties = new Properties();
private final String propertiesAsString;
public TableProperties(Properties properties){
this.properties.putAll(properties);
if ( !this.properties.containsKey(HEADER_SEPARATOR_KEY) ){
this.properties.setProperty(HEADER_SEPARATOR_KEY, HEADER_SEPARATOR);
}
if ( !this.properties.containsKey(VALUE_SEPARATOR_KEY) ){
this.properties.setProperty(VALUE_SEPARATOR_KEY, VALUE_SEPARATOR);
}
if ( !this.properties.containsKey(IGNORABLE_SEPARATOR_KEY) ){
this.properties.setProperty(IGNORABLE_SEPARATOR_KEY, IGNORABLE_SEPARATOR);
}
if ( !this.properties.containsKey(COMMENT_SEPARATOR_KEY) ){
this.properties.setProperty(COMMENT_SEPARATOR_KEY, COMMENT_SEPARATOR);
}
StringBuilder propertiesAsStringBuilder = new StringBuilder();
for (Map.Entry<Object, Object> property : this.properties.entrySet()) {
propertiesAsStringBuilder.append(property.getKey()).append('=').append(property.getValue()).append(',');
}
propertiesAsString = propertiesAsStringBuilder.substring(0, propertiesAsStringBuilder.length() - 1);
}
public TableProperties(String propertiesAsString, String defaultHeaderSeparator, String defaultValueSeparator,
String defaultIgnorableSeparator) {
properties.setProperty(HEADER_SEPARATOR_KEY, defaultHeaderSeparator);
properties.setProperty(VALUE_SEPARATOR_KEY, defaultValueSeparator);
properties.setProperty(IGNORABLE_SEPARATOR_KEY, defaultIgnorableSeparator);
properties.putAll(parseProperties(propertiesAsString));
this.propertiesAsString = propertiesAsString;
}
private Map<String, String> parseProperties(String propertiesAsString) {
Map<String, String> result = new LinkedHashMap<>();
if (!isEmpty(propertiesAsString)) {
for (String propertyAsString : propertiesAsString.split("(?<!\\\\),")) {
String[] property = StringUtils.split(propertyAsString, "=", 2);
result.put(property[0].trim(), StringUtils.replace(property[1], "\\,", ",").trim());
}
}
return result;
}
public String getRowSeparator() {
return ROW_SEPARATOR;
}
public String getHeaderSeparator() {
return properties.getProperty(HEADER_SEPARATOR_KEY);
}
public String getValueSeparator() {
return properties.getProperty(VALUE_SEPARATOR_KEY);
}
public String getIgnorableSeparator() {
return properties.getProperty(IGNORABLE_SEPARATOR_KEY);
}
public String getCommentSeparator() {
return properties.getProperty(COMMENT_SEPARATOR_KEY);
}
public boolean isTrim() {
return parseBoolean(properties.getProperty("trim", "true"));
}
public boolean isMetaByRow(){
return parseBoolean(properties.getProperty("metaByRow", "false"));
}
public String getTransformer() {
return properties.getProperty("transformer");
}
public Properties getProperties() {
return properties;
}
public String getPropertiesAsString() {
return propertiesAsString;
}
}
static final class TablePropertiesQueue {
private final String table;
private final Deque<TableProperties> properties;
TablePropertiesQueue(String table, Deque<TableProperties> properties) {
this.table = table;
this.properties = properties;
}
String getTable() {
return table;
}
Deque<TableProperties> getProperties() {
return properties;
}
}
public static final class TableRows {
private final List<String> headers;
private final List<Map<String, String>> rows;
public TableRows(List<String> headers, List<Map<String, String>> rows) {
this.headers = headers;
this.rows = rows;
}
public List<String> getHeaders() {
return headers;
}
public List<Map<String, String>> getRows() {
return rows;
}
}
}
|
package org.jboss.as.jpa.messages;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.net.URLConnection;
import javax.ejb.EJBException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TransactionRequiredException;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.jandex.MethodInfo;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.vfs.VirtualFile;
@MessageLogger(projectCode = "WFLYJPA", length = 4)
public interface JpaLogger extends BasicLogger {
/**
* Default root level logger with the package name for he category.
*/
JpaLogger ROOT_LOGGER = Logger.getMessageLogger(JpaLogger.class, "org.jboss.as.jpa");
/**
* Logs a warning message indicating duplicate persistence.xml files were found.
*
* @param puName the persistence XML file.
* @param ogPuName the original persistence.xml file.
* @param dupPuName the duplicate persistence.xml file.
*/
@LogMessage(level = WARN)
@Message(id = 1, value = "Duplicate Persistence Unit definition for %s " +
"in application. One of the duplicate persistence.xml should be removed from the application." +
" Application deployment will continue with the persistence.xml definitions from %s used. " +
"The persistence.xml definitions from %s will be ignored.")
void duplicatePersistenceUnitDefinition(String puName, String ogPuName, String dupPuName);
/**
* Logs an informational message indicating the persistence.xml file is being read.
*
* @param puUnitName the persistence unit name.
*/
@LogMessage(level = INFO)
@Message(id = 2, value = "Read persistence.xml for %s")
void readingPersistenceXml(String puUnitName);
/**
* Logs an informational message indicating the service, represented by the {@code serviceName} parameter, is
* starting.
*
* @param serviceName the name of the service.
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 3, value = "Starting %s Service '%s'")
void startingService(String serviceName, String name);
/**
* Logs an informational message indicating the service, represented by the {@code serviceName} parameter, is
* stopping.
*
* @param serviceName the name of the service.
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 4, value = "Stopping %s Service '%s'")
void stoppingService(String serviceName, String name);
/**
* Logs an error message indicating an exception occurred while preloading the default persistence provider adapter module.
* Initialization continues after logging the error.
*
* @param cause the cause of the error.
*/
//@LogMessage(level = ERROR)
//@Message(id = 5, value = "Could not load default persistence provider adaptor module. Management attributes will not be registered for the adaptor")
//void errorPreloadingDefaultProviderAdaptor(@Cause Throwable cause);
/**
* Logs an error message indicating an exception occurred while preloading the default persistence provider module.
* Initialization continues after logging the error.
*
* @param cause the cause of the error.
*/
@LogMessage(level = ERROR)
@Message(id = 6, value = "Could not load default persistence provider module. ")
void errorPreloadingDefaultProvider(@Cause Throwable cause);
/**
* Logs an error message indicating the persistence unit was not stopped
*
* @param cause the cause of the error.
* @param name name of the persistence unit
*/
@LogMessage(level = ERROR)
@Message(id = 7, value = "Failed to stop persistence unit service %s")
void failedToStopPUService(@Cause Throwable cause, String name);
/**
* Creates an exception indicating a failure to get the module for the deployment unit represented by the
* {@code deploymentUnit} parameter.
*
* @param deploymentUnit the deployment unit that failed.
* @return a {@link org.jboss.as.server.deployment.DeploymentUnitProcessingException} for the error.
*/
@LogMessage(level = WARN)
@Message(id = 8, value = "Failed to get module attachment for %s")
void failedToGetModuleAttachment(DeploymentUnit deploymentUnit);
/**
* warn that the entity class could not be loaded with the
* {@link javax.persistence.spi.PersistenceUnitInfo#getClassLoader()}.
*
* @param cause the cause of the error.
* @param className the entity class name.
*/
//@LogMessage(level = WARN)
//@Message(id = 9, value = "Could not load entity class '%s', ignoring this error and continuing with application deployment")
//void cannotLoadEntityClass(@Cause Throwable cause, String className);
/**
* Logs an informational message indicating the persistence unit service is starting phase n of 2.
*
* @param phase is the phase number (1 or 2)
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 10, value = "Starting Persistence Unit (phase %d of 2) Service '%s'")
void startingPersistenceUnitService(int phase, String name);
/**
* Logs an informational message indicating the service is stopping.
*
* @param phase is the phase number (1 or 2)
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 11, value = "Stopping Persistence Unit (phase %d of 2) Service '%s'")
void stoppingPersistenceUnitService(int phase, String name);
/**
* Logs warning about unexpected problem gathering statistics.
*
* @param cause is the cause of the warning
*/
@LogMessage(level = WARN)
@Message(id = 12, value = "Unexpected problem gathering statistics")
void unexpectedStatisticsProblem(@Cause IllegalStateException cause);
/**
* Creates an exception indicating the inability ot add the integration, represented by the {@code name} parameter,
* module to the deployment.
*
* @param cause the cause of the error.
* @param name the name of the integration.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 13, value = "Could not add %s integration module to deployment")
RuntimeException cannotAddIntegration(@Cause Throwable cause, String name);
//@Message(id = 14, value = "Cannot change input stream reference.")
@Message(id = 15, value = "Container managed entity manager can only be closed by the container " +
"(will happen when @remove method is invoked on containing SFSB)")
IllegalStateException cannotCloseContainerManagedEntityManager();
/**
* Creates an exception indicating only ExtendedEntityMangers can be closed.
*
* @param entityManagerTypeName the entity manager type name.
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 16, value = "Can only close SFSB XPC entity manager that are instances of ExtendedEntityManager %s")
//RuntimeException cannotCloseNonExtendedEntityManager(String entityManagerTypeName);
@Message(id = 17, value = "Container managed entity manager can only be closed by the container " +
"(auto-cleared at tx/invocation end and closed when owning component is closed.)")
IllegalStateException cannotCloseTransactionContainerEntityManger();
/**
* Creates an exception indicating the inability to create an instance of the adapter class represented by the
* {@code className} parameter.
*
* @param cause the cause of the error.
* @param className the adapter class name.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 18, value = "Could not create instance of adapter class '%s'")
DeploymentUnitProcessingException cannotCreateAdapter(@Cause Throwable cause, String className);
/**
* Creates an exception indicating the application could not be deployed with the persistence provider, represented
* by the {@code providerName} parameter, packaged.
*
* @param cause the cause of the error.
* @param providerName the persistence provider.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 19, value = "Could not deploy application packaged persistence provider '%s'")
DeploymentUnitProcessingException cannotDeployApp(@Cause Throwable cause, String providerName);
/**
* Creates an exception indicating a failure to get the Hibernate session factory from the entity manager.
*
* @param cause the cause of the error.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 20, value = "Couldn't get Hibernate session factory from entity manager")
RuntimeException cannotGetSessionFactory(@Cause Throwable cause);
/**
* A message indicating the inability to inject a
* {@link javax.persistence.spi.PersistenceUnitTransactionType#RESOURCE_LOCAL} container managed EntityManager
* using the {@link javax.persistence.PersistenceContext} annotation.
*
* @return the message.
*/
@Message(id = 21, value = "Cannot inject RESOURCE_LOCAL container managed EntityManagers using @PersistenceContext")
String cannotInjectResourceLocalEntityManager();
/**
* Creates an exception indicating the inability to inject a
* {@link javax.persistence.spi.PersistenceUnitTransactionType#RESOURCE_LOCAL} entity manager, represented by the
* {@code unitName} parameter, using the {@code <persistence-context-ref>}.
*
* @param unitName the unit name.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
//@Message(id = 22, value = "Cannot inject RESOURCE_LOCAL entity manager %s using <persistence-context-ref>")
//DeploymentUnitProcessingException cannotInjectResourceLocalEntityManager(String unitName);
/**
* Creates an exception indicating the persistence provider adapter module, represented by the {@code adapterModule}
* parameter, had an error loading.
*
* @param cause the cause of the error.
* @param adapterModule the name of the adapter module.
* @param persistenceProviderClass the persistence provider class.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
//@Message(id = 23, value = "Persistence provider adapter module (%s) load error (class %s)")
//DeploymentUnitProcessingException cannotLoadAdapterModule(@Cause Throwable cause, String adapterModule, String persistenceProviderClass);
/**
* Creates an exception indicating the entity class could not be loaded with the
* {@link javax.persistence.spi.PersistenceUnitInfo#getClassLoader()}.
*
* @param cause the cause of the error.
* @param className the entity class name.
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 24, value = "Could not load entity class '%s' with PersistenceUnitInfo.getClassLoader()")
//RuntimeException cannotLoadEntityClass(@Cause Throwable cause, String className);
/**
* Creates an exception indicating the {@code injectionTypeName} could not be loaded from the JPA modules class
* loader.
*
* @param cause the cause of the error.
* @param injectionTypeName the name of the type.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 25, value = "Couldn't load %s from JPA modules classloader")
RuntimeException cannotLoadFromJpa(@Cause Throwable cause, String injectionTypeName);
/**
* Creates an exception indicating the module, represented by the {@code moduleId} parameter, could not be loaded
* for the adapter, represented by the {@code name} parameter.
*
* @param cause the cause of the error.
* @param moduleId the module id that was attempting to be loaded.
* @param name the name of the adapter.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 26, value = "Could not load module %s to add %s adapter to deployment")
RuntimeException cannotLoadModule(@Cause Throwable cause, ModuleIdentifier moduleId, String name);
/**
* Creates an exception indicating the persistence provider module, represented by the
* {@code persistenceProviderModule} parameter, had an error loading.
*
* @param cause the cause of the error.
* @param persistenceProviderModule the name of the adapter module.
* @param persistenceProviderClass the persistence provider class.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 27, value = "Persistence provider module load error %s (class %s)")
DeploymentUnitProcessingException cannotLoadPersistenceProviderModule(@Cause Throwable cause, String persistenceProviderModule, String persistenceProviderClass);
/**
* Creates an exception indicating the top of the stack could not be replaced because the stack is {@code null}.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 28, value = "Internal error: Cannot replace top of stack as stack is null (same as being empty).")
RuntimeException cannotReplaceStack();
/**
* Creates an exception indicating that both {@code key1} and {@code key2} cannot be specified for the object.
*
* @param key1 the first key/tag.
* @param value1 the first value.
* @param key2 the second key/tag.
* @param value2 the second value.
* @param parentTag the parent tag.
* @param object the object the values are being specified for.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 29, value = "Cannot specify both %s (%s) and %s (%s) in %s for %s")
DeploymentUnitProcessingException cannotSpecifyBoth(String key1, Object value1, String key2, Object value2, String parentTag, Object object);
/**
* Creates an exception indicating the extended persistence context for the SFSB already exists.
*
* @param puScopedName the persistence unit name.
* @param existingEntityManager the existing transactional entity manager.
* @param self the entity manager attempting to be created.
* @return an {@link javax.ejb.EJBException} for the error.
*/
@Message(id = 30, value = "Found extended persistence context in SFSB invocation call stack but that cannot be used " +
"because the transaction already has a transactional context associated with it. " +
"This can be avoided by changing application code, either eliminate the extended " +
"persistence context or the transactional context. See JPA spec 2.0 section 7.6.3.1. " +
"Scoped persistence unit name=%s, persistence context already in transaction =%s, extended persistence context =%s.")
EJBException cannotUseExtendedPersistenceTransaction(String puScopedName, EntityManager existingEntityManager, EntityManager self);
/**
* Creates an exception indicating the child could not be found on the parent.
*
* @param child the child that could not be found.
* @param parent the parent.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 31, value = "Could not find child '%s' on '%s'")
RuntimeException childNotFound(String child, VirtualFile parent);
/**
* Creates an exception indicating the class level annotation must provide the parameter specified.
*
* @param annotation the annotation.
* @param className the class name
* @param parameter the parameter.
* @return a string for the error.
*/
@Message(id = 32, value = "Class level %s annotation on class %s must provide a %s")
String classLevelAnnotationParameterRequired(String annotation, String className, String parameter);
/**
* A message indicating that the persistence unit, represented by the {@code path} parameter, could not be found at
* the current deployment unit, represented by the {@code deploymentUnit} parameter.
*
* @param puName the persistence unit name.
* @param deploymentUnit the deployment unit.
* @return the message.
*/
@Message(id = 33, value = "Can't find a persistence unit named %s in %s")
String persistenceUnitNotFound(String puName, DeploymentUnit deploymentUnit);
@Message(id = 34, value = "Can't find a persistence unit named %s#%s at %s")
IllegalArgumentException persistenceUnitNotFound(String path, String puName, DeploymentUnit deploymentUnit);
//@Message(id = 35, value = "Parameter %s is empty")
@Message(id = 36, value = "An error occurred while getting the transaction associated with the current thread: %s")
IllegalStateException errorGettingTransaction(Exception cause);
/**
* Creates an exception indicating a failure to get the adapter for the persistence provider.
*
* @param className the adapter class name.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 37, value = "Failed to get adapter for persistence provider '%s'")
DeploymentUnitProcessingException failedToGetAdapter(String className);
/**
* Creates an exception indicating a failure to add the persistence unit service.
*
* @param cause the cause of the error.
* @param puName the persistence unit name.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 38, value = "Failed to add persistence unit service for %s")
DeploymentUnitProcessingException failedToAddPersistenceUnit(@Cause Throwable cause, String puName);
/**
* Creates an exception indicating a failure to get the module for the deployment unit represented by the
* {@code deploymentUnit} parameter.
*
* @param deploymentUnit the deployment unit that failed.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
//@Message(id = 39, value = "Failed to get module attachment for %s")
//DeploymentUnitProcessingException failedToGetModuleAttachment(DeploymentUnit deploymentUnit);
/**
* A message indicating a failure to parse the file.
*
* @param file the file that could not be parsed.
* @return the message.
*/
@Message(id = 40, value = "Failed to parse %s")
String failedToParse(VirtualFile file);
/**
* Creates an exception indicating the entity manager factory implementation can only be a Hibernate version.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 41, value = "Can only inject from a Hibernate EntityManagerFactoryImpl")
RuntimeException hibernateOnlyEntityManagerFactory();
/**
* Creates an exception indicating the entity manager factory implementation can only be a Hibernate version.
*
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 42, value = "File %s not found")
//RuntimeException fileNotFound(File file);
@Message(id = 43, value = "Persistence unit name (%s) contains illegal '%s' character")
IllegalArgumentException invalidPersistenceUnitName(String persistenceUnitName, char c);
/**
* Creates an exception indicating the scoped persistence name is invalid.
*
* @param validName the valid scope name.
* @param name the scope name that was supplied.
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 44, value = "Scoped persistence name should be \"%s\" but was %s")
//RuntimeException invalidScopeName(String validName, String name);
/**
* Creates an exception indicating the inability to integrate the module, represented by the {@code integrationName}
* parameter, to the deployment as it expected a {@link java.net.JarURLConnection}.
*
* @param integrationName the name of the integration that could not be integrated.
* @param connection the invalid connection.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 45, value = "Could not add %s integration module to deployment, did not get expected JarUrlConnection, got %s")
RuntimeException invalidUrlConnection(String integrationName, URLConnection connection);
//@Message(id = 46, value = "Could not load %s")
//XMLStreamException errorLoadingJBossJPAFile(@Cause Throwable cause, String path);
/**
* Creates an exception indicating the persistence unit metadata likely because thread local was not set.
*
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 47, value = "Missing PersistenceUnitMetadata (thread local wasn't set)")
//RuntimeException missingPersistenceUnitMetadata();
/**
* Creates an exception indicating the persistence provider adapter module, represented by the {@code adapterModule}
* parameter, has more than one adapter.
*
* @param adapterModule the adapter module name.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 48, value = "Persistence provider adapter module (%s) has more than one adapter")
RuntimeException multipleAdapters(String adapterModule);
/**
* Creates an exception indicating more than one thread is invoking the stateful session bean at the same time.
*
* @param sessionBean the stateful session bean.
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 49, value = "More than one thread is invoking stateful session bean '%s' at the same time")
//RuntimeException multipleThreadsInvokingSfsb(Object sessionBean);
/**
* Creates an exception indicating more than one thread is using the entity manager instance at the same time.
*
* @param entityManager the entity manager.
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 50, value = "More than one thread is using EntityManager instance '%s' at the same time")
//RuntimeException multipleThreadsUsingEntityManager(EntityManager entityManager);
//@Message(id = 51, value = "%s not set in InterceptorContext: %s")
/**
* Creates an exception indicating the method is not yet implemented.
*
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 52, value = "Not yet implemented")
//RuntimeException notYetImplemented();
/**
* Creates an exception indicating the {@code description} is {@code null}.
*
* @param description the description of the parameter.
* @param parameterName the parameter name.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 53, value = "Internal %s error, null %s passed in")
RuntimeException nullParameter(String description, String parameterName);
//@Message(id = 54, value = "Parameter %s is null")
/**
* A message indicating the object for the class ({@code cls} has been defined and is not {@code null}.
*
* @param cls the class for the object.
* @param previous the previously defined object.
* @return the message.
*/
//@Message(id = 55, value = "Previous object for class %s is %s instead of null")
//String objectAlreadyDefined(Class<?> cls, Object previous);
/**
* Creates an exception indicating the parameter must be an ExtendedEntityManager
*
* @param gotClass
* @return a {@link RuntimeException} for the error.
*/
//@Message(id = 56, value = "Internal error, expected parameter of type ExtendedEntityManager but instead got %s")
//RuntimeException parameterMustBeExtendedEntityManager(String gotClass);
/**
* Creates an exception indicating the persistence provider could not be found.
*
* @param providerName the provider name.
* @return a {@link javax.persistence.PersistenceException} for the error.
*/
@Message(id = 57, value = "PersistenceProvider '%s' not found")
PersistenceException persistenceProviderNotFound(String providerName);
/**
* Creates an exception indicating the relative path could not be found.
*
* @param cause the cause of the error.
* @param path the path that could not be found.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 58, value = "Could not find relative path: %s")
RuntimeException relativePathNotFound(@Cause Throwable cause, String path);
/**
* A message indicating the annotation is only valid on setter method targets.
*
* @param annotation the annotation.
* @param methodInfo the method information.
* @return the message.
*/
@Message(id = 59, value = "%s injection target is invalid. Only setter methods are allowed: %s")
String setterMethodOnlyAnnotation(String annotation, MethodInfo methodInfo);
/**
* Creates an exception indicating a transaction is required for the operation.
*
* @return a {@link javax.persistence.TransactionRequiredException} for the error.
*/
@Message(id = 60, value = "Transaction is required to perform this operation (either use a transaction or extended persistence context)")
TransactionRequiredException transactionRequired();
@Message(id = 61, value = "Persistence unitName was not specified and there are %d persistence unit definitions in application deployment %s."+
" Either change the application deployment to have only one persistence unit definition or specify the unitName for each reference to a persistence unit.")
IllegalArgumentException noPUnitNameSpecifiedAndMultiplePersistenceUnits(int puCount, DeploymentUnit deploymentUnit);
/**
* Creates an exception indicating the persistence provider could not be instantiated ,
*
* @param cause the cause of the error.
* @param providerClassName
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 62, value = "Could not create instance of persistence provider class %s")
RuntimeException couldNotCreateInstanceProvider(@Cause Throwable cause, String providerClassName);
/**
* internal error indicating that the number of stateful session beans associated with a
* extended persistence context has reached a negative count.
*
* @return a {@link RuntimeException} for the error
*/
@Message(id = 63, value = "internal error, the number of stateful session beans (%d) associated " +
"with an extended persistence context (%s) cannot be a negative number.")
RuntimeException referenceCountedEntityManagerNegativeCount(int referenceCount, String scopedPuName);
/**
* Can't use a new unsynchronization persistence context when transaction already has a synchronized persistence context.
*
* @param puScopedName the persistence unit name.
* @return an {@link javax.ejb.EJBException} for the error.
*/
@Message(id = 64, value =
"JTA transaction already has a 'SynchronizationType.UNSYNCHRONIZED' persistence context (EntityManager) joined to it " +
"but a component with a 'SynchronizationType.SYNCHRONIZED' is now being used. " +
"Change the calling component code to join the persistence context (EntityManager) to the transaction or "+
"change the called component code to also use 'SynchronizationType.UNSYNCHRONIZED'. "+
"See JPA spec 2.1 section 7.6.4.1. " +
"Scoped persistence unit name=%s.")
EJBException badSynchronizationTypeCombination(String puScopedName);
@Message(id = 65, value = "Resources of type %s cannot be registered")
UnsupportedOperationException resourcesOfTypeCannotBeRegistered(String key);
@Message(id = 66, value = "Resources of type %s cannot be removed")
UnsupportedOperationException resourcesOfTypeCannotBeRemoved(String key);
/**
* Only one persistence provider adapter per (persistence provider or application) classloader is allowed
*
* @param classloader
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 67, value = "Classloader '%s' has more than one Persistence provider adapter")
RuntimeException classloaderHasMultipleAdapters(String classloader);
/**
* Likely cause is that the application deployment did not complete successfully
*
* @param scopedPuName
* @return
*/
@Message(id = 68, value = "Persistence unit '%s' is not available")
IllegalStateException PersistenceUnitNotAvailable(String scopedPuName);
/**
* persistence provider adaptor module load error
*
* @param cause the cause of the error.
* @param adaptorModule name of persistence provider adaptor module that couldn't be loaded.
* @return
*/
@Message(id = 69, value = "Persistence provider adapter module load error %s")
DeploymentUnitProcessingException persistenceProviderAdaptorModuleLoadError(@Cause Throwable cause, String adaptorModule);
/**
* extended persistence context can only be used within a stateful session bean. WFLY-69
*
* @param scopedPuName
* @return
*/
@Message(id = 70, value = "A container-managed extended persistence context can only be initiated within the scope of a stateful session bean (persistence unit '%s').")
IllegalStateException xpcOnlyFromSFSB(String scopedPuName);
@Message(id = 71, value = "Deployment '%s' specified more than one Hibernate Search module name ('%s','%s')")
DeploymentUnitProcessingException differentSearchModuleDependencies(String deployment, String searchModuleName1, String searchModuleName2);
}
|
package us.dot.its.jpo.ode.vsdm;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.oss.asn1.AbstractData;
import com.oss.asn1.Coder;
import com.oss.asn1.DecodeFailedException;
import com.oss.asn1.DecodeNotSupportedException;
import us.dot.its.jpo.ode.OdeProperties;
import us.dot.its.jpo.ode.SerializableMessageProducerPool;
import us.dot.its.jpo.ode.asn1.j2735.J2735Util;
import us.dot.its.jpo.ode.j2735.J2735;
import us.dot.its.jpo.ode.j2735.dsrc.BasicSafetyMessage;
import us.dot.its.jpo.ode.j2735.semi.ServiceRequest;
import us.dot.its.jpo.ode.j2735.semi.VehSitDataMessage;
import us.dot.its.jpo.ode.plugin.asn1.Asn1Object;
import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm;
import us.dot.its.jpo.ode.plugin.j2735.oss.OssBsm;
import us.dot.its.jpo.ode.plugin.j2735.oss.OssBsmPart2Content.OssBsmPart2Exception;
import us.dot.its.jpo.ode.util.JsonUtils;
import us.dot.its.jpo.ode.util.SerializationUtils;
import us.dot.its.jpo.ode.wrapper.MessageProducer;
public class VsdmReceiver implements Runnable {
private static Logger logger = LoggerFactory.getLogger(VsdmReceiver.class);
private static Coder coder = J2735.getPERUnalignedCoder();
private DatagramSocket socket;
private OdeProperties odeProperties;
private SerializableMessageProducerPool<String, byte[]> messageProducerPool;
@Autowired
public VsdmReceiver(OdeProperties odeProps) {
this.odeProperties = odeProps;
try {
socket = new DatagramSocket(odeProperties.getReceiverPort());
logger.info("[VSDM Receiver] Created UDP socket bound to port ", odeProperties.getReceiverPort());
} catch (SocketException e) {
logger.error("[VSDM Receiver] Error creating socket with port ", odeProperties.getReceiverPort(), e);
}
messageProducerPool = new SerializableMessageProducerPool<>(odeProperties);
}
@Override
public void run() {
logger.info("Vsdm Receiver Service started.");
byte[] buffer = new byte[odeProperties.getVsdmBufferSize()];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
Boolean stopped = false;
while (!stopped) {
try {
logger.info("VSDM RECEIVER - Waiting for UDP packets...");
socket.receive(packet);
logger.info("VSDM RECEIVER - Packet received.");
String obuIp = packet.getAddress().getHostAddress();
int obuPort = packet.getPort();
SocketAddress sockAddr = packet.getSocketAddress();
System.out.println("Socket Address: " + sockAddr.toString());
InetAddress inet6Addr = Inet6Address.getByName(obuIp);
System.out.println("Inet6 Address: " + inet6Addr.toString());
logger.info("Packet length: {}, Buffer length: {}", packet.getLength(), buffer.length);
byte[] actualPacket = Arrays.copyOf(packet.getData(), packet.getLength());
if (packet.getLength() > 0) {
logger.info("VSDM RECEIVER - Received data:", buffer);
decodeData(actualPacket, obuIp, obuPort);
}
} catch (IOException e) {
logger.error("VSDM RECEIVER - Error receiving UDP packet", e);
stopped = true;
}
}
}
private void decodeData(byte[] msg, String obuIp, int obuPort) {
try {
AbstractData decoded = J2735Util.decode(coder, msg);
logger.info("VSDM RECEIVER - Decoded the message");
if (decoded instanceof ServiceRequest) {
logger.info("VSDM RECEIVER - Received ServiceRequest: ", decoded.toString());
ServiceRequest request = (ServiceRequest) decoded;
ReqResForwarder forwarder = new ReqResForwarder(odeProperties, request, obuIp, obuPort);
Thread forwarderThread = new Thread(forwarder, "forwarderThread");
forwarderThread.start();
} else if (decoded instanceof VehSitDataMessage) {
logger.info("VSDM RECEIVER - Received VSD");
logger.info("VSDM RECEIVER - Forwarding VSD to SDC");
VsdDepositor depositor = new VsdDepositor(odeProperties, msg);
Thread depositorThread = new Thread(depositor, "depositor");
depositorThread.start();
logger.info("VSDM RECEIVER - Publishing VSD to Kafka topic");
publishVsdm(msg);
extractAndPublishBsms((VehSitDataMessage) decoded);
} else {
logger.error("[VSDM Receiver] Error, unknown message type received.");
}
} catch (DecodeFailedException | DecodeNotSupportedException e) {
logger.error("[VSDM Receiver] Error, unable to decode UDP message", e);
}
}
private void extractAndPublishBsms(VehSitDataMessage msg) {
List<BasicSafetyMessage> bsmList = null;
try {
bsmList = VsdToBsmConverter.convert(msg);
} catch (Exception e) {
logger.error("VSDM RECEIVER - Unable to convert VehSitDataMessage bundle to BSM list.", e);
return;
}
for (BasicSafetyMessage entry : bsmList) {
try {
J2735Bsm convertedBsm = OssBsm.genericBsm(entry);
publishBsm(convertedBsm);
String bsmJson = JsonUtils.toJson(convertedBsm, odeProperties.getVsdmVerboseJson());
publishBsm(bsmJson);
} catch (OssBsmPart2Exception e) {
logger.error("[VSDM Receiver] Error, unable to convert BSM: ", e);
}
}
}
public void publishBsm(String msg) {
MessageProducer
.defaultStringMessageProducer(odeProperties.getKafkaBrokers(), odeProperties.getKafkaProducerType())
.send(odeProperties.getKafkaTopicBsmJSON(), null, msg);
logger.debug("Published bsm to the topic J2735BsmRawJSON: {}", msg);
}
public void publishBsm(Asn1Object msg) {
MessageProducer<String, byte[]> producer = messageProducerPool.checkOut();
producer.send(odeProperties.getKafkaTopicBsmSerializedPOJO(), null,
new SerializationUtils<J2735Bsm>().serialize((J2735Bsm) msg));
messageProducerPool.checkIn(producer);
logger.debug("Published bsm to the topic J2735Bsm");
}
private void publishVsdm(byte[] data) {
MessageProducer<String, byte[]> producer = messageProducerPool.checkOut();
producer.send(odeProperties.getKafkaTopicVsdm(), null, data);
messageProducerPool.checkIn(producer);
logger.info("VSDM RECEIVER - Published vsd to the topic J2735Vsdm");
}
}
|
package jsettlers.main.replay;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import jsettlers.common.menu.IStartedGame;
import jsettlers.common.menu.IStartingGame;
import jsettlers.common.resources.ResourceManager;
import jsettlers.common.utils.mutables.MutableInt;
import jsettlers.input.tasks.EGuiAction;
import jsettlers.input.tasks.SimpleGuiTask;
import jsettlers.logic.constants.MatchConstants;
import jsettlers.logic.map.loading.MapLoadException;
import jsettlers.logic.map.loading.MapLoader;
import jsettlers.logic.map.loading.list.MapList;
import jsettlers.logic.player.PlayerSetting;
import jsettlers.main.JSettlersGame;
import jsettlers.main.JSettlersGame.GameRunner;
import jsettlers.main.ReplayStartInformation;
import jsettlers.network.NetworkConstants;
import jsettlers.network.client.OfflineNetworkConnector;
import jsettlers.network.client.interfaces.IGameClock;
import jsettlers.network.client.interfaces.INetworkConnector;
/**
*
* @author Andreas Eberle
*
*/
public class ReplayUtils {
public static MapLoader replayAndCreateSavegame(IReplayStreamProvider replayFile, int targetGameTimeMinutes, String newReplayFile) throws MapLoadException, IOException {
OfflineNetworkConnector networkConnector = createPausingOfflineNetworkConnector();
ReplayStartInformation replayStartInformation = new ReplayStartInformation();
JSettlersGame game = loadGameFromReplay(replayFile, networkConnector, replayStartInformation);
IStartedGame startedGame = startGame(game); // before we can save the clock reference, the game must be started
IGameClock gameClock = MatchConstants.clock(); // after the game, the clock cannot be accessed any more => save reference before the game
MapLoader newSavegame = playGameToTargetTimeAndGetSavegames(startedGame, networkConnector, targetGameTimeMinutes)[0];
// create a jsettlers.integration.replay basing on the savegame and containing the remaining tasks.
createReplayOfRemainingTasks(newSavegame, replayStartInformation, newReplayFile, gameClock);
System.out.println("Replayed: " + replayFile + " and created savegame: " + newSavegame);
return newSavegame;
}
public static MapLoader[] replayAndCreateSavegames(IReplayStreamProvider replayFile, int[] targetGameTimeMinutes) throws MapLoadException {
OfflineNetworkConnector networkConnector = createPausingOfflineNetworkConnector();
ReplayStartInformation replayStartInformation = new ReplayStartInformation();
JSettlersGame game = loadGameFromReplay(replayFile, networkConnector, replayStartInformation);
MapLoader[] newSavegame = playGameToTargetTimeAndGetSavegames(game, networkConnector, targetGameTimeMinutes);
System.out.println("Replayed: " + replayFile + " and created savegames: " + Arrays.asList(newSavegame));
return newSavegame;
}
private static OfflineNetworkConnector createPausingOfflineNetworkConnector() {
OfflineNetworkConnector networkConnector = new OfflineNetworkConnector();
networkConnector.getGameClock().setPausing(true);
return networkConnector;
}
private static MapLoader[] playGameToTargetTimeAndGetSavegames(JSettlersGame game, OfflineNetworkConnector networkConnector, final int... targetGameTimesMinutes) {
IStartedGame startedGame = startGame(game);
return playGameToTargetTimeAndGetSavegames(startedGame, networkConnector, targetGameTimesMinutes);
}
private static MapLoader[] playGameToTargetTimeAndGetSavegames(IStartedGame startedGame, OfflineNetworkConnector networkConnector, final int... targetGameTimesMinutes) {
final int[] targetGameTimesMs = getGameTimeMsFromMinutes(targetGameTimesMinutes);
// schedule the save task and run the game to the target game time
MapLoader[] savegames = new MapLoader[targetGameTimesMs.length];
for (int i = 0; i < targetGameTimesMs.length; i++) {
final int targetGameTimeMs = targetGameTimesMs[i];
networkConnector.scheduleTaskAt(targetGameTimeMs / NetworkConstants.Client.LOCKSTEP_PERIOD,
new SimpleGuiTask(EGuiAction.QUICK_SAVE, (byte) 0)
);
MatchConstants.clock().fastForwardTo(targetGameTimeMs + 1000);
savegames[i] = getNewestSavegame();
}
awaitShutdown(startedGame);
return savegames;
}
private static int[] getGameTimeMsFromMinutes(final int... targetGameTimesMinutes) {
final int[] targetGameTimesMs = new int[targetGameTimesMinutes.length];
for (int i = 0; i < targetGameTimesMinutes.length; i++) {
targetGameTimesMs[i] = targetGameTimesMinutes[i] * 60 * 1000;
}
Arrays.sort(targetGameTimesMs);
return targetGameTimesMs;
}
public static MapLoader getNewestSavegame() {
List<? extends MapLoader> savedMaps = MapList.getDefaultList().getSavedMaps().getItems();
if (savedMaps.isEmpty()) {
throw new RuntimeException("No saved games found.");
}
MapLoader newest = savedMaps.get(0);
for (MapLoader map : savedMaps) {
if (newest.getCreationDate().before(map.getCreationDate())) {
newest = map;
}
}
return newest;
}
public static void awaitShutdown(IStartedGame startedGame) {
final MutableInt gameStopped = new MutableInt(0);
startedGame.setGameExitListener(game -> {
gameStopped.value = 1;
synchronized (gameStopped) {
gameStopped.notifyAll();
}
});
((GameRunner) startedGame).stopGame();
synchronized (gameStopped) {
while (gameStopped.value == 0 && !startedGame.isShutdownFinished()) {
try {
gameStopped.wait();
} catch (InterruptedException e) {
}
}
}
}
private static IStartedGame startGame(JSettlersGame game) {
IStartingGame startingGame = game.start();
return waitForGameStartup(startingGame);
}
public static IStartedGame waitForGameStartup(IStartingGame game) {
DummyStartingGameListener startingGameListener = new DummyStartingGameListener();
game.setListener(startingGameListener);
return startingGameListener.waitForGameStartup();
}
private static JSettlersGame loadGameFromReplay(IReplayStreamProvider replayFile, INetworkConnector networkConnector, ReplayStartInformation replayStartInformation) throws MapLoadException {
System.out.println("Found loadable jsettlers.integration.replay file. Started loading it: " + replayFile);
return JSettlersGame.loadFromReplayFile(replayFile, networkConnector, replayStartInformation);
}
private static void createReplayOfRemainingTasks(MapLoader newSavegame, ReplayStartInformation replayStartInformation, String newReplayFile, IGameClock gameClock) throws IOException {
System.out.println("Creating new jsettlers.integration.replay file (" + newReplayFile + ")...");
ReplayStartInformation replayInfo = new ReplayStartInformation(0, newSavegame.getMapName(), newSavegame.getMapId(), replayStartInformation.getPlayerId(),
replayStartInformation.getPlayerSettings()
);
DataOutputStream dos = new DataOutputStream(ResourceManager.writeUserFile(newReplayFile));
replayInfo.serialize(dos);
gameClock.saveRemainingTasks(dos);
dos.close();
System.out.println("New jsettlers.integration.replay file successfully created!");
}
public static PlayMapResult playMapToTargetTimes(MapLoader map, byte playerId, final int... targetTimeMinutes) {
OfflineNetworkConnector networkConnector = ReplayUtils.createPausingOfflineNetworkConnector();
JSettlersGame game = new JSettlersGame(map, 0L, networkConnector, playerId, PlayerSetting.createDefaultSettings(playerId, (byte) map.getMaxPlayers())) {
@Override
protected OutputStream createReplayWriteStream() throws IOException {
return ResourceManager.writeConfigurationFile("jsettlers.integration.replay");
}
};
final MapLoader[] savegames = ReplayUtils.playGameToTargetTimeAndGetSavegames(game, networkConnector, targetTimeMinutes);
return new PlayMapResult(map, savegames);
}
public interface IReplayStreamProvider {
InputStream openStream() throws IOException;
MapLoader getMap(ReplayStartInformation replayStartInformation) throws MapLoadException;
}
/**
* A jsettlers.integration.replay file using the default list.
*
* @see MapList#defaultList
*/
public static class ReplayFile implements IReplayStreamProvider {
private final File file;
public ReplayFile(File file) {
this.file = file;
}
@Override
public InputStream openStream() throws IOException {
return new FileInputStream(file);
}
@Override
public MapLoader getMap(ReplayStartInformation replayStartInformation) {
return MapList.getDefaultList().getMapById(replayStartInformation.getMapId());
}
}
public static class PlayMapResult implements IReplayStreamProvider {
private final MapLoader map;
private final MapLoader[] savegames;
PlayMapResult(MapLoader map, MapLoader[] savegames) {
this.map = map;
this.savegames = savegames;
}
@Override
public InputStream openStream() throws IOException {
return ResourceManager.getResourcesFileStream("jsettlers.integration.replay");
}
@Override
public MapLoader getMap(ReplayStartInformation replayStartInformation) throws MapLoadException {
if (map.getMapId().equals(replayStartInformation.getMapId())) {
return map;
}
throw new MapLoadException("No file found for " + replayStartInformation);
}
public MapLoader[] getSavegames() {
return savegames;
}
}
}
|
package creational.singleton;
public class DatabaseConnection
{
private static volatile DatabaseConnection instance = null;
private DatabaseConnection()
{
System.out.println("Initializing database connection...");
}
public static synchronized DatabaseConnection getInstance()
{
if (DatabaseConnection.instance == null)
{
synchronized (DatabaseConnection.class)
{
if (DatabaseConnection.instance == null)
{
DatabaseConnection.instance = new DatabaseConnection();
}
}
}
return DatabaseConnection.instance;
}
public void executeQuery(String query)
{
System.out.println(query);
}
}
|
package com.fsck.k9.activity.setup;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceScreen;
import android.preference.RingtonePreference;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.Account.Expunge;
import com.fsck.k9.Account.FolderMode;
import com.fsck.k9.Account.MessageFormat;
import com.fsck.k9.Account.QuoteStyle;
import com.fsck.k9.Account.Searchable;
import com.fsck.k9.Account.ShowPictures;
import com.fsck.k9.K9;
import com.fsck.k9.NotificationSetting;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.ChooseIdentity;
import com.fsck.k9.activity.ColorPickerDialog;
import com.fsck.k9.activity.K9PreferenceActivity;
import com.fsck.k9.activity.ManageIdentities;
import com.fsck.k9.crypto.OpenPgpApiHelper;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mailstore.StorageManager;
import com.fsck.k9.service.MailService;
import org.openintents.openpgp.util.OpenPgpKeyPreference;
import timber.log.Timber;
public class AccountSettings extends K9PreferenceActivity {
private static final String EXTRA_ACCOUNT = "account";
private static final int DIALOG_COLOR_PICKER_ACCOUNT = 1;
private static final int DIALOG_COLOR_PICKER_LED = 2;
private static final int SELECT_AUTO_EXPAND_FOLDER = 1;
private static final int ACTIVITY_MANAGE_IDENTITIES = 2;
private static final String PREFERENCE_SCREEN_MAIN = "main";
private static final String PREFERENCE_SCREEN_COMPOSING = "composing";
private static final String PREFERENCE_SCREEN_INCOMING = "incoming_prefs";
private static final String PREFERENCE_SCREEN_PUSH_ADVANCED = "push_advanced";
private static final String PREFERENCE_SCREEN_SEARCH = "search";
private static final String PREFERENCE_DESCRIPTION = "account_description";
private static final String PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW = "mark_message_as_read_on_view";
private static final String PREFERENCE_COMPOSITION = "composition";
private static final String PREFERENCE_MANAGE_IDENTITIES = "manage_identities";
private static final String PREFERENCE_FREQUENCY = "account_check_frequency";
private static final String PREFERENCE_DISPLAY_COUNT = "account_display_count";
private static final String PREFERENCE_DEFAULT = "account_default";
private static final String PREFERENCE_SHOW_PICTURES = "show_pictures_enum";
private static final String PREFERENCE_NOTIFY = "account_notify";
private static final String PREFERENCE_NOTIFY_NEW_MAIL_MODE = "folder_notify_new_mail_mode";
private static final String PREFERENCE_NOTIFY_SELF = "account_notify_self";
private static final String PREFERENCE_NOTIFY_CONTACTS_MAIL_ONLY = "account_notify_contacts_mail_only";
private static final String PREFERENCE_NOTIFY_SYNC = "account_notify_sync";
private static final String PREFERENCE_VIBRATE = "account_vibrate";
private static final String PREFERENCE_VIBRATE_PATTERN = "account_vibrate_pattern";
private static final String PREFERENCE_VIBRATE_TIMES = "account_vibrate_times";
private static final String PREFERENCE_RINGTONE = "account_ringtone";
private static final String PREFERENCE_NOTIFICATION_LED = "account_led";
private static final String PREFERENCE_INCOMING = "incoming";
private static final String PREFERENCE_OUTGOING = "outgoing";
private static final String PREFERENCE_DISPLAY_MODE = "folder_display_mode";
private static final String PREFERENCE_SYNC_MODE = "folder_sync_mode";
private static final String PREFERENCE_PUSH_MODE = "folder_push_mode";
private static final String PREFERENCE_PUSH_POLL_ON_CONNECT = "push_poll_on_connect";
private static final String PREFERENCE_MAX_PUSH_FOLDERS = "max_push_folders";
private static final String PREFERENCE_IDLE_REFRESH_PERIOD = "idle_refresh_period";
private static final String PREFERENCE_TARGET_MODE = "folder_target_mode";
private static final String PREFERENCE_DELETE_POLICY = "delete_policy";
private static final String PREFERENCE_EXPUNGE_POLICY = "expunge_policy";
private static final String PREFERENCE_AUTO_EXPAND_FOLDER = "account_setup_auto_expand_folder";
private static final String PREFERENCE_SEARCHABLE_FOLDERS = "searchable_folders";
private static final String PREFERENCE_CHIP_COLOR = "chip_color";
private static final String PREFERENCE_LED_COLOR = "led_color";
private static final String PREFERENCE_NOTIFICATION_OPENS_UNREAD = "notification_opens_unread";
private static final String PREFERENCE_MESSAGE_AGE = "account_message_age";
private static final String PREFERENCE_MESSAGE_SIZE = "account_autodownload_size";
private static final String PREFERENCE_MESSAGE_FORMAT = "message_format";
private static final String PREFERENCE_MESSAGE_READ_RECEIPT = "message_read_receipt";
private static final String PREFERENCE_QUOTE_PREFIX = "account_quote_prefix";
private static final String PREFERENCE_QUOTE_STYLE = "quote_style";
private static final String PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN = "default_quoted_text_shown";
private static final String PREFERENCE_REPLY_AFTER_QUOTE = "reply_after_quote";
private static final String PREFERENCE_STRIP_SIGNATURE = "strip_signature";
private static final String PREFERENCE_SYNC_REMOTE_DELETIONS = "account_sync_remote_deletetions";
private static final String PREFERENCE_CRYPTO = "crypto";
private static final String PREFERENCE_CRYPTO_KEY = "crypto_key";
private static final String PREFERENCE_CLOUD_SEARCH_ENABLED = "remote_search_enabled";
private static final String PREFERENCE_REMOTE_SEARCH_NUM_RESULTS = "account_remote_search_num_results";
private static final String PREFERENCE_REMOTE_SEARCH_FULL_TEXT = "account_remote_search_full_text";
private static final String PREFERENCE_LOCAL_STORAGE_PROVIDER = "local_storage_provider";
private static final String PREFERENCE_CATEGORY_FOLDERS = "folders";
private static final String PREFERENCE_ARCHIVE_FOLDER = "archive_folder";
private static final String PREFERENCE_DRAFTS_FOLDER = "drafts_folder";
private static final String PREFERENCE_SENT_FOLDER = "sent_folder";
private static final String PREFERENCE_SPAM_FOLDER = "spam_folder";
private static final String PREFERENCE_TRASH_FOLDER = "trash_folder";
private static final String PREFERENCE_ALWAYS_SHOW_CC_BCC = "always_show_cc_bcc";
private Account account;
private boolean isMoveCapable = false;
private boolean isPushCapable = false;
private boolean isExpungeCapable = false;
private boolean isSeenFlagSupported = false;
private PreferenceScreen mainScreen;
private PreferenceScreen composingScreen;
private EditTextPreference accountDescription;
private CheckBoxPreference markMessageAsReadOnView;
private ListPreference checkFrequency;
private ListPreference displayCount;
private ListPreference messageAge;
private ListPreference messageSize;
private CheckBoxPreference accountDefault;
private CheckBoxPreference accountNotify;
private ListPreference accountNotifyNewMailMode;
private CheckBoxPreference accountNotifySelf;
private CheckBoxPreference accountNotifyContactsMailOnly;
private ListPreference accountShowPictures;
private CheckBoxPreference accountNotifySync;
private CheckBoxPreference accountVibrateEnabled;
private CheckBoxPreference accountLedEnabled;
private ListPreference accountVibratePattern;
private ListPreference accountVibrateTimes;
private RingtonePreference accountRingtone;
private ListPreference displayMode;
private ListPreference syncMode;
private ListPreference pushMode;
private ListPreference targetMode;
private ListPreference deletePolicy;
private ListPreference expungePolicy;
private ListPreference searchableFolders;
private ListPreference autoExpandFolder;
private Preference chipColor;
private Preference ledColor;
private boolean incomingChanged = false;
private CheckBoxPreference notificationOpensUnread;
private ListPreference messageFormat;
private CheckBoxPreference messageReadReceipt;
private ListPreference quoteStyle;
private EditTextPreference accountQuotePrefix;
private CheckBoxPreference accountDefaultQuotedTextShown;
private CheckBoxPreference replyAfterQuote;
private CheckBoxPreference stripSignature;
private CheckBoxPreference syncRemoteDeletions;
private CheckBoxPreference pushPollOnConnect;
private ListPreference idleRefreshPeriod;
private ListPreference mMaxPushFolders;
private boolean hasPgpCrypto = false;
private OpenPgpKeyPreference pgpCryptoKey;
private CheckBoxPreference pgpSupportSignOnly;
private PreferenceScreen searchScreen;
private CheckBoxPreference cloudSearchEnabled;
private ListPreference remoteSearchNumResults;
/*
* Temporarily removed because search results aren't displayed to the user.
* So this feature is useless.
*/
//private CheckBoxPreference mRemoteSearchFullText;
private ListPreference localStorageProvider;
private ListPreference archiveFolder;
private ListPreference draftsFolder;
private ListPreference sentFolder;
private ListPreference spamFolder;
private ListPreference trashFolder;
private CheckBoxPreference alwaysShowCcBcc;
public static void actionSettings(Context context, Account account) {
Intent i = new Intent(context, AccountSettings.class);
i.putExtra(EXTRA_ACCOUNT, account.getUuid());
context.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
account = Preferences.getPreferences(this).getAccount(accountUuid);
try {
final Store store = account.getRemoteStore();
isMoveCapable = store.isMoveCapable();
isPushCapable = store.isPushCapable();
isExpungeCapable = store.isExpungeCapable();
isSeenFlagSupported = store.isSeenFlagSupported();
} catch (Exception e) {
Timber.e(e, "Could not get remote store");
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mainScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_MAIN);
accountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
accountDescription.setSummary(account.getDescription());
accountDescription.setText(account.getDescription());
accountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
accountDescription.setSummary(summary);
accountDescription.setText(summary);
return false;
}
});
markMessageAsReadOnView = (CheckBoxPreference) findPreference(PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW);
markMessageAsReadOnView.setChecked(account.isMarkMessageAsReadOnView());
messageFormat = (ListPreference) findPreference(PREFERENCE_MESSAGE_FORMAT);
messageFormat.setValue(account.getMessageFormat().name());
messageFormat.setSummary(messageFormat.getEntry());
messageFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = messageFormat.findIndexOfValue(summary);
messageFormat.setSummary(messageFormat.getEntries()[index]);
messageFormat.setValue(summary);
return false;
}
});
alwaysShowCcBcc = (CheckBoxPreference) findPreference(PREFERENCE_ALWAYS_SHOW_CC_BCC);
alwaysShowCcBcc.setChecked(account.isAlwaysShowCcBcc());
messageReadReceipt = (CheckBoxPreference) findPreference(PREFERENCE_MESSAGE_READ_RECEIPT);
messageReadReceipt.setChecked(account.isMessageReadReceiptAlways());
accountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
accountQuotePrefix.setSummary(account.getQuotePrefix());
accountQuotePrefix.setText(account.getQuotePrefix());
accountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String value = newValue.toString();
accountQuotePrefix.setSummary(value);
accountQuotePrefix.setText(value);
return false;
}
});
accountDefaultQuotedTextShown = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN);
accountDefaultQuotedTextShown.setChecked(account.isDefaultQuotedTextShown());
replyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
replyAfterQuote.setChecked(account.isReplyAfterQuote());
stripSignature = (CheckBoxPreference) findPreference(PREFERENCE_STRIP_SIGNATURE);
stripSignature.setChecked(account.isStripSignature());
composingScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_COMPOSING);
Preference.OnPreferenceChangeListener quoteStyleListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final QuoteStyle style = QuoteStyle.valueOf(newValue.toString());
int index = quoteStyle.findIndexOfValue(newValue.toString());
quoteStyle.setSummary(quoteStyle.getEntries()[index]);
if (style == QuoteStyle.PREFIX) {
composingScreen.addPreference(accountQuotePrefix);
composingScreen.addPreference(replyAfterQuote);
} else if (style == QuoteStyle.HEADER) {
composingScreen.removePreference(accountQuotePrefix);
composingScreen.removePreference(replyAfterQuote);
}
return true;
}
};
quoteStyle = (ListPreference) findPreference(PREFERENCE_QUOTE_STYLE);
quoteStyle.setValue(account.getQuoteStyle().name());
quoteStyle.setSummary(quoteStyle.getEntry());
quoteStyle.setOnPreferenceChangeListener(quoteStyleListener);
// Call the onPreferenceChange() handler on startup to update the Preference dialogue based
// upon the existing quote style setting.
quoteStyleListener.onPreferenceChange(quoteStyle, account.getQuoteStyle().name());
checkFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
checkFrequency.setValue(String.valueOf(account.getAutomaticCheckIntervalMinutes()));
checkFrequency.setSummary(checkFrequency.getEntry());
checkFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = checkFrequency.findIndexOfValue(summary);
checkFrequency.setSummary(checkFrequency.getEntries()[index]);
checkFrequency.setValue(summary);
return false;
}
});
displayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
displayMode.setValue(account.getFolderDisplayMode().name());
displayMode.setSummary(displayMode.getEntry());
displayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = displayMode.findIndexOfValue(summary);
displayMode.setSummary(displayMode.getEntries()[index]);
displayMode.setValue(summary);
return false;
}
});
syncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
syncMode.setValue(account.getFolderSyncMode().name());
syncMode.setSummary(syncMode.getEntry());
syncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = syncMode.findIndexOfValue(summary);
syncMode.setSummary(syncMode.getEntries()[index]);
syncMode.setValue(summary);
return false;
}
});
targetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
targetMode.setValue(account.getFolderTargetMode().name());
targetMode.setSummary(targetMode.getEntry());
targetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = targetMode.findIndexOfValue(summary);
targetMode.setSummary(targetMode.getEntries()[index]);
targetMode.setValue(summary);
return false;
}
});
deletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
if (!isSeenFlagSupported) {
removeListEntry(deletePolicy, DeletePolicy.MARK_AS_READ.preferenceString());
}
deletePolicy.setValue(account.getDeletePolicy().preferenceString());
deletePolicy.setSummary(deletePolicy.getEntry());
deletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = deletePolicy.findIndexOfValue(summary);
deletePolicy.setSummary(deletePolicy.getEntries()[index]);
deletePolicy.setValue(summary);
return false;
}
});
expungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
if (isExpungeCapable) {
expungePolicy.setValue(account.getExpungePolicy().name());
expungePolicy.setSummary(expungePolicy.getEntry());
expungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = expungePolicy.findIndexOfValue(summary);
expungePolicy.setSummary(expungePolicy.getEntries()[index]);
expungePolicy.setValue(summary);
return false;
}
});
} else {
((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(expungePolicy);
}
syncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
syncRemoteDeletions.setChecked(account.syncRemoteDeletions());
searchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
searchableFolders.setValue(account.getSearchableFolders().name());
searchableFolders.setSummary(searchableFolders.getEntry());
searchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = searchableFolders.findIndexOfValue(summary);
searchableFolders.setSummary(searchableFolders.getEntries()[index]);
searchableFolders.setValue(summary);
return false;
}
});
displayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
displayCount.setValue(String.valueOf(account.getDisplayCount()));
displayCount.setSummary(displayCount.getEntry());
displayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = displayCount.findIndexOfValue(summary);
displayCount.setSummary(displayCount.getEntries()[index]);
displayCount.setValue(summary);
return false;
}
});
messageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
if (!account.isSearchByDateCapable()) {
((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(messageAge);
} else {
messageAge.setValue(String.valueOf(account.getMaximumPolledMessageAge()));
messageAge.setSummary(messageAge.getEntry());
messageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = messageAge.findIndexOfValue(summary);
messageAge.setSummary(messageAge.getEntries()[index]);
messageAge.setValue(summary);
return false;
}
});
}
messageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
messageSize.setValue(String.valueOf(account.getMaximumAutoDownloadMessageSize()));
messageSize.setSummary(messageSize.getEntry());
messageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = messageSize.findIndexOfValue(summary);
messageSize.setSummary(messageSize.getEntries()[index]);
messageSize.setValue(summary);
return false;
}
});
accountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
accountDefault.setChecked(
account.equals(Preferences.getPreferences(this).getDefaultAccount()));
accountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
accountShowPictures.setValue("" + account.getShowPictures());
accountShowPictures.setSummary(accountShowPictures.getEntry());
accountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = accountShowPictures.findIndexOfValue(summary);
accountShowPictures.setSummary(accountShowPictures.getEntries()[index]);
accountShowPictures.setValue(summary);
return false;
}
});
localStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
{
final Map<String, String> providers;
providers = StorageManager.getInstance(this).getAvailableProviders();
int i = 0;
final String[] providerLabels = new String[providers.size()];
final String[] providerIds = new String[providers.size()];
for (final Map.Entry<String, String> entry : providers.entrySet()) {
providerIds[i] = entry.getKey();
providerLabels[i] = entry.getValue();
i++;
}
localStorageProvider.setEntryValues(providerIds);
localStorageProvider.setEntries(providerLabels);
localStorageProvider.setValue(account.getLocalStorageProviderId());
localStorageProvider.setSummary(providers.get(account.getLocalStorageProviderId()));
localStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
localStorageProvider.setSummary(providers.get(newValue));
return true;
}
});
}
// IMAP-specific preferences
searchScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_SEARCH);
cloudSearchEnabled = (CheckBoxPreference) findPreference(PREFERENCE_CLOUD_SEARCH_ENABLED);
remoteSearchNumResults = (ListPreference) findPreference(PREFERENCE_REMOTE_SEARCH_NUM_RESULTS);
remoteSearchNumResults.setOnPreferenceChangeListener(
new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference pref, Object newVal) {
updateRemoteSearchLimit((String)newVal);
return true;
}
}
);
//mRemoteSearchFullText = (CheckBoxPreference) findPreference(PREFERENCE_REMOTE_SEARCH_FULL_TEXT);
pushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
idleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (isPushCapable) {
pushPollOnConnect.setChecked(account.isPushPollOnConnect());
cloudSearchEnabled.setChecked(account.allowRemoteSearch());
String searchNumResults = Integer.toString(account.getRemoteSearchNumResults());
remoteSearchNumResults.setValue(searchNumResults);
updateRemoteSearchLimit(searchNumResults);
//mRemoteSearchFullText.setChecked(account.isRemoteSearchFullText());
idleRefreshPeriod.setValue(String.valueOf(account.getIdleRefreshMinutes()));
idleRefreshPeriod.setSummary(idleRefreshPeriod.getEntry());
idleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = idleRefreshPeriod.findIndexOfValue(summary);
idleRefreshPeriod.setSummary(idleRefreshPeriod.getEntries()[index]);
idleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(account.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
pushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
pushMode.setValue(account.getFolderPushMode().name());
pushMode.setSummary(pushMode.getEntry());
pushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = pushMode.findIndexOfValue(summary);
pushMode.setSummary(pushMode.getEntries()[index]);
pushMode.setValue(summary);
return false;
}
});
} else {
PreferenceScreen incomingPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING);
incomingPrefs.removePreference(findPreference(PREFERENCE_SCREEN_PUSH_ADVANCED));
incomingPrefs.removePreference(findPreference(PREFERENCE_PUSH_MODE));
mainScreen.removePreference(searchScreen);
}
accountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
accountNotify.setChecked(account.isNotifyNewMail());
accountNotifyNewMailMode = (ListPreference) findPreference(PREFERENCE_NOTIFY_NEW_MAIL_MODE);
accountNotifyNewMailMode.setValue(account.getFolderNotifyNewMailMode().name());
accountNotifyNewMailMode.setSummary(accountNotifyNewMailMode.getEntry());
accountNotifyNewMailMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = accountNotifyNewMailMode.findIndexOfValue(summary);
accountNotifyNewMailMode.setSummary(accountNotifyNewMailMode.getEntries()[index]);
accountNotifyNewMailMode.setValue(summary);
return false;
}
});
accountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
accountNotifySelf.setChecked(account.isNotifySelfNewMail());
accountNotifyContactsMailOnly = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_CONTACTS_MAIL_ONLY);
accountNotifyContactsMailOnly.setChecked(account.isNotifyContactsMailOnly());
accountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
accountNotifySync.setChecked(account.isShowOngoing());
accountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = accountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!account.getNotificationSetting().isRingEnabled() ? null : account.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
accountVibrateEnabled = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
accountVibrateEnabled.setChecked(account.getNotificationSetting().isVibrateEnabled());
accountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
accountVibratePattern.setValue(String.valueOf(account.getNotificationSetting().getVibratePattern()));
accountVibratePattern.setSummary(accountVibratePattern.getEntry());
accountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = accountVibratePattern.findIndexOfValue(summary);
accountVibratePattern.setSummary(accountVibratePattern.getEntries()[index]);
accountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
accountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
accountVibrateTimes.setValue(String.valueOf(account.getNotificationSetting().getVibrateTimes()));
accountVibrateTimes.setSummary(String.valueOf(account.getNotificationSetting().getVibrateTimes()));
accountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String value = newValue.toString();
accountVibrateTimes.setSummary(value);
accountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
accountLedEnabled = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
accountLedEnabled.setChecked(account.getNotificationSetting().isLedEnabled());
notificationOpensUnread = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
notificationOpensUnread.setChecked(account.goToUnreadMessageSearch());
new PopulateFolderPrefsTask().execute();
chipColor = findPreference(PREFERENCE_CHIP_COLOR);
chipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onChooseChipColor();
return false;
}
});
ledColor = findPreference(PREFERENCE_LED_COLOR);
ledColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
incomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onOutgoingSettings();
return true;
}
});
hasPgpCrypto = K9.isOpenPgpProviderConfigured();
PreferenceScreen cryptoMenu = (PreferenceScreen) findPreference(PREFERENCE_CRYPTO);
if (hasPgpCrypto) {
pgpCryptoKey = (OpenPgpKeyPreference) findPreference(PREFERENCE_CRYPTO_KEY);
pgpCryptoKey.setValue(account.getCryptoKey());
pgpCryptoKey.setOpenPgpProvider(K9.getOpenPgpProvider());
// TODO: other identities?
pgpCryptoKey.setDefaultUserId(OpenPgpApiHelper.buildUserId(account.getIdentity(0)));
pgpCryptoKey.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
long value = (Long) newValue;
pgpCryptoKey.setValue(value);
return false;
}
});
cryptoMenu.setOnPreferenceClickListener(null);
} else {
cryptoMenu.setSummary(R.string.account_settings_no_openpgp_provider_configured);
cryptoMenu.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Dialog dialog = ((PreferenceScreen) preference).getDialog();
if (dialog != null) {
dialog.dismiss();
}
Toast.makeText(AccountSettings.this,
R.string.no_crypto_provider_see_global, Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
private void removeListEntry(ListPreference listPreference, String remove) {
CharSequence[] entryValues = listPreference.getEntryValues();
CharSequence[] entries = listPreference.getEntries();
CharSequence[] newEntryValues = new String[entryValues.length - 1];
CharSequence[] newEntries = new String[entryValues.length - 1];
for (int i = 0, out = 0; i < entryValues.length; i++) {
CharSequence value = entryValues[i];
if (!value.equals(remove)) {
newEntryValues[out] = value;
newEntries[out] = entries[i];
out++;
}
}
listPreference.setEntryValues(newEntryValues);
listPreference.setEntries(newEntries);
}
private void saveSettings() {
if (accountDefault.isChecked()) {
Preferences.getPreferences(this).setDefaultAccount(account);
}
account.setDescription(accountDescription.getText());
account.setMarkMessageAsReadOnView(markMessageAsReadOnView.isChecked());
account.setNotifyNewMail(accountNotify.isChecked());
account.setFolderNotifyNewMailMode(FolderMode.valueOf(accountNotifyNewMailMode.getValue()));
account.setNotifySelfNewMail(accountNotifySelf.isChecked());
account.setNotifyContactsMailOnly(accountNotifyContactsMailOnly.isChecked());
account.setShowOngoing(accountNotifySync.isChecked());
account.setDisplayCount(Integer.parseInt(displayCount.getValue()));
account.setMaximumAutoDownloadMessageSize(Integer.parseInt(messageSize.getValue()));
if (account.isSearchByDateCapable()) {
account.setMaximumPolledMessageAge(Integer.parseInt(messageAge.getValue()));
}
account.getNotificationSetting().setVibrate(accountVibrateEnabled.isChecked());
account.getNotificationSetting().setVibratePattern(Integer.parseInt(accountVibratePattern.getValue()));
account.getNotificationSetting().setVibrateTimes(Integer.parseInt(accountVibrateTimes.getValue()));
account.getNotificationSetting().setLed(accountLedEnabled.isChecked());
account.setGoToUnreadMessageSearch(notificationOpensUnread.isChecked());
account.setFolderTargetMode(FolderMode.valueOf(targetMode.getValue()));
account.setDeletePolicy(DeletePolicy.fromInt(Integer.parseInt(deletePolicy.getValue())));
if (isExpungeCapable) {
account.setExpungePolicy(Expunge.valueOf(expungePolicy.getValue()));
}
account.setSyncRemoteDeletions(syncRemoteDeletions.isChecked());
account.setSearchableFolders(Searchable.valueOf(searchableFolders.getValue()));
account.setMessageFormat(MessageFormat.valueOf(messageFormat.getValue()));
account.setAlwaysShowCcBcc(alwaysShowCcBcc.isChecked());
account.setMessageReadReceipt(messageReadReceipt.isChecked());
account.setQuoteStyle(QuoteStyle.valueOf(quoteStyle.getValue()));
account.setQuotePrefix(accountQuotePrefix.getText());
account.setDefaultQuotedTextShown(accountDefaultQuotedTextShown.isChecked());
account.setReplyAfterQuote(replyAfterQuote.isChecked());
account.setStripSignature(stripSignature.isChecked());
account.setLocalStorageProviderId(localStorageProvider.getValue());
if (hasPgpCrypto) {
account.setCryptoKey(pgpCryptoKey.getValue());
} else {
account.setCryptoKey(Account.NO_OPENPGP_KEY);
}
// In webdav account we use the exact folder name also for inbox,
// since it varies because of internationalization
if (account.getStoreUri().startsWith("webdav"))
account.setAutoExpandFolderName(autoExpandFolder.getValue());
else
account.setAutoExpandFolderName(reverseTranslateFolder(autoExpandFolder.getValue()));
if (isMoveCapable) {
account.setArchiveFolderName(archiveFolder.getValue());
account.setDraftsFolderName(draftsFolder.getValue());
account.setSentFolderName(sentFolder.getValue());
account.setSpamFolderName(spamFolder.getValue());
account.setTrashFolderName(trashFolder.getValue());
}
//IMAP stuff
if (isPushCapable) {
account.setPushPollOnConnect(pushPollOnConnect.isChecked());
account.setIdleRefreshMinutes(Integer.parseInt(idleRefreshPeriod.getValue()));
account.setMaxPushFolders(Integer.parseInt(mMaxPushFolders.getValue()));
account.setAllowRemoteSearch(cloudSearchEnabled.isChecked());
account.setRemoteSearchNumResults(Integer.parseInt(remoteSearchNumResults.getValue()));
//account.setRemoteSearchFullText(mRemoteSearchFullText.isChecked());
}
boolean needsRefresh = account.setAutomaticCheckIntervalMinutes(Integer.parseInt(checkFrequency.getValue()));
needsRefresh |= account.setFolderSyncMode(FolderMode.valueOf(syncMode.getValue()));
boolean displayModeChanged = account.setFolderDisplayMode(FolderMode.valueOf(displayMode.getValue()));
SharedPreferences prefs = accountRingtone.getPreferenceManager().getSharedPreferences();
String newRingtone = prefs.getString(PREFERENCE_RINGTONE, null);
if (newRingtone != null) {
account.getNotificationSetting().setRingEnabled(true);
account.getNotificationSetting().setRingtone(newRingtone);
} else {
if (account.getNotificationSetting().isRingEnabled()) {
account.getNotificationSetting().setRingtone(null);
}
}
account.setShowPictures(ShowPictures.valueOf(accountShowPictures.getValue()));
//IMAP specific stuff
if (isPushCapable) {
boolean needsPushRestart = account.setFolderPushMode(FolderMode.valueOf(pushMode.getValue()));
if (account.getFolderPushMode() != FolderMode.NONE) {
needsPushRestart |= displayModeChanged;
needsPushRestart |= incomingChanged;
}
if (needsRefresh && needsPushRestart) {
MailService.actionReset(this, null);
} else if (needsRefresh) {
MailService.actionReschedulePoll(this, null);
} else if (needsPushRestart) {
MailService.actionRestartPushers(this, null);
}
}
// TODO: refresh folder list here
account.save(Preferences.getPreferences(this));
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (pgpCryptoKey != null && pgpCryptoKey.handleOnActivityResult(requestCode, resultCode, data)) {
return;
}
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_AUTO_EXPAND_FOLDER:
autoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER)));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
saveSettings();
super.onPause();
}
private void onCompositionSettings() {
AccountSetupComposition.actionEditCompositionSettings(this, account);
}
private void onManageIdentities() {
Intent intent = new Intent(this, ManageIdentities.class);
intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, account.getUuid());
startActivityForResult(intent, ACTIVITY_MANAGE_IDENTITIES);
}
private void onIncomingSettings() {
AccountSetupIncoming.actionEditIncomingSettings(this, account);
}
private void onOutgoingSettings() {
AccountSetupOutgoing.actionEditOutgoingSettings(this, account);
}
public void onChooseChipColor() {
showDialog(DIALOG_COLOR_PICKER_ACCOUNT);
}
public void onChooseLedColor() {
showDialog(DIALOG_COLOR_PICKER_LED);
}
@Override
public Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_COLOR_PICKER_ACCOUNT: {
dialog = new ColorPickerDialog(this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
account.setChipColor(color);
}
},
account.getChipColor());
break;
}
case DIALOG_COLOR_PICKER_LED: {
dialog = new ColorPickerDialog(this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
account.getNotificationSetting().setLedColor(color);
}
},
account.getNotificationSetting().getLedColor());
break;
}
}
return dialog;
}
@Override
public void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_COLOR_PICKER_ACCOUNT: {
ColorPickerDialog colorPicker = (ColorPickerDialog) dialog;
colorPicker.setColor(account.getChipColor());
break;
}
case DIALOG_COLOR_PICKER_LED: {
ColorPickerDialog colorPicker = (ColorPickerDialog) dialog;
colorPicker.setColor(account.getNotificationSetting().getLedColor());
break;
}
}
}
public void onChooseAutoExpandFolder() {
Intent selectIntent = new Intent(this, ChooseFolder.class);
selectIntent.putExtra(ChooseFolder.EXTRA_ACCOUNT, account.getUuid());
selectIntent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, autoExpandFolder.getSummary());
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_FOLDER_NONE, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_DISPLAYABLE_ONLY, "yes");
startActivityForResult(selectIntent, SELECT_AUTO_EXPAND_FOLDER);
}
private String translateFolder(String in) {
if (account.getInboxFolderName().equalsIgnoreCase(in)) {
return getString(R.string.special_mailbox_name_inbox);
} else {
return in;
}
}
private String reverseTranslateFolder(String in) {
if (getString(R.string.special_mailbox_name_inbox).equals(in)) {
return account.getInboxFolderName();
} else {
return in;
}
}
private void doVibrateTest(Preference preference) {
// Do the vibration to show the user what it's like.
Vibrator vibrate = (Vibrator)preference.getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrate.vibrate(NotificationSetting.getVibration(
Integer.parseInt(accountVibratePattern.getValue()),
Integer.parseInt(accountVibrateTimes.getValue())), -1);
}
/**
* Remote search result limit summary contains the current limit. On load or change, update this value.
* @param maxResults Search limit to update the summary with.
*/
private void updateRemoteSearchLimit(String maxResults) {
if (maxResults != null) {
if (maxResults.equals("0")) {
maxResults = getString(R.string.account_settings_remote_search_num_results_entries_all);
}
remoteSearchNumResults
.setSummary(String.format(getString(R.string.account_settings_remote_search_num_summary), maxResults));
}
}
private class PopulateFolderPrefsTask extends AsyncTask<Void, Void, Void> {
List <? extends Folder > folders = new LinkedList<>();
String[] allFolderValues;
String[] allFolderLabels;
@Override
protected Void doInBackground(Void... params) {
try {
folders = account.getLocalStore().getPersonalNamespaces(false);
} catch (Exception e) {
/// this can't be checked in
}
// TODO: In the future the call above should be changed to only return remote folders.
// For now we just remove the Outbox folder if present.
Iterator <? extends Folder > iter = folders.iterator();
while (iter.hasNext()) {
Folder folder = iter.next();
if (account.getOutboxFolderName().equals(folder.getName())) {
iter.remove();
}
}
allFolderValues = new String[folders.size() + 1];
allFolderLabels = new String[folders.size() + 1];
allFolderValues[0] = K9.FOLDER_NONE;
allFolderLabels[0] = K9.FOLDER_NONE;
int i = 1;
for (Folder folder : folders) {
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
return null;
}
@Override
protected void onPreExecute() {
autoExpandFolder = (ListPreference) findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
autoExpandFolder.setEnabled(false);
archiveFolder = (ListPreference) findPreference(PREFERENCE_ARCHIVE_FOLDER);
archiveFolder.setEnabled(false);
draftsFolder = (ListPreference) findPreference(PREFERENCE_DRAFTS_FOLDER);
draftsFolder.setEnabled(false);
sentFolder = (ListPreference) findPreference(PREFERENCE_SENT_FOLDER);
sentFolder.setEnabled(false);
spamFolder = (ListPreference) findPreference(PREFERENCE_SPAM_FOLDER);
spamFolder.setEnabled(false);
trashFolder = (ListPreference) findPreference(PREFERENCE_TRASH_FOLDER);
trashFolder.setEnabled(false);
if (!isMoveCapable) {
PreferenceScreen foldersCategory =
(PreferenceScreen) findPreference(PREFERENCE_CATEGORY_FOLDERS);
foldersCategory.removePreference(archiveFolder);
foldersCategory.removePreference(spamFolder);
foldersCategory.removePreference(draftsFolder);
foldersCategory.removePreference(sentFolder);
foldersCategory.removePreference(trashFolder);
}
}
@Override
protected void onPostExecute(Void res) {
initListPreference(autoExpandFolder, account.getAutoExpandFolderName(), allFolderLabels, allFolderValues);
autoExpandFolder.setEnabled(true);
if (isMoveCapable) {
initListPreference(archiveFolder, account.getArchiveFolderName(), allFolderLabels, allFolderValues);
initListPreference(draftsFolder, account.getDraftsFolderName(), allFolderLabels, allFolderValues);
initListPreference(sentFolder, account.getSentFolderName(), allFolderLabels, allFolderValues);
initListPreference(spamFolder, account.getSpamFolderName(), allFolderLabels, allFolderValues);
initListPreference(trashFolder, account.getTrashFolderName(), allFolderLabels, allFolderValues);
archiveFolder.setEnabled(true);
spamFolder.setEnabled(true);
draftsFolder.setEnabled(true);
sentFolder.setEnabled(true);
trashFolder.setEnabled(true);
}
}
}
}
|
package de.lmu.ifi.dbs.data.synthetic;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* Provides methods for generating synthetic data.
*
* @author Elke Achtert (<a
* href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>)
*/
public class Generator {
// private static Random RANDOM = new Random(210571);
private static Random RANDOM = new Random();
private static double MAX = 100;
private static double MAX_JITTER_PCT = 0.5;
private static String FILE_NAME = "combined";
// private static String FILE_NAME = "gerade1.txt";
// private static String FILE_NAME = "gerade1.txt";
private static String DIRECTORY;
static {
String prefix = "";
// String directory = "/nfs/infdbs/Publication/RECOMB06-ACEP/experiments/data/synthetic/runtime/";
String directory = "/nfs/infdbs/Publication/ICDE06-DeliClu/experiments/data/synthetic/runtime/";
String user = System.getProperty("user.name");
// String os = System.getProperty("os.name");
if ((user.equals("achtert") || user.equals("schumm"))) {
prefix = "P:";
}
DIRECTORY = prefix + directory;
}
public static List<Double[]> randomGauss(int corrDim, int dataDim, Random random) {
if (corrDim > dataDim || corrDim < 1 || dataDim < 1) {
throw new IllegalArgumentException("Illegal arguments: corrDim=" + corrDim + " - dataDim=" + dataDim + ".");
}
double multiplier = 1000;
List<Double[]> gauss = new ArrayList<Double[]>(corrDim);
for (int i = 0; i < corrDim; i++) {
Double[] coefficients = new Double[dataDim + 1];
for (int d = 0; d < coefficients.length; d++) {
coefficients[d] = random.nextDouble();
if (d == dataDim) {
coefficients[d] *= corrDim * multiplier;
}
}
gauss.add(coefficients);
}
return gauss;
}
public static void correlationClusterSize(int dataDim, int minSize, int increment, int steps) {
try {
for (int i = 0; i < steps; i++) {
int size = minSize + i * increment;
File output = new File(DIRECTORY + "size/size" + size);
output.getParentFile().mkdirs();
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(output));
int sizePerPartition = size / (dataDim - 1);
int x0 = 2;
for (int d = 1; d < dataDim; d++) {
if (d == dataDim - 1) {
sizePerPartition = sizePerPartition + size % (dataDim - 1);
}
int sizePerPartitionCluster = sizePerPartition / (i + 1);
for (int c = 0; c <= i; c++) {
if (c == i) {
sizePerPartitionCluster = sizePerPartitionCluster + sizePerPartition % (i + 1);
}
generateAxesParallelDependency(sizePerPartitionCluster, d, dataDim, "corrdim" + d + "_" + c,
x0, out);
x0 += 2;
}
}
out.flush();
out.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void correlationClusterDim(int size, int minDim, int increment, int steps) {
try {
for (int i = 0; i < steps; i++) {
int dataDim = minDim + i * increment;
File output = new File(DIRECTORY + "dimensionality/dim" + dataDim);
output.getParentFile().mkdirs();
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(output));
int sizePerPartition = size / (dataDim - 1);
for (int d = 1; d < dataDim; d++) {
if (d == dataDim - 1) {
sizePerPartition = sizePerPartition + size % (dataDim - 1);
}
generateAxesParallelDependency(sizePerPartition, d, dataDim, "corrdim" + d, d * 2, out);
}
out.flush();
out.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void clusterSize(int dataDim, int minSize, int increment, int steps) {
try {
for (int i = 0; i < steps; i++) {
int size = minSize + i * increment;
File output = new File(DIRECTORY + (size / 1000) + "_T_" + dataDim + ".txt");
output.getParentFile().mkdirs();
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(output));
final double[] radii = new double[]{2.0, 5.0, 10.0, 15.0, 20.0};
// final double[] radii = new double[]{10};
generateClusters(size, dataDim, radii, 0.0, false, 0, 100, out);
out.flush();
out.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void combined() {
try {
List<Double[]> gauss = new ArrayList<Double[]>();
gauss.add(new Double[]{1.0, 10.0, -30.0, 100.0});
int dim = gauss.get(0).length - 1;
double[] minima = new double[dim];
double[] maxima = new double[dim];
for (int i = 0; i < dim; i++) {
minima[i] = Double.MAX_VALUE;
maxima[i] = -Double.MAX_VALUE;
}
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(DIRECTORY + FILE_NAME));
generateDependency(2000, gauss, "e1", true, minima, maxima, out);
gauss = new ArrayList<Double[]>();
gauss.add(new Double[]{1.0, 30.0, 10.0, 600.0});
generateDependency(2000, gauss, "e2", true, minima, maxima, out);
gauss = new ArrayList<Double[]>();
gauss.add(new Double[]{1.0, 0.0, -2.0, -100.0});
gauss.add(new Double[]{0.0, 1.0, 2.0, -200.0});
generateDependency(1000, gauss, "g1", true, minima, maxima, out);
gauss = new ArrayList<Double[]>();
gauss.add(new Double[]{1.0, 0.0, -3.0, 300.0});
gauss.add(new Double[]{0.0, 1.0, 15.0, -400.0});
generateDependency(1000, gauss, "g2", true, minima, maxima, out);
gauss = new ArrayList<Double[]>();
gauss.add(new Double[]{1.0, 0.0, 20.0, -400.0});
gauss.add(new Double[]{0.0, 1.0, -6.0, 500.0});
generateDependency(1000, gauss, "g3", true, minima, maxima, out);
generateNoise(100, minima, maxima, "noise", out);
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// correlationClusterSize(20, 10000, 10000, 10);
// dim(10000, 5, 5, 10);
clusterSize(15, 10000, 1, 1);
// int dim = 10;
// double[] minima = new double[dim];
// double[] maxima = new double[dim];
// Arrays.fill(maxima, 1);
// File output = new File("1_T_"+dim);
// try {
// generateNoise(1000, minima, maxima, "noise", new OutputStreamWriter(new FileOutputStream(output)));
// catch (IOException e) {
// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
/**
* Generates data that follows the specified dependencies.
*
* @param noPoints the number of points to be generated
* @param gauss the matrix holding the dependencies, has to be in
* 'zeilenstufenform'
* @param label the label for the generated data
* @param jitter if true, the generated data has jitter
* @param out the outputstream to write to
* @throws IOException
*/
private static void generateDependency(int noPoints, List<Double[]> gauss, String label, boolean jitter, double[] minima, double[] maxima, OutputStreamWriter out) throws IOException {
if (gauss.size() == 0)
throw new IllegalArgumentException("gauss.size == 0");
int dim = gauss.get(0).length - 1;
// get the independent variables
int independentCount = 0;
List<Integer> independentIndices = new ArrayList<Integer>();
for (int i = 0; i < gauss.size(); i++) {
Double[] dependency = gauss.get(i);
if (dependency.length != dim + 1)
throw new IllegalArgumentException("dependency.length != dim + 1");
if (dependency[i + independentCount] == 0) {
independentIndices.add(i + independentCount);
independentCount++;
}
}
while (gauss.size() + independentCount != dim) {
independentCount++;
independentIndices.add(gauss.size() + independentCount - 1);
}
out.write("
if (jitter) {
out.write("### Jitter max. +/- " + MAX_JITTER_PCT + " %\n");
out.write("
}
for (Double[] g : gauss) {
out.write("### " + Arrays.asList(g) + "\n");
}
out.write("
double[][] featureVectors = new double[noPoints][dim];
// generate the feature vectors
for (int n = 0; n < noPoints; n++) {
// randomize the independent values
for (int i = 0; i < independentCount; i++) {
int index = independentIndices.get(i);
Double[] values = new Double[dim + 1];
for (int d = 0; d < dim + 1; d++) {
if (d == index)
values[d] = 1.0;
else if (d == dim)
values[d] = (-1) * RANDOM.nextDouble() * MAX;
else
values[d] = 0.0;
}
if (n != 0)
gauss.remove(index);
gauss.add(index, values);
}
for (int i = dim - 1; i >= 0; i
Double[] dependency = gauss.get(i);
for (int d = dim - 1; d >= i; d
if (d == dim - 1) {
featureVectors[n][i] += dependency[d + 1];
}
else {
featureVectors[n][i] += (-1) * dependency[d + 1] * featureVectors[n][d + 1];
}
if (minima[i] > featureVectors[n][i])
minima[i] = featureVectors[n][i];
if (maxima[i] < featureVectors[n][i])
maxima[i] = featureVectors[n][i];
}
}
}
if (jitter) {
for (int n = 0; n < noPoints; n++) {
for (int i = dim - 1; i >= 0; i
double j = (RANDOM.nextDouble() * 2 - 1) * (MAX_JITTER_PCT * (maxima[i] - minima[i]) / 100.0);
featureVectors[n][i] = featureVectors[n][i] + j;
}
}
}
for (int n = 0; n < noPoints; n++) {
for (int i = 0; i < dim; i++) {
out.write(featureVectors[n][i] + " ");
}
out.write(label + "\n");
}
}
private static void generateNoise(int noPoints, double[] minima, double[] maxima, String label, OutputStreamWriter out) throws IOException {
if (minima.length != maxima.length) {
throw new IllegalArgumentException("minima.length != maxima.length");
}
int dim = minima.length;
for (int i = 0; i < noPoints; i++) {
double[] values = new double[dim];
for (int d = 0; d < dim; d++) {
values[d] = RANDOM.nextDouble() * (maxima[d] - minima[d]) + minima[d];
out.write(values[d] + " ");
}
out.write(label + "\n");
}
}
private static void generateAxesParallelDependency(int noPoints, int corrDim,
int dataDim, String label,
double min,
OutputStreamWriter out) throws IOException {
if (corrDim >= dataDim)
throw new IllegalArgumentException("corrDim >= dataDim");
out.write("
out.write("### corrDim " + corrDim + "\n");
out.write("
// randomize the dependent values
Double[] dependentValues = new Double[dataDim - corrDim];
for (int d = 0; d < dataDim - corrDim; d++) {
dependentValues[d] = RANDOM.nextDouble();
}
// generate the feature vectors
double[][] featureVectors = new double[noPoints][dataDim];
for (int n = 0; n < noPoints; n++) {
for (int d = 0; d < dataDim; d++) {
if (d < dataDim - corrDim)
featureVectors[n][d] = dependentValues[d];
else
featureVectors[n][d] = RANDOM.nextDouble();
}
}
for (int n = 0; n < noPoints; n++) {
for (int d = 0; d < dataDim; d++) {
featureVectors[n][d] = featureVectors[n][d] + min;
}
}
for (int n = 0; n < noPoints; n++) {
for (int d = 0; d < dataDim; d++) {
out.write(featureVectors[n][d] + " ");
}
out.write(label + "\n");
}
}
private static void generateClusters(int noPoints, int dim, double[] radii,
double noisePct, boolean overlap,
double min, double max, OutputStreamWriter out) throws IOException {
Double[][] featureVectors = new Double[noPoints][dim];
String[] labels = new String[noPoints];
// number of clusters
int noCluster = radii.length;
System.out.println("noCluster " + noCluster);
// noNoise of points in each cluster
int pointsPerCluster = (int) ((1.0 - noisePct) * noPoints / noCluster);
System.out.println("pointsPerCluster " + pointsPerCluster);
// number of noise points
int noNoise = noPoints - noCluster * pointsPerCluster;
System.out.println("noNoise " + noNoise);
// determine centroids of clusters
List<Double[]> centroids = new ArrayList<Double[]>();
for (int c = 0; c < noCluster; c++) {
Double[] centroid = new Double[dim];
for (int d = 0; d < dim; d++) {
centroid[d] = radii[c] + ((max - min) - 2.0 * radii[c]) * RANDOM.nextDouble();
}
boolean ok = true;
if (!overlap) {
for (int j = 0; j < c; j++) {
Double[] otherCenter = centroids.get(j);
double l = 0;
for (int a = 0; a < dim; a++) {
l += (centroid[a] - otherCenter[a]) * (centroid[a] - otherCenter[a]);
}
l = Math.sqrt(l);
if (l <= radii[c] + radii[j]) {
ok = false;
break;
}
}
}
if (ok) {
System.out.println("center " + c + " ok");
centroids.add(centroid);
}
else {
c
}
}
System.out.println("all center ok");
// create clusters
int n = 0;
for (int c = 0; c < noCluster; c++) {
for (int j = 0; j < pointsPerCluster; j++) {
Double[] featureVector = new Double[dim];
double l = 0;
for (int d = 0; d < dim; d++) {
Double[] centroid = centroids.get(c);
double value = centroid[d] +
(2.0 * RANDOM.nextDouble() - 1.0) * radii[c];
featureVector[d] = value;
l += (centroid[d] - value) * (centroid[d] - value);
}
l = Math.sqrt(l);
if (overlap || l <= radii[c]) {
featureVectors[n++] = featureVector;
labels[n - 1] = "cluster_" + c;
}
else {
j
}
}
System.out.println("Cluster " + (c + 1) + " ok");
}
// create noise
for (int i = 0; i < noNoise; i++) {
Double[] featureVector = new Double[dim];
for (int d = 0; d < dim; d++) {
featureVector[d] = (max - min) * RANDOM.nextDouble();
}
featureVectors[n++] = featureVector;
labels[n - 1] = "noise";
}
// write to out
for (n = 0; n < noPoints; n++) {
for (int d = 0; d < dim; d++) {
out.write(featureVectors[n][d] + " ");
}
out.write(labels[n] + "\n");
}
}
}
|
package com.fsck.k9.controller;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.os.Process;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.Account.Expunge;
import com.fsck.k9.AccountStats;
import com.fsck.k9.K9;
import com.fsck.k9.K9.NotificationHideSubject;
import com.fsck.k9.K9.Intents;
import com.fsck.k9.K9.NotificationQuickDelete;
import com.fsck.k9.NotificationSetting;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.Accounts;
import com.fsck.k9.activity.FolderList;
import com.fsck.k9.activity.MessageList;
import com.fsck.k9.activity.MessageReference;
import com.fsck.k9.activity.NotificationDeleteConfirmation;
import com.fsck.k9.activity.setup.AccountSetupCheckSettings.CheckDirection;
import com.fsck.k9.activity.setup.AccountSetupIncoming;
import com.fsck.k9.activity.setup.AccountSetupOutgoing;
import com.fsck.k9.cache.EmailProviderCache;
import com.fsck.k9.helper.Contacts;
import com.fsck.k9.helper.MessageHelper;
import com.fsck.k9.mail.power.TracingPowerManager;
import com.fsck.k9.mail.power.TracingPowerManager.TracingWakeLock;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.FetchProfile;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Folder.FolderType;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.CertificateValidationException;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.PushReceiver;
import com.fsck.k9.mail.Pusher;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.Transport;
import com.fsck.k9.mail.internet.MessageExtractor;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeMessageHelper;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mailstore.MessageRemovalListener;
import com.fsck.k9.mail.MessageRetrievalListener;
import com.fsck.k9.mailstore.LocalFolder;
import com.fsck.k9.mailstore.LocalMessage;
import com.fsck.k9.mailstore.LocalStore;
import com.fsck.k9.mailstore.LocalStore.PendingCommand;
import com.fsck.k9.mail.store.pop3.Pop3Store;
import com.fsck.k9.mailstore.UnavailableStorageException;
import com.fsck.k9.provider.EmailProvider;
import com.fsck.k9.provider.EmailProvider.StatsColumns;
import com.fsck.k9.search.ConditionsTreeNode;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SqlQueryBuilder;
import com.fsck.k9.service.NotificationActionService;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable {
public static final long INVALID_MESSAGE_ID = -1;
/**
* Immutable empty {@link String} array
*/
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW = "com.fsck.k9.MessagingController.moveOrCopyBulkNew";
private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk";
private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead";
private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge";
public static class UidReverseComparator implements Comparator<Message> {
@Override
public int compare(Message o1, Message o2) {
if (o1 == null || o2 == null || o1.getUid() == null || o2.getUid() == null) {
return 0;
}
int id1, id2;
try {
id1 = Integer.parseInt(o1.getUid());
id2 = Integer.parseInt(o2.getUid());
} catch (NumberFormatException e) {
return 0;
}
//reversed intentionally.
if (id1 < id2)
return 1;
if (id1 > id2)
return -1;
return 0;
}
}
/**
* Maximum number of unsynced messages to store at once
*/
private static final int UNSYNC_CHUNK_SIZE = 5;
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>();
private Thread mThread;
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private final ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>();
private final ExecutorService threadPool = Executors.newCachedThreadPool();
private MessagingListener checkMailListener = null;
private MemorizingListener memorizingListener = new MemorizingListener();
private boolean mBusy;
private Context context;
/**
* A holder class for pending notification data
*
* This class holds all pieces of information for constructing
* a notification with message preview.
*/
private static class NotificationData {
/** Number of unread messages before constructing the notification */
int unreadBeforeNotification;
/**
* List of messages that should be used for the inbox-style overview.
* It's sorted from newest to oldest message.
* Don't modify this list directly, but use {@link #addMessage(com.fsck.k9.mailstore.LocalMessage)} and
* {@link #removeMatchingMessage(android.content.Context, com.fsck.k9.activity.MessageReference)} instead.
*/
LinkedList<LocalMessage> messages;
/**
* List of references for messages that the user is still to be notified of,
* but which don't fit into the inbox style anymore. It's sorted from newest
* to oldest message.
*/
LinkedList<MessageReference> droppedMessages;
/**
* Maximum number of messages to keep for the inbox-style overview.
* As of Jellybean, phone notifications show a maximum of 5 lines, while tablet
* notifications show 7 lines. To make sure no lines are silently dropped,
* we default to 5 lines.
*/
private final static int MAX_MESSAGES = 5;
/**
* Constructs a new data instance.
*
* @param unread Number of unread messages prior to instance construction
*/
public NotificationData(int unread) {
unreadBeforeNotification = unread;
droppedMessages = new LinkedList<MessageReference>();
messages = new LinkedList<LocalMessage>();
}
/**
* Adds a new message to the list of pending messages for this notification.
*
* The implementation will take care of keeping a meaningful amount of
* messages in {@link #messages}.
*
* @param m The new message to add.
*/
public void addMessage(LocalMessage m) {
while (messages.size() >= MAX_MESSAGES) {
LocalMessage dropped = messages.removeLast();
droppedMessages.addFirst(dropped.makeMessageReference());
}
messages.addFirst(m);
}
/**
* Remove a certain message from the message list.
*
* @param context A context.
* @param ref Reference of the message to remove
* @return true if message was found and removed, false otherwise
*/
public boolean removeMatchingMessage(Context context, MessageReference ref) {
for (MessageReference dropped : droppedMessages) {
if (dropped.equals(ref)) {
droppedMessages.remove(dropped);
return true;
}
}
for (LocalMessage message : messages) {
if (message.makeMessageReference().equals(ref)) {
if (messages.remove(message) && !droppedMessages.isEmpty()) {
LocalMessage restoredMessage = droppedMessages.getFirst().restoreToLocalMessage(context);
if (restoredMessage != null) {
messages.addLast(restoredMessage);
droppedMessages.removeFirst();
}
}
return true;
}
}
return false;
}
/**
* Adds a list of references for all pending messages for the notification to the supplied
* List.
*/
public void supplyAllMessageRefs(List<MessageReference> refs) {
for (LocalMessage m : messages) {
refs.add(m.makeMessageReference());
}
refs.addAll(droppedMessages);
}
/**
* Gets the total number of messages the user is to be notified of.
*
* @return Amount of new messages the notification notifies for
*/
public int getNewMessageCount() {
return messages.size() + droppedMessages.size();
}
};
// Key is accountNumber
private final ConcurrentMap<Integer, NotificationData> notificationData = new ConcurrentHashMap<Integer, NotificationData>();
private static final Set<Flag> SYNC_FLAGS = EnumSet.of(Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED);
private void suppressMessages(Account account, List<LocalMessage> messages) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
cache.hideMessages(messages);
}
private void unsuppressMessages(Account account, List<? extends Message> messages) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
cache.unhideMessages(messages);
}
private boolean isMessageSuppressed(LocalMessage message) {
long messageId = message.getId();
long folderId = message.getFolder().getId();
EmailProviderCache cache = EmailProviderCache.getCache(message.getFolder().getAccountUuid(), context);
return cache.isMessageHidden(messageId, folderId);
}
private void setFlagInCache(final Account account, final List<Long> messageIds,
final Flag flag, final boolean newState) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
String columnName = LocalStore.getColumnNameForFlag(flag);
String value = Integer.toString((newState) ? 1 : 0);
cache.setValueForMessages(messageIds, columnName, value);
}
private void removeFlagFromCache(final Account account, final List<Long> messageIds,
final Flag flag) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
String columnName = LocalStore.getColumnNameForFlag(flag);
cache.removeValueForMessages(messageIds, columnName);
}
private void setFlagForThreadsInCache(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
String columnName = LocalStore.getColumnNameForFlag(flag);
String value = Integer.toString((newState) ? 1 : 0);
cache.setValueForThreads(threadRootIds, columnName, value);
}
private void removeFlagForThreadsFromCache(final Account account, final List<Long> messageIds,
final Flag flag) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
String columnName = LocalStore.getColumnNameForFlag(flag);
cache.removeValueForThreads(messageIds, columnName);
}
private MessagingController(Context context) {
this.context = context;
mThread = new Thread(this);
mThread.setName("MessagingController");
mThread.start();
if (memorizingListener != null) {
addListener(memorizingListener);
}
}
public synchronized static MessagingController getInstance(Context context) {
if (inst == null) {
inst = new MessagingController(context.getApplicationContext());
}
return inst;
}
public boolean isBusy() {
return mBusy;
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true) {
String commandDescription = null;
try {
final Command command = mCommands.take();
if (command != null) {
commandDescription = command.description;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence);
mBusy = true;
try {
command.runnable.run();
} catch (UnavailableAccountException e) {
// retry later
new Thread() {
@Override
public void run() {
try {
sleep(30 * 1000);
mCommands.put(command);
} catch (InterruptedException e) {
Log.e(K9.LOG_TAG, "interrupted while putting a pending command for"
+ " an unavailable account back into the queue."
+ " THIS SHOULD NEVER HAPPEN.");
}
}
} .start();
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") +
" Command '" + command.description + "' completed");
for (MessagingListener l : getListeners(command.listener)) {
l.controllerCommandCompleted(!mCommands.isEmpty());
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable) {
putCommand(mCommands, description, listener, runnable, true);
}
private void putBackground(String description, MessagingListener listener, Runnable runnable) {
putCommand(mCommands, description, listener, runnable, false);
}
private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) {
int retries = 10;
Exception e = null;
while (retries
try {
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
command.isForeground = isForeground;
queue.put(command);
return;
} catch (InterruptedException ie) {
try {
Thread.sleep(200);
} catch (InterruptedException ne) {
}
e = ie;
}
}
throw new Error(e);
}
public void addListener(MessagingListener listener) {
mListeners.add(listener);
refreshListener(listener);
}
public void refreshListener(MessagingListener listener) {
if (memorizingListener != null && listener != null) {
memorizingListener.refreshOther(listener);
}
}
public void removeListener(MessagingListener listener) {
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners() {
return mListeners;
}
public Set<MessagingListener> getListeners(MessagingListener listener) {
if (listener == null) {
return mListeners;
}
Set<MessagingListener> listeners = new HashSet<MessagingListener>(mListeners);
listeners.add(listener);
return listeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param listener
* @throws MessagingException
*/
public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
listFoldersSynchronous(account, refreshRemote, listener);
}
});
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method is called in the
* foreground.
* TODO this needs to cache the remote folder list
*
* @param account
* @param listener
* @throws MessagingException
*/
public void listFoldersSynchronous(final Account account, final boolean refreshRemote, final MessagingListener listener) {
for (MessagingListener l : getListeners(listener)) {
l.listFoldersStarted(account);
}
List <? extends Folder > localFolders = null;
if (!account.isAvailable(context)) {
Log.i(K9.LOG_TAG, "not listing folders of unavailable account");
} else {
try {
Store localStore = account.getLocalStore();
localFolders = localStore.getPersonalNamespaces(false);
if (refreshRemote || localFolders.isEmpty()) {
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners(listener)) {
l.listFolders(account, localFolders);
}
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, null, e);
return;
} finally {
if (localFolders != null) {
for (Folder localFolder : localFolders) {
closeFolder(localFolder);
}
}
}
}
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFinished(account);
}
}
private void doRefreshRemote(final Account account, final MessagingListener listener) {
put("doRefreshRemote", listener, new Runnable() {
@Override
public void run() {
List <? extends Folder > localFolders = null;
try {
Store store = account.getRemoteStore();
List <? extends Folder > remoteFolders = store.getPersonalNamespaces(false);
LocalStore localStore = account.getLocalStore();
Set<String> remoteFolderNames = new HashSet<String>();
List<LocalFolder> foldersToCreate = new LinkedList<LocalFolder>();
localFolders = localStore.getPersonalNamespaces(false);
Set<String> localFolderNames = new HashSet<String>();
for (Folder localFolder : localFolders) {
localFolderNames.add(localFolder.getName());
}
for (Folder remoteFolder : remoteFolders) {
if (localFolderNames.contains(remoteFolder.getName()) == false) {
LocalFolder localFolder = localStore.getFolder(remoteFolder.getName());
foldersToCreate.add(localFolder);
}
remoteFolderNames.add(remoteFolder.getName());
}
localStore.createFolders(foldersToCreate, account.getDisplayCount());
localFolders = localStore.getPersonalNamespaces(false);
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders) {
String localFolderName = localFolder.getName();
// FIXME: This is a hack used to clean up when we accidentally created the
// special placeholder folder "-NONE-".
if (K9.FOLDER_NONE.equals(localFolderName)) {
localFolder.delete(false);
}
if (!account.isSpecialFolder(localFolderName) &&
!remoteFolderNames.contains(localFolderName)) {
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces(false);
for (MessagingListener l : getListeners(listener)) {
l.listFolders(account, localFolders);
}
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFinished(account);
}
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFailed(account, "");
}
addErrorMessage(account, null, e);
} finally {
if (localFolders != null) {
for (Folder localFolder : localFolders) {
closeFolder(localFolder);
}
}
}
}
});
}
/**
* Find all messages in any local account which match the query 'query'
* @throws MessagingException
*/
public void searchLocalMessages(final LocalSearch search, final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
searchLocalMessagesSynchronous(search, listener);
}
});
}
public void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) {
final AccountStats stats = new AccountStats();
final Set<String> uuidSet = new HashSet<String>(Arrays.asList(search.getAccountUuids()));
List<Account> accounts = Preferences.getPreferences(context).getAccounts();
boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS);
// for every account we want to search do the query in the localstore
for (final Account account : accounts) {
if (!allAccounts && !uuidSet.contains(account.getUuid())) {
continue;
}
// Collecting statistics of the search result
MessageRetrievalListener retrievalListener = new MessageRetrievalListener<LocalMessage>() {
@Override
public void messageStarted(String message, int number, int ofTotal) {}
@Override
public void messagesFinished(int number) {}
@Override
public void messageFinished(LocalMessage message, int number, int ofTotal) {
if (!isMessageSuppressed(message)) {
List<LocalMessage> messages = new ArrayList<LocalMessage>();
messages.add(message);
stats.unreadMessageCount += (!message.isSet(Flag.SEEN)) ? 1 : 0;
stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0;
if (listener != null) {
listener.listLocalMessagesAddMessages(account, null, messages);
}
}
}
};
// alert everyone the search has started
if (listener != null) {
listener.listLocalMessagesStarted(account, null);
}
// build and do the query in the localstore
try {
LocalStore localStore = account.getLocalStore();
localStore.searchForMessages(retrievalListener, search);
} catch (Exception e) {
if (listener != null) {
listener.listLocalMessagesFailed(account, null, e.getMessage());
}
addErrorMessage(account, null, e);
} finally {
if (listener != null) {
listener.listLocalMessagesFinished(account, null);
}
}
}
// publish the total search statistics
if (listener != null) {
listener.searchStats(stats);
}
}
public Future<?> searchRemoteMessages(final String acctUuid, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener) {
if (K9.DEBUG) {
String msg = "searchRemoteMessages ("
+ "acct=" + acctUuid
+ ", folderName = " + folderName
+ ", query = " + query
+ ")";
Log.i(K9.LOG_TAG, msg);
}
return threadPool.submit(new Runnable() {
@Override
public void run() {
searchRemoteMessagesSynchronous(acctUuid, folderName, query, requiredFlags, forbiddenFlags, listener);
}
});
}
public void searchRemoteMessagesSynchronous(final String acctUuid, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener) {
final Account acct = Preferences.getPreferences(context).getAccount(acctUuid);
if (listener != null) {
listener.remoteSearchStarted(folderName);
}
List<Message> extraResults = new ArrayList<Message>();
try {
Store remoteStore = acct.getRemoteStore();
LocalStore localStore = acct.getLocalStore();
if (remoteStore == null || localStore == null) {
throw new MessagingException("Could not get store");
}
Folder remoteFolder = remoteStore.getFolder(folderName);
LocalFolder localFolder = localStore.getFolder(folderName);
if (remoteFolder == null || localFolder == null) {
throw new MessagingException("Folder not found");
}
List<Message> messages = remoteFolder.search(query, requiredFlags, forbiddenFlags);
if (K9.DEBUG) {
Log.i("Remote Search", "Remote search got " + messages.size() + " results");
}
// There's no need to fetch messages already completely downloaded
List<Message> remoteMessages = localFolder.extractNewMessages(messages);
messages.clear();
if (listener != null) {
listener.remoteSearchServerQueryComplete(folderName, remoteMessages.size(), acct.getRemoteSearchNumResults());
}
Collections.sort(remoteMessages, new UidReverseComparator());
int resultLimit = acct.getRemoteSearchNumResults();
if (resultLimit > 0 && remoteMessages.size() > resultLimit) {
extraResults = remoteMessages.subList(resultLimit, remoteMessages.size());
remoteMessages = remoteMessages.subList(0, resultLimit);
}
loadSearchResultsSynchronous(remoteMessages, localFolder, remoteFolder, listener);
} catch (Exception e) {
if (Thread.currentThread().isInterrupted()) {
Log.i(K9.LOG_TAG, "Caught exception on aborted remote search; safe to ignore.", e);
} else {
Log.e(K9.LOG_TAG, "Could not complete remote search", e);
if (listener != null) {
listener.remoteSearchFailed(null, e.getMessage());
}
addErrorMessage(acct, null, e);
}
} finally {
if (listener != null) {
listener.remoteSearchFinished(folderName, 0, acct.getRemoteSearchNumResults(), extraResults);
}
}
}
public void loadSearchResults(final Account account, final String folderName, final List<Message> messages, final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
if (listener != null) {
listener.enableProgressIndicator(true);
}
try {
Store remoteStore = account.getRemoteStore();
LocalStore localStore = account.getLocalStore();
if (remoteStore == null || localStore == null) {
throw new MessagingException("Could not get store");
}
Folder remoteFolder = remoteStore.getFolder(folderName);
LocalFolder localFolder = localStore.getFolder(folderName);
if (remoteFolder == null || localFolder == null) {
throw new MessagingException("Folder not found");
}
loadSearchResultsSynchronous(messages, localFolder, remoteFolder, listener);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Exception in loadSearchResults: " + e);
addErrorMessage(account, null, e);
} finally {
if (listener != null) {
listener.enableProgressIndicator(false);
}
}
}
});
}
public void loadSearchResultsSynchronous(List<Message> messages, LocalFolder localFolder, Folder remoteFolder, MessagingListener listener) throws MessagingException {
final FetchProfile header = new FetchProfile();
header.add(FetchProfile.Item.FLAGS);
header.add(FetchProfile.Item.ENVELOPE);
final FetchProfile structure = new FetchProfile();
structure.add(FetchProfile.Item.STRUCTURE);
int i = 0;
for (Message message : messages) {
i++;
LocalMessage localMsg = localFolder.getMessage(message.getUid());
if (localMsg == null) {
remoteFolder.fetch(Collections.singletonList(message), header, null);
//fun fact: ImapFolder.fetch can't handle getting STRUCTURE at same time as headers
remoteFolder.fetch(Collections.singletonList(message), structure, null);
localFolder.appendMessages(Collections.singletonList(message));
localMsg = localFolder.getMessage(message.getUid());
}
if (listener != null) {
listener.remoteSearchAddMessage(remoteFolder.getName(), localMsg, i, messages.size());
}
}
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener) {
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
if (localFolder.getVisibleLimit() > 0) {
localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount());
}
synchronizeMailbox(account, folder, listener, null);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Collection<Account> accounts) {
for (Account account : accounts) {
account.resetVisibleLimits();
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
* @param providedRemoteFolder TODO
*/
public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) {
putBackground("synchronizeMailbox", listener, new Runnable() {
@Override
public void run() {
synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
* @param providedRemoteFolder TODO
*/
private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) {
Folder remoteFolder = null;
LocalFolder tLocalFolder = null;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder);
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxStarted(account, folder);
}
/*
* We don't ever sync the Outbox or errors folder
*/
if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) {
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
return;
}
Exception commandException = null;
try {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription());
try {
processPendingCommandsSynchronous(account);
} catch (Exception e) {
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder);
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(Folder.OPEN_MODE_RW);
localFolder.updateLastUid();
List<? extends Message> localMessages = localFolder.getMessages(null);
Map<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages) {
localUidMap.put(message.getUid(), message);
}
if (providedRemoteFolder != null) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder);
remoteFolder = providedRemoteFolder;
} else {
Store remoteStore = account.getRemoteStore();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder);
remoteFolder = remoteStore.getFolder(folder);
if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) {
return;
}
/*
* Synchronization process:
*
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder);
remoteFolder.open(Folder.OPEN_MODE_RW);
if (Expunge.EXPUNGE_ON_POLL == account.getExpungePolicy()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder);
remoteFolder.expunge();
}
}
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
if (visibleLimit < 0) {
visibleLimit = K9.DEFAULT_VISIBLE_LIMIT;
}
final List<Message> remoteMessages = new ArrayList<Message>();
Map<String, Message> remoteUidMap = new HashMap<String, Message>();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount);
final Date earliestDate = account.getEarliestPollDate();
if (remoteMessageCount > 0) {
/* Message numbers start at 1. */
int remoteStart;
if (visibleLimit > 0) {
remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
} else {
remoteStart = 1;
}
int remoteEnd = remoteMessageCount;
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder);
final AtomicInteger headerProgress = new AtomicInteger(0);
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxHeadersStarted(account, folder);
}
List<? extends Message> remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null);
int messageCount = remoteMessageArray.size();
for (Message thisMess : remoteMessageArray) {
headerProgress.incrementAndGet();
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount);
}
Message localMessage = localUidMap.get(thisMess.getUid());
if (localMessage == null || !localMessage.olderThan(earliestDate)) {
remoteMessages.add(thisMess);
remoteUidMap.put(thisMess.getUid(), thisMess);
}
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder);
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size());
}
} else if (remoteMessageCount < 0) {
throw new Exception("Message count " + remoteMessageCount + " for folder " + folder);
}
/*
* Remove any messages that are in the local store but no longer on the remote store or are too old
*/
if (account.syncRemoteDeletions()) {
List<Message> destroyMessages = new ArrayList<Message>();
for (Message localMessage : localMessages) {
if (remoteUidMap.get(localMessage.getUid()) == null) {
destroyMessages.add(localMessage);
}
}
localFolder.destroyMessages(destroyMessages);
for (Message destroyMessage : destroyMessages) {
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxRemovedMessage(account, folder, destroyMessage);
}
}
}
localMessages = null;
/*
* Now we download the actual content of messages.
*/
int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false);
int unreadMessageCount = localFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder, unreadMessageCount);
}
/* Notify listeners that we're finally done. */
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder +
" @ " + new Date() + " with " + newMessages + " new messages");
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (commandException != null) {
String rootMessage = getRootCauseMessage(commandException);
Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" +
tLocalFolder.getName() + " was '" + rootMessage + "'");
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null) {
try {
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
notifyUserIfCertificateProblem(context, e, account, true);
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date());
} finally {
if (providedRemoteFolder == null) {
closeFolder(remoteFolder);
}
closeFolder(tLocalFolder);
}
}
private void closeFolder(Folder f) {
if (f != null) {
f.close();
}
}
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException {
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName())) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder);
return false;
}
}
}
return true;
}
/**
* Fetches the messages described by inputMessages from the remote store and writes them to
* local storage.
*
* @param account
* The account the remote store belongs to.
* @param remoteFolder
* The remote folder to download messages from.
* @param localFolder
* The {@link LocalFolder} instance corresponding to the remote folder.
* @param inputMessages
* A list of messages objects that store the UIDs of which messages to download.
* @param flagSyncOnly
* Only flags will be fetched from the remote store if this is {@code true}.
*
* @return The number of downloaded messages that are not flagged as {@link Flag#SEEN}.
*
* @throws MessagingException
*/
private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages,
boolean flagSyncOnly) throws MessagingException {
final Date earliestDate = account.getEarliestPollDate();
Date downloadStarted = new Date(); // now
if (earliestDate != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate);
}
}
final String folder = remoteFolder.getName();
int unreadBeforeStart = 0;
try {
AccountStats stats = account.getStats(context);
unreadBeforeStart = stats.unreadMessageCount;
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
List<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages) {
evaluateMessageForDownload(message, folder, localFolder, remoteFolder, account, unsyncedMessages, syncFlagMessages , flagSyncOnly);
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final List<Message> largeMessages = new ArrayList<Message>();
final List<Message> smallMessages = new ArrayList<Message>();
if (!unsyncedMessages.isEmpty()) {
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.sort(unsyncedMessages, new UidReverseComparator());
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if ((visibleLimit > 0) && (listSize > visibleLimit)) {
unsyncedMessages = unsyncedMessages.subList(0, visibleLimit);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags()) {
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, fp);
String updatedPushState = localFolder.getPushState();
for (Message message : unsyncedMessages) {
String newPushState = remoteFolder.getNewPushState(updatedPushState, message);
if (newPushState != null) {
updatedPushState = newPushState;
}
}
localFolder.setPushState(updatedPushState);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
downloadSmallMessages(account, remoteFolder, localFolder, smallMessages, progress, unreadBeforeStart, newMessages, todo, fp);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
downloadLargeMessages(account, remoteFolder, localFolder, largeMessages, progress, unreadBeforeStart, newMessages, todo, fp);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
refreshLocalMessageFlags(account, remoteFolder, localFolder, syncFlagMessages, progress, todo);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener() {
@Override
public void messageRemoved(Message message) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
// If the oldest message seen on this sync is newer than
// the oldest message seen on the previous sync, then
// we want to move our high-water mark forward
// this is all here just for pop which only syncs inbox
// this would be a little wrong for IMAP (we'd want a folder-level pref, not an account level pref.)
// fortunately, we just don't care.
Long oldestMessageTime = localFolder.getOldestMessageDate();
if (oldestMessageTime != null) {
Date oldestExtantMessage = new Date(oldestMessageTime);
if (oldestExtantMessage.before(downloadStarted) &&
oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) {
account.setLatestOldMessageSeenTime(oldestExtantMessage.getTime());
account.save(Preferences.getPreferences(context));
}
}
return newMessages.get();
}
private void evaluateMessageForDownload(final Message message, final String folder,
final LocalFolder localFolder,
final Folder remoteFolder,
final Account account,
final List<Message> unsyncedMessages,
final List<Message> syncFlagMessages,
boolean flagSyncOnly) throws MessagingException {
if (message.isSet(Flag.DELETED)) {
syncFlagMessages.add(message);
return;
}
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null) {
if (!flagSyncOnly) {
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded");
unsyncedMessages.add(message);
} else {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
// Store the updated message locally
localFolder.appendMessages(Collections.singletonList(message));
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
} else if (!localMessage.isSet(Flag.DELETED)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store");
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
unsyncedMessages.add(message);
} else {
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null) {
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
private <T extends Message> void fetchUnsyncedMessages(final Account account, final Folder<T> remoteFolder,
final LocalFolder localFolder,
List<T> unsyncedMessages,
final List<Message> smallMessages,
final List<Message> largeMessages,
final AtomicInteger progress,
final int todo,
FetchProfile fp) throws MessagingException {
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
/*
* Messages to be batch written
*/
final List<Message> chunk = new ArrayList<Message>(UNSYNC_CHUNK_SIZE);
remoteFolder.fetch(unsyncedMessages, fp,
new MessageRetrievalListener<T>() {
@Override
public void messageFinished(T message, int number, int ofTotal) {
try {
if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) {
if (K9.DEBUG) {
if (message.isSet(Flag.DELETED)) {
Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid()
+ " was marked deleted on server, skipping");
} else {
Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than "
+ earliestDate + ", skipping");
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
return;
}
if (account.getMaximumAutoDownloadMessageSize() > 0 &&
message.getSize() > account.getMaximumAutoDownloadMessageSize()) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
// And include it in the view
if (message.getSubject() != null && message.getFrom() != null) {
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
// keep message for delayed storing
chunk.add(message);
if (chunk.size() >= UNSYNC_CHUNK_SIZE) {
writeUnsyncedMessages(chunk, localFolder, account, folder);
chunk.clear();
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
@Override
public void messageStarted(String uid, int number, int ofTotal) {}
@Override
public void messagesFinished(int total) {
// FIXME this method is almost never invoked by various Stores! Don't rely on it unless fixed!!
}
});
if (!chunk.isEmpty()) {
writeUnsyncedMessages(chunk, localFolder, account, folder);
chunk.clear();
}
}
/**
* Actual storing of messages
*
* <br>
* FIXME: <strong>This method should really be moved in the above MessageRetrievalListener once {@link MessageRetrievalListener#messagesFinished(int)} is properly invoked by various stores</strong>
*
* @param messages Never <code>null</code>.
* @param localFolder
* @param account
* @param folder
*/
private void writeUnsyncedMessages(final List<Message> messages, final LocalFolder localFolder, final Account account, final String folder) {
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Batch writing " + Integer.toString(messages.size()) + " messages");
}
try {
// Store the new message locally
localFolder.appendMessages(messages);
for (final Message message : messages) {
final LocalMessage localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
for (final MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
} catch (final Exception e) {
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) {
if (account.isSearchByDateCapable() && message.olderThan(earliestDate)) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
return false;
}
return true;
}
private <T extends Message> void downloadSmallMessages(final Account account, final Folder<T> remoteFolder,
final LocalFolder localFolder,
List<T> smallMessages,
final AtomicInteger progress,
final int unreadBeforeStart,
final AtomicInteger newMessages,
final int todo,
FetchProfile fp) throws MessagingException {
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages,
fp, new MessageRetrievalListener<T>() {
@Override
public void messageFinished(final T message, int number, int ofTotal) {
try {
if (!shouldImportMessage(account, folder, message, progress, earliestDate)) {
progress.incrementAndGet();
return;
}
// Store the updated message locally
final LocalMessage localMessage = localFolder.storeSmallMessage(message, new Runnable() {
@Override
public void run() {
progress.incrementAndGet();
}
});
// Increment the number of "new messages" if the newly downloaded message is
// not marked as read.
if (!localMessage.isSet(Flag.SEEN)) {
newMessages.incrementAndGet();
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
// Send a notification of this message
if (shouldNotifyForMessage(account, localFolder, message)) {
// Notify with the localMessage so that we don't have to recalculate the content preview.
notifyAccount(context, account, localMessage, unreadBeforeStart);
}
} catch (MessagingException me) {
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
@Override
public void messageStarted(String uid, int number, int ofTotal) {}
@Override
public void messagesFinished(int total) {}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
}
private <T extends Message> void downloadLargeMessages(final Account account, final Folder<T> remoteFolder,
final LocalFolder localFolder,
List<T> largeMessages,
final AtomicInteger progress,
final int unreadBeforeStart,
final AtomicInteger newMessages,
final int todo,
FetchProfile fp) throws MessagingException {
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages, fp, null);
for (T message : largeMessages) {
if (!shouldImportMessage(account, folder, message, progress, earliestDate)) {
progress.incrementAndGet();
continue;
}
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(Collections.singletonList(message), fp, null);
// Store the updated message locally
localFolder.appendMessages(Collections.singletonList(message));
Message localMessage = localFolder.getMessage(message.getUid());
// Certain (POP3) servers give you the whole message even when you ask for only the first x Kb
if (!message.isSet(Flag.X_DOWNLOADED_FULL)) {
/*
* Mark the message as fully downloaded if the message size is smaller than
* the account's autodownload size limit, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*
* If there is no limit on autodownload size, that's the same as the message
* being smaller than the max size
*/
if (account.getMaximumAutoDownloadMessageSize() == 0 || message.getSize() < account.getMaximumAutoDownloadMessageSize()) {
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
} else {
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
Set<Part> viewables = MessageExtractor.collectTextParts(message);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
remoteFolder.fetchPart(message, part, null);
}
// Store the updated message locally
localFolder.appendMessages(Collections.singletonList(message));
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
progress.incrementAndGet();
// TODO do we need to re-fetch this here?
LocalMessage localMessage = localFolder.getMessage(message.getUid());
// Increment the number of "new messages" if the newly downloaded message is
// not marked as read.
if (!localMessage.isSet(Flag.SEEN)) {
newMessages.incrementAndGet();
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
// Send a notification of this message
if (shouldNotifyForMessage(account, localFolder, message)) {
// Notify with the localMessage so that we don't have to recalculate the content preview.
notifyAccount(context, account, localMessage, unreadBeforeStart);
}
}//for large messages
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
}
private void refreshLocalMessageFlags(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
List<Message> syncFlagMessages,
final AtomicInteger progress,
final int todo
) throws MessagingException {
final String folder = remoteFolder.getName();
if (remoteFolder.supportsFetchingFlags()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
List<Message> undeletedMessages = new LinkedList<Message>();
for (Message message : syncFlagMessages) {
if (!message.isSet(Flag.DELETED)) {
undeletedMessages.add(message);
}
}
remoteFolder.fetch(undeletedMessages, fp, null);
for (Message remoteMessage : syncFlagMessages) {
LocalMessage localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged) {
boolean shouldBeNotifiedOf = false;
if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(localMessage)) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
} else {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
if (shouldNotifyForMessage(account, localFolder, localMessage)) {
shouldBeNotifiedOf = true;
}
}
// we're only interested in messages that need removing
if (!shouldBeNotifiedOf) {
NotificationData data = getNotificationData(account, null);
if (data != null) {
synchronized (data) {
MessageReference ref = localMessage.makeMessageReference();
if (data.removeMatchingMessage(context, ref)) {
notifyAccountWithDataLocked(context, account, null, data);
}
}
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
}
private boolean syncFlags(LocalMessage localMessage, Message remoteMessage) throws MessagingException {
boolean messageChanged = false;
if (localMessage == null || localMessage.isSet(Flag.DELETED)) {
return false;
}
if (remoteMessage.isSet(Flag.DELETED)) {
if (localMessage.getFolder().syncRemoteDeletions()) {
localMessage.setFlag(Flag.DELETED, true);
messageChanged = true;
}
} else {
for (Flag flag : MessagingController.SYNC_FLAGS) {
if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) {
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
}
return messageChanged;
}
private String getRootCauseMessage(Throwable t) {
Throwable rootCause = t;
Throwable nextCause = rootCause;
do {
nextCause = rootCause.getCause();
if (nextCause != null) {
rootCause = nextCause;
}
} while (nextCause != null);
if (rootCause instanceof MessagingException) {
return rootCause.getMessage();
} else {
// Remove the namespace on the exception so we have a fighting chance of seeing more of the error in the
// notification.
return (rootCause.getLocalizedMessage() != null)
? (rootCause.getClass().getSimpleName() + ": " + rootCause.getLocalizedMessage())
: rootCause.getClass().getSimpleName();
}
}
private void queuePendingCommand(Account account, PendingCommand command) {
try {
LocalStore localStore = account.getLocalStore();
localStore.addPendingCommand(command);
} catch (Exception e) {
addErrorMessage(account, null, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account) {
putBackground("processPendingCommands", null, new Runnable() {
@Override
public void run() {
try {
processPendingCommandsSynchronous(account);
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to process pending command because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "processPendingCommands", me);
addErrorMessage(account, null, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException {
LocalStore localStore = account.getLocalStore();
List<PendingCommand> commands = localStore.getPendingCommands();
int progress = 0;
int todo = commands.size();
if (todo == 0) {
return;
}
for (MessagingListener l : getListeners()) {
l.pendingCommandsProcessing(account);
l.synchronizeMailboxProgress(account, null, progress, todo);
}
PendingCommand processingCommand = null;
try {
for (PendingCommand command : commands) {
processingCommand = command;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'");
String[] components = command.command.split("\\.");
String commandTitle = components[components.length - 1];
for (MessagingListener l : getListeners()) {
l.pendingCommandStarted(account, commandTitle);
}
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try {
if (PENDING_COMMAND_APPEND.equals(command.command)) {
processPendingAppend(command, account);
} else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) {
processPendingSetFlag(command, account);
} else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) {
processPendingSetFlagOld(command, account);
} else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) {
processPendingMarkAllAsRead(command, account);
} else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) {
processPendingMoveOrCopyOld2(command, account);
} else if (PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW.equals(command.command)) {
processPendingMoveOrCopy(command, account);
} else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) {
processPendingMoveOrCopyOld(command, account);
} else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) {
processPendingEmptyTrash(command, account);
} else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) {
processPendingExpunge(command, account);
}
localStore.removePendingCommand(command);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'");
} catch (MessagingException me) {
if (me.isPermanentFailure()) {
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
} else {
throw me;
}
} finally {
progress++;
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, null, progress, todo);
l.pendingCommandCompleted(account, commandTitle);
}
}
}
} catch (MessagingException me) {
notifyUserIfCertificateProblem(context, me, account, true);
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
} finally {
for (MessagingListener l : getListeners()) {
l.pendingCommandsFinished(account);
}
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException {
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder)) {
return;
}
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
LocalMessage localMessage = localFolder.getMessage(uid);
if (localMessage == null) {
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return;
}
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null) {
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) {
Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null) {
Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
} else {
Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(Collections.singletonList(localMessage) , fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(Collections.singletonList(localMessage));
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
} else {
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(Collections.singletonList(remoteMessage), fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate != null && remoteDate.compareTo(localDate) > 0) {
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.destroy();
} else {
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(Collections.singletonList(localMessage), fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(Collections.singletonList(localMessage));
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
if (remoteDate != null) {
remoteMessage.setFlag(Flag.DELETED, true);
if (Expunge.EXPUNGE_IMMEDIATELY == account.getExpungePolicy()) {
remoteFolder.expunge();
}
}
}
}
} finally {
closeFolder(remoteFolder);
closeFolder(localFolder);
}
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) {
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW;
int length = 4 + uids.length;
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
command.arguments[3] = Boolean.toString(false);
System.arraycopy(uids, 0, command.arguments, 4, uids.length);
queuePendingCommand(account, command);
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[], Map<String, String> uidMap) {
if (uidMap == null || uidMap.isEmpty()) {
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, uids);
} else {
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW;
int length = 4 + uidMap.keySet().size() + uidMap.values().size();
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
command.arguments[3] = Boolean.toString(true);
System.arraycopy(uidMap.keySet().toArray(), 0, command.arguments, 4, uidMap.keySet().size());
System.arraycopy(uidMap.values().toArray(), 0, command.arguments, 4 + uidMap.keySet().size(), uidMap.values().size());
queuePendingCommand(account, command);
}
}
/**
* Convert pending command to new format and call
* {@link #processPendingMoveOrCopy(PendingCommand, Account)}.
*
* <p>
* TODO: This method is obsolete and is only for transition from K-9 4.0 to K-9 4.2
* Eventually, it should be removed.
* </p>
*
* @param command
* Pending move/copy command in old format.
* @param account
* The account the pending command belongs to.
*
* @throws MessagingException
* In case of an error.
*/
private void processPendingMoveOrCopyOld2(PendingCommand command, Account account)
throws MessagingException {
PendingCommand newCommand = new PendingCommand();
int len = command.arguments.length;
newCommand.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW;
newCommand.arguments = new String[len + 1];
newCommand.arguments[0] = command.arguments[0];
newCommand.arguments[1] = command.arguments[1];
newCommand.arguments[2] = command.arguments[2];
newCommand.arguments[3] = Boolean.toString(false);
System.arraycopy(command.arguments, 3, newCommand.arguments, 4, len - 3);
processPendingMoveOrCopy(newCommand, account);
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException {
Folder remoteSrcFolder = null;
Folder remoteDestFolder = null;
LocalFolder localDestFolder = null;
try {
String srcFolder = command.arguments[0];
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
String destFolder = command.arguments[1];
String isCopyS = command.arguments[2];
String hasNewUidsS = command.arguments[3];
boolean hasNewUids = false;
if (hasNewUidsS != null) {
hasNewUids = Boolean.parseBoolean(hasNewUidsS);
}
Store remoteStore = account.getRemoteStore();
remoteSrcFolder = remoteStore.getFolder(srcFolder);
Store localStore = account.getLocalStore();
localDestFolder = (LocalFolder) localStore.getFolder(destFolder);
List<Message> messages = new ArrayList<Message>();
/*
* We split up the localUidMap into two parts while sending the command, here we assemble it back.
*/
Map<String, String> localUidMap = new HashMap<String, String>();
if (hasNewUids) {
int offset = (command.arguments.length - 4) / 2;
for (int i = 4; i < 4 + offset; i++) {
localUidMap.put(command.arguments[i], command.arguments[i + offset]);
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
messages.add(remoteSrcFolder.getMessage(uid));
}
}
} else {
for (int i = 4; i < command.arguments.length; i++) {
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
messages.add(remoteSrcFolder.getMessage(uid));
}
}
}
boolean isCopy = false;
if (isCopyS != null) {
isCopy = Boolean.parseBoolean(isCopyS);
}
if (!remoteSrcFolder.exists()) {
throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(Folder.OPEN_MODE_RW);
if (remoteSrcFolder.getMode() != Folder.OPEN_MODE_RW) {
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy);
Map <String, String> remoteUidMap = null;
if (!isCopy && destFolder.equals(account.getTrashFolderName())) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
String destFolderName = destFolder;
if (K9.FOLDER_NONE.equals(destFolderName)) {
destFolderName = null;
}
remoteSrcFolder.delete(messages, destFolderName);
} else {
remoteDestFolder = remoteStore.getFolder(destFolder);
if (isCopy) {
remoteUidMap = remoteSrcFolder.copyMessages(messages, remoteDestFolder);
} else {
remoteUidMap = remoteSrcFolder.moveMessages(messages, remoteDestFolder);
}
}
if (!isCopy && Expunge.EXPUNGE_IMMEDIATELY == account.getExpungePolicy()) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder);
remoteSrcFolder.expunge();
}
/*
* This next part is used to bring the local UIDs of the local destination folder
* upto speed with the remote UIDs of remote destination folder.
*/
if (!localUidMap.isEmpty() && remoteUidMap != null && !remoteUidMap.isEmpty()) {
for (Map.Entry<String, String> entry : remoteUidMap.entrySet()) {
String remoteSrcUid = entry.getKey();
String localDestUid = localUidMap.get(remoteSrcUid);
String newUid = entry.getValue();
Message localDestMessage = localDestFolder.getMessage(localDestUid);
if (localDestMessage != null) {
localDestMessage.setUid(newUid);
localDestFolder.changeUid((LocalMessage)localDestMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, destFolder, localDestUid, newUid);
}
}
}
}
} finally {
closeFolder(remoteSrcFolder);
closeFolder(remoteDestFolder);
}
}
private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) {
putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() {
@Override
public void run() {
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = folderName;
command.arguments[1] = newState;
command.arguments[2] = flag;
System.arraycopy(uids, 0, command.arguments, 3, uids.length);
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder)) {
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[1]);
Flag flag = Flag.valueOf(command.arguments[2]);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(flag)) {
return;
}
try {
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++) {
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
messages.add(remoteFolder.getMessage(uid));
}
}
if (messages.isEmpty()) {
return;
}
remoteFolder.setFlags(messages, Collections.singleton(flag), newState);
} finally {
closeFolder(remoteFolder);
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingSetFlagOld(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder)) {
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid);
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Folder remoteFolder = null;
try {
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null) {
return;
}
remoteMessage.setFlag(flag, newState);
} finally {
closeFolder(remoteFolder);
}
}
private void queueExpunge(final Account account, final String folderName) {
putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() {
@Override
public void run() {
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EXPUNGE;
command.arguments = new String[1];
command.arguments[0] = folderName;
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
private void processPendingExpunge(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder)) {
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
try {
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
remoteFolder.expunge();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder);
} finally {
closeFolder(remoteFolder);
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingMoveOrCopyOld(PendingCommand command, Account account)
throws MessagingException {
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null) {
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
Store remoteStore = account.getRemoteStore();
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists()) {
throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(Folder.OPEN_MODE_RW);
if (remoteSrcFolder.getMode() != Folder.OPEN_MODE_RW) {
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null) {
throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (!isCopy && destFolder.equals(account.getTrashFolderName())) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message");
remoteMessage.delete(account.getTrashFolderName());
remoteSrcFolder.close();
return;
}
remoteDestFolder.open(Folder.OPEN_MODE_RW);
if (remoteDestFolder.getMode() != Folder.OPEN_MODE_RW) {
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy) {
remoteSrcFolder.copyMessages(Collections.singletonList(remoteMessage), remoteDestFolder);
} else {
remoteSrcFolder.moveMessages(Collections.singletonList(remoteMessage), remoteDestFolder);
}
remoteSrcFolder.close();
remoteDestFolder.close();
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException {
String folder = command.arguments[0];
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
Store localStore = account.getLocalStore();
localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(Folder.OPEN_MODE_RW);
List<? extends Message> messages = localFolder.getMessages(null, false);
for (Message message : messages) {
if (!message.isSet(Flag.SEEN)) {
message.setFlag(Flag.SEEN, true);
for (MessagingListener l : getListeners()) {
l.listLocalMessagesUpdateMessage(account, folder, message);
}
}
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder, 0);
}
if (account.getErrorFolderName().equals(folder)) {
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(Flag.SEEN)) {
return;
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
remoteFolder.setFlags(Collections.singleton(Flag.SEEN), true);
remoteFolder.close();
} catch (UnsupportedOperationException uoe) {
Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
} finally {
closeFolder(localFolder);
closeFolder(remoteFolder);
}
}
void notifyUserIfCertificateProblem(Context context, Exception e,
Account account, boolean incoming) {
if (!(e instanceof CertificateValidationException)) {
return;
}
CertificateValidationException cve = (CertificateValidationException) e;
if (!cve.needsUserAttention()) {
return;
}
final int id = incoming
? K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber()
: K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber();
final Intent i = incoming
? AccountSetupIncoming.intentActionEditIncomingSettings(context, account)
: AccountSetupOutgoing.intentActionEditOutgoingSettings(context, account);
final PendingIntent pi = PendingIntent.getActivity(context,
account.getAccountNumber(), i, PendingIntent.FLAG_UPDATE_CURRENT);
final String title = context.getString(
R.string.notification_certificate_error_title, account.getDescription());
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(platformSupportsLockScreenNotifications()
? R.drawable.ic_notify_new_mail_vector
: R.drawable.ic_notify_new_mail);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(true);
builder.setTicker(title);
builder.setContentTitle(title);
builder.setContentText(context.getString(R.string.notification_certificate_error_text));
builder.setContentIntent(pi);
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
configureNotification(builder, null, null,
K9.NOTIFICATION_LED_FAILURE_COLOR,
K9.NOTIFICATION_LED_BLINK_FAST, true);
final NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(null, id, builder.build());
}
public void clearCertificateErrorNotifications(Context context,
final Account account, CheckDirection direction) {
final NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (direction == CheckDirection.INCOMING) {
nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber());
} else {
nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber());
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, String subject, Throwable t) {
try {
if (t == null) {
return;
}
CharArrayWriter baos = new CharArrayWriter(t.getStackTrace().length * 10);
PrintWriter ps = new PrintWriter(baos);
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
ps.format("K9-Mail version: %s\r\n", packageInfo.versionName);
} catch (Exception e) {
// ignore
}
ps.format("Device make: %s\r\n", Build.MANUFACTURER);
ps.format("Device model: %s\r\n", Build.MODEL);
ps.format("Android version: %s\r\n\r\n", Build.VERSION.RELEASE);
t.printStackTrace(ps);
ps.close();
if (subject == null) {
subject = getRootCauseMessage(t);
}
addErrorMessage(account, subject, baos.toString());
} catch (Throwable it) {
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
}
public void addErrorMessage(Account account, String subject, String body) {
if (!K9.DEBUG) {
return;
}
if (!loopCatch.compareAndSet(false, true)) {
return;
}
try {
if (body == null || body.length() < 1) {
return;
}
Store localStore = account.getLocalStore();
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
MimeMessage message = new MimeMessage();
MimeMessageHelper.setBody(message, new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate, K9.hideTimeZone());
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
localFolder.appendMessages(Collections.singletonList(message));
localFolder.clearMessagesOlderThan(nowTime - (15 * 60 * 1000));
} catch (Throwable it) {
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
} finally {
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(EMPTY_STRING_ARRAY);
queuePendingCommand(account, command);
processPendingCommands(account);
}
public void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState) {
setFlagInCache(account, messageIds, flag, newState);
threadPool.execute(new Runnable() {
@Override
public void run() {
setFlagSynchronous(account, messageIds, flag, newState, false);
}
});
}
public void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState) {
setFlagForThreadsInCache(account, threadRootIds, flag, newState);
threadPool.execute(new Runnable() {
@Override
public void run() {
setFlagSynchronous(account, threadRootIds, flag, newState, true);
}
});
}
private void setFlagSynchronous(final Account account, final List<Long> ids,
final Flag flag, final boolean newState, final boolean threadedList) {
LocalStore localStore;
try {
localStore = account.getLocalStore();
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Couldn't get LocalStore instance", e);
return;
}
// Update affected messages in the database. This should be as fast as possible so the UI
// can be updated with the new state.
try {
if (threadedList) {
localStore.setFlagForThreads(ids, flag, newState);
removeFlagForThreadsFromCache(account, ids, flag);
} else {
localStore.setFlag(ids, flag, newState);
removeFlagFromCache(account, ids, flag);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Couldn't set flags in local database", e);
}
// Read folder name and UID of messages from the database
Map<String, List<String>> folderMap;
try {
folderMap = localStore.getFoldersAndUids(ids, threadedList);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Couldn't get folder name and UID of messages", e);
return;
}
// Loop over all folders
for (Entry<String, List<String>> entry : folderMap.entrySet()) {
String folderName = entry.getKey();
// Notify listeners of changed folder status
LocalFolder localFolder = localStore.getFolder(folderName);
try {
int unreadMessageCount = localFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
} catch (MessagingException e) {
Log.w(K9.LOG_TAG, "Couldn't get unread count for folder: " + folderName, e);
}
// The error folder is always a local folder
// TODO: Skip the remote part for all local-only folders
if (account.getErrorFolderName().equals(folderName)) {
continue;
}
// Send flag change to server
String[] uids = entry.getValue().toArray(EMPTY_STRING_ARRAY);
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
}
}
/**
* Set or remove a flag for a set of messages in a specific folder.
*
* <p>
* The {@link Message} objects passed in are updated to reflect the new flag state.
* </p>
*
* @param account
* The account the folder containing the messages belongs to.
* @param folderName
* The name of the folder.
* @param messages
* The messages to change the flag for.
* @param flag
* The flag to change.
* @param newState
* {@code true}, if the flag should be set. {@code false} if it should be removed.
*/
public void setFlag(Account account, String folderName, List<? extends Message> messages, Flag flag,
boolean newState) {
// TODO: Put this into the background, but right now some callers depend on the message
// objects being modified right after this method returns.
Folder localFolder = null;
try {
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
localFolder.open(Folder.OPEN_MODE_RW);
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && !newState &&
account.getOutboxFolderName().equals(folderName)) {
for (Message message : messages) {
String uid = message.getUid();
if (uid != null) {
sendCount.remove(uid);
}
}
}
// Update the messages in the local store
localFolder.setFlags(messages, Collections.singleton(flag), newState);
int unreadMessageCount = localFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
/*
* Handle the remote side
*/
// The error folder is always a local folder
// TODO: Skip the remote part for all local-only folders
if (account.getErrorFolderName().equals(folderName)) {
return;
}
String[] uids = new String[messages.size()];
for (int i = 0, end = uids.length; i < end; i++) {
uids[i] = messages.get(i).getUid();
}
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException(me);
} finally {
closeFolder(localFolder);
}
}
/**
* Set or remove a flag for a message referenced by message UID.
*
* @param account
* The account the folder containing the message belongs to.
* @param folderName
* The name of the folder.
* @param uid
* The UID of the message to change the flag for.
* @param flag
* The flag to change.
* @param newState
* {@code true}, if the flag should be set. {@code false} if it should be removed.
*/
public void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState) {
Folder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
localFolder.open(Folder.OPEN_MODE_RW);
Message message = localFolder.getMessage(uid);
if (message != null) {
setFlag(account, folderName, Collections.singletonList(message), flag, newState);
}
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException(me);
} finally {
closeFolder(localFolder);
}
}
public void clearAllPending(final Account account) {
try {
Log.w(K9.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = account.getLocalStore();
localStore.removePendingCommands();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, null, me);
}
}
public void loadMessageForViewRemote(final Account account, final String folder,
final String uid, final MessagingListener listener) {
put("loadMessageForViewRemote", listener, new Runnable() {
@Override
public void run() {
loadMessageForViewRemoteSynchronous(account, folder, uid, listener, false, false);
}
});
}
public boolean loadMessageForViewRemoteSynchronous(final Account account, final String folder,
final String uid, final MessagingListener listener, final boolean force,
final boolean loadPartialFromSearch) {
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(Folder.OPEN_MODE_RW);
LocalMessage message = localFolder.getMessage(uid);
if (uid.startsWith(K9.LOCAL_UID_PREFIX)) {
Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully.");
// ASH move toast
android.widget.Toast.makeText(context,
"Message has local UID so cannot download fully",
android.widget.Toast.LENGTH_LONG).show();
// TODO: Using X_DOWNLOADED_FULL is wrong because it's only a partial message. But
// one we can't download completely. Maybe add a new flag; X_PARTIAL_MESSAGE ?
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false);
}
/* commented out because this was pulled from another unmerged branch:
} else if (localFolder.isLocalOnly() && !force) {
Log.w(K9.LOG_TAG, "Message in local-only folder so cannot download fully.");
// ASH move toast
android.widget.Toast.makeText(mApplication,
"Message in local-only folder so cannot download fully",
android.widget.Toast.LENGTH_LONG).show();
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false);
}*/
if (message.isSet(Flag.X_DOWNLOADED_FULL)) {
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(Collections.singletonList(message), fp, null);
} else {
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(Folder.OPEN_MODE_RW);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(Collections.singletonList(remoteMessage), fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(Collections.singletonList(remoteMessage));
if (loadPartialFromSearch) {
fp.add(FetchProfile.Item.BODY);
}
fp.add(FetchProfile.Item.ENVELOPE);
message = localFolder.getMessage(uid);
localFolder.fetch(Collections.singletonList(message), fp, null);
// Mark that this message is now fully synched
if (account.isMarkMessageAsReadOnView()) {
message.setFlag(Flag.SEEN, true);
}
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// now that we have the full message, refresh the headers
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
return true;
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFailed(account, folder, uid, e);
}
notifyUserIfCertificateProblem(context, e, account, true);
addErrorMessage(account, null, e);
return false;
} finally {
closeFolder(remoteFolder);
closeFolder(localFolder);
}
}
public void loadMessageForView(final Account account, final String folder, final String uid,
final MessagingListener listener) {
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewStarted(account, folder, uid);
}
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.open(Folder.OPEN_MODE_RW);
LocalMessage message = localFolder.getMessage(uid);
if (message == null
|| message.getId() == 0) {
throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid);
}
// IMAP search results will usually need to be downloaded before viewing.
// TODO: limit by account.getMaximumAutoDownloadMessageSize().
if (!message.isSet(Flag.X_DOWNLOADED_FULL) &&
!message.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
if (loadMessageForViewRemoteSynchronous(account, folder, uid, listener,
false, true)) {
markMessageAsReadOnView(account, message);
}
return;
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(Collections.singletonList(message), fp, null);
localFolder.close();
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
markMessageAsReadOnView(account, message);
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
}
});
}
public LocalMessage loadMessage(Account account, String folderName, String uid) throws MessagingException {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folderName);
localFolder.open(Folder.OPEN_MODE_RW);
LocalMessage message = localFolder.getMessage(uid);
if (message == null || message.getId() == 0) {
throw new IllegalArgumentException("Message not found: folder=" + folderName + ", uid=" + uid);
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(Collections.singletonList(message), fp, null);
localFolder.close();
markMessageAsReadOnView(account, message);
return message;
}
private void markMessageAsReadOnView(Account account, LocalMessage message)
throws MessagingException {
if (account.isMarkMessageAsReadOnView() && !message.isSet(Flag.SEEN)) {
List<Long> messageIds = Collections.singletonList(message.getId());
setFlag(account, messageIds, Flag.SEEN, true);
message.setFlagInternal(Flag.SEEN, true);
}
}
public void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener) {
put("loadAttachment", listener, new Runnable() {
@Override
public void run() {
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
String folderName = message.getFolder().getName();
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folderName);
remoteFolder.open(Folder.OPEN_MODE_RW);
Message remoteMessage = remoteFolder.getMessage(message.getUid());
remoteFolder.fetchPart(remoteMessage, part, null);
localFolder.addPartToMessage(message, part);
for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentFinished(account, message, part);
}
} catch (MessagingException me) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Exception loading attachment", me);
for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentFailed(account, message, part, me.getMessage());
}
notifyUserIfCertificateProblem(context, me, account, true);
addErrorMessage(account, null, me);
} finally {
closeFolder(localFolder);
closeFolder(remoteFolder);
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener) {
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
localFolder.appendMessages(Collections.singletonList(message));
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close();
sendPendingMessages(account, listener);
} catch (Exception e) {
/*
for (MessagingListener l : getListeners())
{
// TODO general failed
}
*/
addErrorMessage(account, null, e);
}
}
public void sendPendingMessages(MessagingListener listener) {
final Preferences prefs = Preferences.getPreferences(context);
for (Account account : prefs.getAvailableAccounts()) {
sendPendingMessages(account, listener);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener) {
putBackground("sendPendingMessages", listener, new Runnable() {
@Override
public void run() {
if (!account.isAvailable(context)) {
throw new UnavailableAccountException();
}
if (messagesPendingSend(account)) {
notifyWhileSending(account);
try {
sendPendingMessagesSynchronous(account);
} finally {
notifyWhileSendingDone(account);
}
}
}
});
}
private void cancelNotification(int id) {
NotificationManager notifMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(id);
}
private void notifyWhileSendingDone(Account account) {
if (account.isShowOngoing()) {
cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
/**
* Display an ongoing notification while a message is being sent.
*
* @param account
* The account the message is sent from. Never {@code null}.
*/
private void notifyWhileSending(Account account) {
if (!account.isShowOngoing()) {
return;
}
NotificationManager notifMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_notify_check_mail);
builder.setWhen(System.currentTimeMillis());
builder.setOngoing(true);
String accountDescription = account.getDescription();
String accountName = (TextUtils.isEmpty(accountDescription)) ?
account.getEmail() : accountDescription;
builder.setTicker(context.getString(R.string.notification_bg_send_ticker,
accountName));
builder.setContentTitle(context.getString(R.string.notification_bg_send_title));
builder.setContentText(account.getDescription());
TaskStackBuilder stack = buildMessageListBackStack(context, account,
account.getInboxFolderName());
builder.setContentIntent(stack.getPendingIntent(0, 0));
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
if (K9.NOTIFICATION_LED_WHILE_SYNCING) {
configureNotification(builder, null, null,
account.getNotificationSetting().getLedColor(),
K9.NOTIFICATION_LED_BLINK_FAST, true);
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(),
builder.build());
}
private void notifySendTempFailed(Account account, Exception lastFailure) {
notifySendFailed(account, lastFailure, account.getOutboxFolderName());
}
private void notifySendPermFailed(Account account, Exception lastFailure) {
notifySendFailed(account, lastFailure, account.getDraftsFolderName());
}
/**
* Display a notification when sending a message has failed.
*
* @param account
* The account that was used to sent the message.
* @param lastFailure
* The {@link Exception} instance that indicated sending the message has failed.
* @param openFolder
* The name of the folder to open when the notification is clicked.
*/
private void notifySendFailed(Account account, Exception lastFailure, String openFolder) {
NotificationManager notifMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(platformSupportsLockScreenNotifications()
? R.drawable.ic_notify_new_mail_vector
: R.drawable.ic_notify_new_mail);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(true);
builder.setTicker(context.getString(R.string.send_failure_subject));
builder.setContentTitle(context.getString(R.string.send_failure_subject));
builder.setContentText(getRootCauseMessage(lastFailure));
TaskStackBuilder stack = buildFolderListBackStack(context, account);
builder.setContentIntent(stack.getPendingIntent(0, 0));
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
configureNotification(builder, null, null, K9.NOTIFICATION_LED_FAILURE_COLOR,
K9.NOTIFICATION_LED_BLINK_FAST, true);
notifMgr.notify(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber(),
builder.build());
}
/**
* Display an ongoing notification while checking for new messages on the server.
*
* @param account
* The account that is checked for new messages. Never {@code null}.
* @param folder
* The folder that is being checked for new messages. Never {@code null}.
*/
private void notifyFetchingMail(final Account account, final Folder folder) {
if (!account.isShowOngoing()) {
return;
}
final NotificationManager notifMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_notify_check_mail);
builder.setWhen(System.currentTimeMillis());
builder.setOngoing(true);
builder.setTicker(context.getString(
R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()));
builder.setContentTitle(context.getString(R.string.notification_bg_sync_title));
builder.setContentText(account.getDescription() +
context.getString(R.string.notification_bg_title_separator) +
folder.getName());
TaskStackBuilder stack = buildMessageListBackStack(context, account,
account.getInboxFolderName());
builder.setContentIntent(stack.getPendingIntent(0, 0));
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
if (K9.NOTIFICATION_LED_WHILE_SYNCING) {
configureNotification(builder, null, null,
account.getNotificationSetting().getLedColor(),
K9.NOTIFICATION_LED_BLINK_FAST, true);
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(),
builder.build());
}
private void notifyFetchingMailCancel(final Account account) {
if (account.isShowOngoing()) {
cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
public boolean messagesPendingSend(final Account account) {
Folder localFolder = null;
try {
localFolder = account.getLocalStore().getFolder(
account.getOutboxFolderName());
if (!localFolder.exists()) {
return false;
}
localFolder.open(Folder.OPEN_MODE_RW);
if (localFolder.getMessageCount() > 0) {
return true;
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e);
} finally {
closeFolder(localFolder);
}
return false;
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
*/
public void sendPendingMessagesSynchronous(final Account account) {
Folder localFolder = null;
Exception lastFailure = null;
try {
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists()) {
return;
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesStarted(account);
}
localFolder.open(Folder.OPEN_MODE_RW);
List<? extends Message> localMessages = localFolder.getMessages(null);
int progress = 0;
int todo = localMessages.size();
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(K9.app, account);
for (Message message : localMessages) {
if (message.isSet(Flag.DELETED)) {
message.destroy();
continue;
}
try {
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null) {
count = oldCount;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) {
Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " can't be delivered after " + K9.MAX_SEND_ATTEMPTS + " attempts. Giving up until the user restarts the device");
notifySendTempFailed(account, new MessagingException(message.getSubject()));
continue;
}
localFolder.fetch(Collections.singletonList(message), fp, null);
try {
if (message.getHeader(K9.IDENTITY_HEADER) != null) {
Log.v(K9.LOG_TAG, "The user has set the Outbox and Drafts folder to the same thing. " +
"This message appears to be a draft, so K-9 will not send it");
continue;
}
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
progress++;
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
if (!account.hasSentFolder()) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Account does not have a sent mail folder; deleting sent message");
message.setFlag(Flag.DELETED, true);
} else {
LocalFolder localSentFolder = (LocalFolder) localStore.getFolder(account.getSentFolderName());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(Collections.singletonList(message), localSentFolder);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[] { localSentFolder.getName(), message.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
} catch (Exception e) {
// 5.x.x errors from the SMTP server are "PERMFAIL"
// move the message over to drafts rather than leaving it in the outbox
// This is a complete hack, but is worlds better than the previous
// "don't even bother" functionality
if (getRootCauseMessage(e).startsWith("5")) {
localFolder.moveMessages(Collections.singletonList(message), (LocalFolder) localStore.getFolder(account.getDraftsFolderName()));
}
notifyUserIfCertificateProblem(context, e, account, false);
addErrorMessage(account, "Failed to send message", e);
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(K9.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e));
}
lastFailure = e;
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e));
}
addErrorMessage(account, "Failed to fetch message for sending", e);
lastFailure = e;
}
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesCompleted(account);
}
if (lastFailure != null) {
if (getRootCauseMessage(lastFailure).startsWith("5")) {
notifySendPermFailed(account, lastFailure);
} else {
notifySendTempFailed(account, lastFailure);
}
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to send pending messages because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, null, e);
} finally {
if (lastFailure == null) {
cancelNotification(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber());
}
closeFolder(localFolder);
}
}
public void getAccountStats(final Context context, final Account account,
final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
AccountStats stats = account.getStats(context);
listener.accountStatusChanged(account, stats);
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Count not get unread count for account " +
account.getDescription(), me);
}
}
});
}
public void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
getSearchAccountStatsSynchronous(searchAccount, listener);
}
});
}
public AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener) {
Preferences preferences = Preferences.getPreferences(context);
LocalSearch search = searchAccount.getRelatedSearch();
// Collect accounts that belong to the search
String[] accountUuids = search.getAccountUuids();
List<Account> accounts;
if (search.searchAllAccounts()) {
accounts = preferences.getAccounts();
} else {
accounts = new ArrayList<Account>(accountUuids.length);
for (int i = 0, len = accountUuids.length; i < len; i++) {
String accountUuid = accountUuids[i];
accounts.set(i, preferences.getAccount(accountUuid));
}
}
ContentResolver cr = context.getContentResolver();
int unreadMessageCount = 0;
int flaggedMessageCount = 0;
String[] projection = {
StatsColumns.UNREAD_COUNT,
StatsColumns.FLAGGED_COUNT
};
for (Account account : accounts) {
StringBuilder query = new StringBuilder();
List<String> queryArgs = new ArrayList<String>();
ConditionsTreeNode conditions = search.getConditions();
SqlQueryBuilder.buildWhereClause(account, conditions, query, queryArgs);
String selection = query.toString();
String[] selectionArgs = queryArgs.toArray(EMPTY_STRING_ARRAY);
Uri uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI,
"account/" + account.getUuid() + "/stats");
// Query content provider to get the account stats
Cursor cursor = cr.query(uri, projection, selection, selectionArgs, null);
try {
if (cursor.moveToFirst()) {
unreadMessageCount += cursor.getInt(0);
flaggedMessageCount += cursor.getInt(1);
}
} finally {
cursor.close();
}
}
// Create AccountStats instance...
AccountStats stats = new AccountStats();
stats.unreadMessageCount = unreadMessageCount;
stats.flaggedMessageCount = flaggedMessageCount;
// ...and notify the listener
if (listener != null) {
listener.accountStatusChanged(searchAccount, stats);
}
return stats;
}
public void getFolderUnreadMessageCount(final Account account, final String folderName,
final MessagingListener l) {
Runnable unreadRunnable = new Runnable() {
@Override
public void run() {
int unreadMessageCount = 0;
try {
Folder localFolder = account.getLocalStore().getFolder(folderName);
unreadMessageCount = localFolder.getUnreadMessageCount();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me);
}
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
};
put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable);
}
public boolean isMoveCapable(Message message) {
return !message.getUid().startsWith(K9.LOCAL_UID_PREFIX);
}
public boolean isCopyCapable(Message message) {
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account) {
try {
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account) {
try {
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public void moveMessages(final Account account, final String srcFolder,
final List<LocalMessage> messages, final String destFolder,
final MessagingListener listener) {
suppressMessages(account, messages);
putBackground("moveMessages", null, new Runnable() {
@Override
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false,
listener);
}
});
}
public void moveMessagesInThread(final Account account, final String srcFolder,
final List<LocalMessage> messages, final String destFolder) {
suppressMessages(account, messages);
putBackground("moveMessagesInThread", null, new Runnable() {
@Override
public void run() {
try {
List<Message> messagesInThreads = collectMessagesInThreads(account, messages);
moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder,
false, null);
} catch (MessagingException e) {
addErrorMessage(account, "Exception while moving messages", e);
}
}
});
}
public void moveMessage(final Account account, final String srcFolder, final LocalMessage message,
final String destFolder, final MessagingListener listener) {
moveMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener);
}
public void copyMessages(final Account account, final String srcFolder,
final List<? extends Message> messages, final String destFolder,
final MessagingListener listener) {
putBackground("copyMessages", null, new Runnable() {
@Override
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true,
listener);
}
});
}
public void copyMessagesInThread(final Account account, final String srcFolder,
final List<? extends Message> messages, final String destFolder) {
putBackground("copyMessagesInThread", null, new Runnable() {
@Override
public void run() {
try {
List<Message> messagesInThreads = collectMessagesInThreads(account, messages);
moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder,
true, null);
} catch (MessagingException e) {
addErrorMessage(account, "Exception while copying messages", e);
}
}
});
}
public void copyMessage(final Account account, final String srcFolder, final Message message,
final String destFolder, final MessagingListener listener) {
copyMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener);
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder,
final List<? extends Message> inMessages, final String destFolder, final boolean isCopy,
MessagingListener listener) {
try {
Map<String, String> uidMap = new HashMap<String, String>();
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
if (!isCopy && (!remoteStore.isMoveCapable() || !localStore.isMoveCapable())) {
return;
}
if (isCopy && (!remoteStore.isCopyCapable() || !localStore.isCopyCapable())) {
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
boolean unreadCountAffected = false;
List<String> uids = new LinkedList<String>();
for (Message message : inMessages) {
String uid = message.getUid();
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
uids.add(uid);
}
if (!unreadCountAffected && !message.isSet(Flag.SEEN)) {
unreadCountAffected = true;
}
}
List<? extends Message> messages = localSrcFolder.getMessages(uids.toArray(EMPTY_STRING_ARRAY), null);
if (messages.size() > 0) {
Map<String, Message> origUidMap = new HashMap<String, Message>();
for (Message message : messages) {
origUidMap.put(message.getUid(), message);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", " + messages.size() + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(messages, fp, null);
uidMap = localSrcFolder.copyMessages(messages, localDestFolder);
if (unreadCountAffected) {
// If this copy operation changes the unread count in the destination
// folder, notify the listeners.
int unreadMessageCount = localDestFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, destFolder, unreadMessageCount);
}
}
} else {
uidMap = localSrcFolder.moveMessages(messages, localDestFolder);
for (Map.Entry<String, Message> entry : origUidMap.entrySet()) {
String origUid = entry.getKey();
Message message = entry.getValue();
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, srcFolder, origUid, message.getUid());
}
}
unsuppressMessages(account, messages);
if (unreadCountAffected) {
// If this move operation changes the unread count, notify the listeners
// that the unread count changed in both the source and destination folder.
int unreadMessageCountSrc = localSrcFolder.getUnreadMessageCount();
int unreadMessageCountDest = localDestFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, srcFolder, unreadMessageCountSrc);
l.folderStatusChanged(account, destFolder, unreadMessageCountDest);
}
}
}
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(EMPTY_STRING_ARRAY), uidMap);
}
processPendingCommands(account);
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to move/copy message because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException("Error moving message", me);
}
}
public void expunge(final Account account, final String folder, final MessagingListener listener) {
putBackground("expunge", null, new Runnable() {
@Override
public void run() {
queueExpunge(account, folder);
}
});
}
public void deleteDraft(final Account account, long id) {
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
String uid = localFolder.getMessageUidById(id);
if (uid != null) {
LocalMessage message = localFolder.getMessage(uid);
if (message != null) {
deleteMessages(Collections.singletonList(message), null);
}
}
} catch (MessagingException me) {
addErrorMessage(account, null, me);
} finally {
closeFolder(localFolder);
}
}
public void deleteThreads(final List<LocalMessage> messages) {
actOnMessages(messages, new MessageActor() {
@Override
public void act(final Account account, final Folder folder,
final List<Message> accountMessages) {
suppressMessages(account, messages);
putBackground("deleteThreads", null, new Runnable() {
@Override
public void run() {
deleteThreadsSynchronous(account, folder.getName(), accountMessages);
}
});
}
});
}
public void deleteThreadsSynchronous(Account account, String folderName,
List<Message> messages) {
try {
List<Message> messagesToDelete = collectMessagesInThreads(account, messages);
deleteMessagesSynchronous(account, folderName,
messagesToDelete, null);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Something went wrong while deleting threads", e);
}
}
public List<Message> collectMessagesInThreads(Account account, List<? extends Message> messages)
throws MessagingException {
LocalStore localStore = account.getLocalStore();
List<Message> messagesInThreads = new ArrayList<Message>();
for (Message message : messages) {
LocalMessage localMessage = (LocalMessage) message;
long rootId = localMessage.getRootId();
long threadId = (rootId == -1) ? localMessage.getThreadId() : rootId;
List<? extends Message> messagesInThread = localStore.getMessagesInThread(threadId);
messagesInThreads.addAll(messagesInThread);
}
return messagesInThreads;
}
public void deleteMessages(final List<LocalMessage> messages, final MessagingListener listener) {
actOnMessages(messages, new MessageActor() {
@Override
public void act(final Account account, final Folder folder,
final List<Message> accountMessages) {
suppressMessages(account, messages);
putBackground("deleteMessages", null, new Runnable() {
@Override
public void run() {
deleteMessagesSynchronous(account, folder.getName(),
accountMessages, listener);
}
});
}
});
}
private void deleteMessagesSynchronous(final Account account, final String folder, final List<? extends Message> messages,
MessagingListener listener) {
Folder localFolder = null;
Folder localTrashFolder = null;
String[] uids = getUidsFromMessages(messages);
try {
//We need to make these callbacks before moving the messages to the trash
//as messages get a new UID after being moved
for (Message message : messages) {
for (MessagingListener l : getListeners(listener)) {
l.messageDeleted(account, folder, message);
}
}
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
Map<String, String> uidMap = null;
if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying");
localFolder.setFlags(messages, Collections.singleton(Flag.DELETED), true);
} else {
localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (!localTrashFolder.exists()) {
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving");
uidMap = localFolder.moveMessages(messages, localTrashFolder);
}
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount());
if (localTrashFolder != null) {
l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount());
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
if (folder.equals(account.getOutboxFolderName())) {
for (Message message : messages) {
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[] {
account.getTrashFolderName(),
message.getUid()
};
queuePendingCommand(account, command);
}
processPendingCommands(account);
} else if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) {
if (folder.equals(account.getTrashFolderName())) {
queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids);
} else {
queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids, uidMap);
}
processPendingCommands(account);
} else if (account.getDeletePolicy() == DeletePolicy.MARK_AS_READ) {
queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids);
processPendingCommands(account);
} else {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
unsuppressMessages(account, messages);
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to delete message because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException("Error deleting message from local store.", me);
} finally {
closeFolder(localFolder);
closeFolder(localTrashFolder);
}
}
private String[] getUidsFromMessages(List <? extends Message> messages) {
String[] uids = new String[messages.size()];
for (int i = 0; i < messages.size(); i++) {
uids[i] = messages.get(i).getUid();
}
return uids;
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException {
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
try {
if (remoteFolder.exists()) {
remoteFolder.open(Folder.OPEN_MODE_RW);
remoteFolder.setFlags(Collections.singleton(Flag.DELETED), true);
if (Expunge.EXPUNGE_IMMEDIATELY == account.getExpungePolicy()) {
remoteFolder.expunge();
}
// When we empty trash, we need to actually synchronize the folder
// or local deletes will never get cleaned up
synchronizeFolder(account, remoteFolder, true, 0, null);
compact(account, null);
}
} finally {
closeFolder(remoteFolder);
}
}
public void emptyTrash(final Account account, MessagingListener listener) {
putBackground("emptyTrash", listener, new Runnable() {
@Override
public void run() {
LocalFolder localFolder = null;
try {
Store localStore = account.getLocalStore();
localFolder = (LocalFolder) localStore.getFolder(account.getTrashFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
boolean isTrashLocalOnly = isTrashLocalOnly(account);
if (isTrashLocalOnly) {
localFolder.clearAllMessages();
} else {
localFolder.setFlags(Collections.singleton(Flag.DELETED), true);
}
for (MessagingListener l : getListeners()) {
l.emptyTrashCompleted(account);
}
if (!isTrashLocalOnly) {
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(EMPTY_STRING_ARRAY);
queuePendingCommand(account, command);
processPendingCommands(account);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to empty trash because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, null, e);
} finally {
closeFolder(localFolder);
}
}
});
}
/**
* Find out whether the account type only supports a local Trash folder.
*
* <p>Note: Currently this is only the case for POP3 accounts.</p>
*
* @param account
* The account to check.
*
* @return {@code true} if the account only has a local Trash folder that is not synchronized
* with a folder on the server. {@code false} otherwise.
*
* @throws MessagingException
* In case of an error.
*/
private boolean isTrashLocalOnly(Account account) throws MessagingException {
// TODO: Get rid of the tight coupling once we properly support local folders
return (account.getRemoteStore() instanceof Pop3Store);
}
public void sendAlternate(final Context context, Account account, Message message) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener() {
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
try {
Intent msg = new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
quotedText = MessageExtractor.getTextFromPart(part);
}
if (quotedText != null) {
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, message.getSubject());
Address[] from = message.getFrom();
String[] senders = new String[from.length];
for (int i = 0; i < from.length; i++) {
senders[i] = from[i].toString();
}
msg.putExtra(Intents.Share.EXTRA_FROM, senders);
Address[] to = message.getRecipients(RecipientType.TO);
String[] recipientsTo = new String[to.length];
for (int i = 0; i < to.length; i++) {
recipientsTo[i] = to[i].toString();
}
msg.putExtra(Intent.EXTRA_EMAIL, recipientsTo);
Address[] cc = message.getRecipients(RecipientType.CC);
String[] recipientsCc = new String[cc.length];
for (int i = 0; i < cc.length; i++) {
recipientsCc[i] = cc[i].toString();
}
msg.putExtra(Intent.EXTRA_CC, recipientsCc);
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener) {
TracingWakeLock twakeLock = null;
if (useManualWakeLock) {
TracingPowerManager pm = TracingPowerManager.getPowerManager(context);
twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail");
twakeLock.setReferenceCounted(false);
twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT);
}
final TracingWakeLock wakeLock = twakeLock;
for (MessagingListener l : getListeners()) {
l.checkMailStarted(context, account);
}
putBackground("checkMail", listener, new Runnable() {
@Override
public void run() {
try {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Collection<Account> accounts;
if (account != null) {
accounts = new ArrayList<Account>(1);
accounts.add(account);
} else {
accounts = prefs.getAvailableAccounts();
}
for (final Account account : accounts) {
checkMailForAccount(context, account, ignoreLastCheckedTime, prefs, listener);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, null, e);
}
putBackground("finalize sync", null, new Runnable() {
@Override
public void run() {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Finished mail sync");
if (wakeLock != null) {
wakeLock.release();
}
for (MessagingListener l : getListeners()) {
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
private void checkMailForAccount(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final Preferences prefs,
final MessagingListener listener) {
if (!account.isAvailable(context)) {
if (K9.DEBUG) {
Log.i(K9.LOG_TAG, "Skipping synchronizing unavailable account " + account.getDescription());
}
return;
}
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (!ignoreLastCheckedTime && accountInterval <= 0) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
return;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription());
account.setRingNotified(false);
sendPendingMessages(account, listener);
try {
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false)) {
folder.open(Folder.OPEN_MODE_RW);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fSyncClass = folder.getSyncClass();
if (modeMismatch(aDisplayMode, fDisplayClass)) {
// Never sync a folder that isn't displayed
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode);
*/
continue;
}
if (modeMismatch(aSyncMode, fSyncClass)) {
// Do not sync folders in the wrong class
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode);
*/
continue;
}
synchronizeFolder(account, folder, ignoreLastCheckedTime, accountInterval, listener);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, null, e);
} finally {
putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() {
@Override
public void run() {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription());
account.setRingNotified(false);
try {
AccountStats stats = account.getStats(context);
if (stats == null || stats.unreadMessageCount == 0) {
notifyAccountCancel(context, account);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
}
}
);
}
}
private void synchronizeFolder(
final Account account,
final Folder folder,
final boolean ignoreLastCheckedTime,
final long accountInterval,
final MessagingListener listener) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
if (!ignoreLastCheckedTime && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
return;
}
putBackground("sync" + folder.getName(), null, new Runnable() {
@Override
public void run() {
LocalFolder tLocalFolder = null;
try {
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OPEN_MODE_RW);
if (!ignoreLastCheckedTime && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
return;
}
notifyFetchingMail(account, folder);
try {
synchronizeMailboxSynchronous(account, folder.getName(), listener, null);
} finally {
notifyFetchingMailCancel(account);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, null, e);
} finally {
closeFolder(tLocalFolder);
}
}
}
);
}
public void compact(final Account account, final MessagingListener ml) {
putBackground("compact:" + account.getDescription(), ml, new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
for (MessagingListener l : getListeners(ml)) {
l.accountSizeChanged(account, oldSize, newSize);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to compact account because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml) {
putBackground("clear:" + account.getDescription(), ml, new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
for (MessagingListener l : getListeners(ml)) {
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to clear account because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e);
}
}
});
}
public void recreate(final Account account, final MessagingListener ml) {
putBackground("recreate:" + account.getDescription(), ml, new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.recreate();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
for (MessagingListener l : getListeners(ml)) {
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to recreate an account because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e);
}
}
});
}
private boolean shouldNotifyForMessage(Account account, LocalFolder localFolder, Message message) {
// If we don't even have an account name, don't show the notification.
// (This happens during initial account setup)
if (account.getName() == null) {
return false;
}
// Do not notify if the user does not have notifications enabled or if the message has
// been read.
if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN)) {
return false;
}
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aNotifyMode = account.getFolderNotifyNewMailMode();
Folder.FolderClass fDisplayClass = localFolder.getDisplayClass();
Folder.FolderClass fNotifyClass = localFolder.getNotifyClass();
if (modeMismatch(aDisplayMode, fDisplayClass)) {
// Never notify a folder that isn't displayed
return false;
}
if (modeMismatch(aNotifyMode, fNotifyClass)) {
// Do not notify folders in the wrong class
return false;
}
// If the account is a POP3 account and the message is older than the oldest message we've
// previously seen, then don't notify about it.
if (account.getStoreUri().startsWith("pop3") &&
message.olderThan(new Date(account.getLatestOldMessageSeenTime()))) {
return false;
}
// No notification for new messages in Trash, Drafts, Spam or Sent folder.
// But do notify if it's the INBOX (see issue 1817).
Folder folder = message.getFolder();
if (folder != null) {
String folderName = folder.getName();
if (!account.getInboxFolderName().equals(folderName) &&
(account.getTrashFolderName().equals(folderName)
|| account.getDraftsFolderName().equals(folderName)
|| account.getSpamFolderName().equals(folderName)
|| account.getSentFolderName().equals(folderName))) {
return false;
}
}
if (message.getUid() != null && localFolder.getLastUid() != null) {
try {
Integer messageUid = Integer.parseInt(message.getUid());
if (messageUid <= localFolder.getLastUid()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Message uid is " + messageUid + ", max message uid is " +
localFolder.getLastUid() + ". Skipping notification.");
return false;
}
} catch (NumberFormatException e) {
// Nothing to be done here.
}
}
// Don't notify if the sender address matches one of our identities and the user chose not
// to be notified for such messages.
if (account.isAnIdentity(message.getFrom()) && !account.isNotifySelfNewMail()) {
return false;
}
return true;
}
/**
* Get the pending notification data for an account.
* See {@link NotificationData}.
*
* @param account The account to retrieve the pending data for
* @param previousUnreadMessageCount The number of currently pending messages, which will be used
* if there's no pending data yet. If passed as null, a new instance
* won't be created if currently not existent.
* @return A pending data instance, or null if one doesn't exist and
* previousUnreadMessageCount was passed as null.
*/
private NotificationData getNotificationData(Account account, Integer previousUnreadMessageCount) {
NotificationData data;
synchronized (notificationData) {
data = notificationData.get(account.getAccountNumber());
if (data == null && previousUnreadMessageCount != null) {
data = new NotificationData(previousUnreadMessageCount);
notificationData.put(account.getAccountNumber(), data);
}
}
return data;
}
private CharSequence getMessageSender(Context context, Account account, Message message) {
try {
boolean isSelf = false;
final Contacts contacts = K9.showContactName() ? Contacts.getInstance(context) : null;
final Address[] fromAddrs = message.getFrom();
if (fromAddrs != null) {
isSelf = account.isAnIdentity(fromAddrs);
if (!isSelf && fromAddrs.length > 0) {
return MessageHelper.toFriendly(fromAddrs[0], contacts).toString();
}
}
if (isSelf) {
// show To: if the message was sent from me
Address[] rcpts = message.getRecipients(Message.RecipientType.TO);
if (rcpts != null && rcpts.length > 0) {
return context.getString(R.string.message_to_fmt,
MessageHelper.toFriendly(rcpts[0], contacts).toString());
}
return context.getString(R.string.general_no_sender);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to get sender information for notification.", e);
}
return null;
}
private CharSequence getMessageSubject(Context context, Message message) {
String subject = message.getSubject();
if (!TextUtils.isEmpty(subject)) {
return subject;
}
return context.getString(R.string.general_no_subject);
}
private static TextAppearanceSpan sEmphasizedSpan;
private TextAppearanceSpan getEmphasizedSpan(Context context) {
if (sEmphasizedSpan == null) {
sEmphasizedSpan = new TextAppearanceSpan(context,
R.style.TextAppearance_StatusBar_EventContent_Emphasized);
}
return sEmphasizedSpan;
}
private CharSequence getMessagePreview(Context context, Message message) {
CharSequence subject = getMessageSubject(context, message);
String snippet = message.getPreview();
if (TextUtils.isEmpty(subject)) {
return snippet;
} else if (TextUtils.isEmpty(snippet)) {
return subject;
}
SpannableStringBuilder preview = new SpannableStringBuilder();
preview.append(subject);
preview.append('\n');
preview.append(snippet);
preview.setSpan(getEmphasizedSpan(context), 0, subject.length(), 0);
return preview;
}
private CharSequence buildMessageSummary(Context context, CharSequence sender, CharSequence subject) {
if (sender == null) {
return subject;
}
SpannableStringBuilder summary = new SpannableStringBuilder();
summary.append(sender);
summary.append(" ");
summary.append(subject);
summary.setSpan(getEmphasizedSpan(context), 0, sender.length(), 0);
return summary;
}
public static final boolean platformSupportsExtendedNotifications() {
// supported in Jellybean
// TODO: use constant once target SDK is set to >= 16
return Build.VERSION.SDK_INT >= 16;
}
public static boolean platformSupportsLockScreenNotifications() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
private LocalMessage findNewestMessageForNotificationLocked(Context context, NotificationData data) {
if (!data.messages.isEmpty()) {
return data.messages.getFirst();
}
if (!data.droppedMessages.isEmpty()) {
return data.droppedMessages.getFirst().restoreToLocalMessage(context);
}
return null;
}
/**
* Creates a notification of a newly received message.
*/
private void notifyAccount(Context context, Account account,
LocalMessage message, int previousUnreadMessageCount) {
final NotificationData data = getNotificationData(account, previousUnreadMessageCount);
synchronized (data) {
notifyAccountWithDataLocked(context, account, message, data);
}
}
// Maximum number of senders to display in a lock screen notification.
private static final int NUM_SENDERS_IN_LOCK_SCREEN_NOTIFICATION = 5;
private void notifyAccountWithDataLocked(Context context, Account account,
LocalMessage message, NotificationData data) {
boolean updateSilently = false;
if (message == null) {
/* this can happen if a message we previously notified for is read or deleted remotely */
message = findNewestMessageForNotificationLocked(context, data);
updateSilently = true;
if (message == null) {
// seemingly both the message list as well as the overflow list is empty;
// it probably is a good idea to cancel the notification in that case
notifyAccountCancel(context, account);
return;
}
} else {
data.addMessage(message);
}
final KeyguardManager keyguardService = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
final CharSequence sender = getMessageSender(context, account, message);
final CharSequence subject = getMessageSubject(context, message);
CharSequence summary = buildMessageSummary(context, sender, subject);
boolean privacyModeEnabled =
(K9.getNotificationHideSubject() == NotificationHideSubject.ALWAYS) ||
(K9.getNotificationHideSubject() == NotificationHideSubject.WHEN_LOCKED &&
keyguardService.inKeyguardRestrictedInputMode());
if (privacyModeEnabled || summary.length() == 0) {
summary = context.getString(R.string.notification_new_title);
}
NotificationManager notifMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_notify_new_mail);
builder.setWhen(System.currentTimeMillis());
if (!updateSilently) {
builder.setTicker(summary);
}
final int newMessages = data.getNewMessageCount();
final int unreadCount = data.unreadBeforeNotification + newMessages;
builder.setNumber(unreadCount);
String accountDescr = (account.getDescription() != null) ?
account.getDescription() : account.getEmail();
final ArrayList<MessageReference> allRefs = new ArrayList<MessageReference>();
data.supplyAllMessageRefs(allRefs);
if (platformSupportsExtendedNotifications() && !privacyModeEnabled) {
if (newMessages > 1) {
// multiple messages pending, show inbox style
NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(builder);
for (Message m : data.messages) {
style.addLine(buildMessageSummary(context,
getMessageSender(context, account, m),
getMessageSubject(context, m)));
}
if (!data.droppedMessages.isEmpty()) {
style.setSummaryText(context.getString(R.string.notification_additional_messages,
data.droppedMessages.size(), accountDescr));
}
final String title = context.getResources().getQuantityString(
R.plurals.notification_new_messages_title, newMessages, newMessages);
style.setBigContentTitle(title);
builder.setContentTitle(title);
builder.setSubText(accountDescr);
builder.setStyle(style);
} else {
// single message pending, show big text
NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle(builder);
CharSequence preview = getMessagePreview(context, message);
if (preview != null) {
style.bigText(preview);
}
builder.setContentText(subject);
builder.setSubText(accountDescr);
builder.setContentTitle(sender);
builder.setStyle(style);
builder.addAction(
platformSupportsLockScreenNotifications()
? R.drawable.ic_action_single_message_options_dark_vector
: R.drawable.ic_action_single_message_options_dark,
context.getString(R.string.notification_action_reply),
NotificationActionService.getReplyIntent(context, account, message.makeMessageReference()));
}
// Mark Read on phone
builder.addAction(
platformSupportsLockScreenNotifications()
? R.drawable.ic_action_mark_as_read_dark_vector
: R.drawable.ic_action_mark_as_read_dark,
context.getString(R.string.notification_action_mark_as_read),
NotificationActionService.getReadAllMessagesIntent(context, account, allRefs));
NotificationQuickDelete deleteOption = K9.getNotificationQuickDeleteBehaviour();
boolean showDeleteAction = deleteOption == NotificationQuickDelete.ALWAYS ||
(deleteOption == NotificationQuickDelete.FOR_SINGLE_MSG && newMessages == 1);
NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
if (showDeleteAction) {
// we need to pass the action directly to the activity, otherwise the
// status bar won't be pulled up and we won't see the confirmation (if used)
// Delete on phone
builder.addAction(
platformSupportsLockScreenNotifications()
? R.drawable.ic_action_delete_dark_vector
: R.drawable.ic_action_delete_dark,
context.getString(R.string.notification_action_delete),
NotificationDeleteConfirmation.getIntent(context, account, allRefs));
// Delete on wear only if no confirmation is required
if (!K9.confirmDeleteFromNotification()) {
NotificationCompat.Action wearActionDelete =
new NotificationCompat.Action.Builder(
R.drawable.ic_action_delete_dark,
context.getString(R.string.notification_action_delete),
NotificationDeleteConfirmation.getIntent(context, account, allRefs))
.build();
builder.extend(wearableExtender.addAction(wearActionDelete));
}
}
if (NotificationActionService.isArchiveAllMessagesWearAvaliable(context, account, data.messages)) {
// Archive on wear
NotificationCompat.Action wearActionArchive =
new NotificationCompat.Action.Builder(
R.drawable.ic_action_delete_dark,
context.getString(R.string.notification_action_archive),
NotificationActionService.getArchiveAllMessagesIntent(context, account, allRefs))
.build();
builder.extend(wearableExtender.addAction(wearActionArchive));
}
if (NotificationActionService.isSpamAllMessagesWearAvaliable(context, account, data.messages)) {
// Archive on wear
NotificationCompat.Action wearActionSpam =
new NotificationCompat.Action.Builder(
R.drawable.ic_action_delete_dark,
context.getString(R.string.notification_action_spam),
NotificationActionService.getSpamAllMessagesIntent(context, account, allRefs))
.build();
builder.extend(wearableExtender.addAction(wearActionSpam));
}
} else {
String accountNotice = context.getString(R.string.notification_new_one_account_fmt,
unreadCount, accountDescr);
builder.setContentTitle(accountNotice);
builder.setContentText(summary);
}
for (Message m : data.messages) {
if (m.isSet(Flag.FLAGGED)) {
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
break;
}
}
TaskStackBuilder stack;
boolean treatAsSingleMessageNotification;
if (platformSupportsExtendedNotifications()) {
// in the new-style notifications, we focus on the new messages, not the unread ones
treatAsSingleMessageNotification = newMessages == 1;
} else {
// in the old-style notifications, we focus on unread messages, as we don't have a
// good way to express the new message count
treatAsSingleMessageNotification = unreadCount == 1;
}
if (treatAsSingleMessageNotification) {
stack = buildMessageViewBackStack(context, message.makeMessageReference());
} else if (account.goToUnreadMessageSearch()) {
stack = buildUnreadBackStack(context, account);
} else {
String initialFolder = message.getFolder().getName();
/* only go to folder if all messages are in the same folder, else go to folder list */
for (MessageReference ref : allRefs) {
if (!TextUtils.equals(initialFolder, ref.getFolderName())) {
initialFolder = null;
break;
}
}
stack = buildMessageListBackStack(context, account, initialFolder);
}
builder.setContentIntent(stack.getPendingIntent(
account.getAccountNumber(),
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT));
builder.setDeleteIntent(NotificationActionService.getAcknowledgeIntent(context, account));
// Only ring or vibrate if we have not done so already on this account and fetch
boolean ringAndVibrate = false;
if (!updateSilently && !account.isRingNotified()) {
account.setRingNotified(true);
ringAndVibrate = true;
}
NotificationSetting n = account.getNotificationSetting();
configureLockScreenNotification(builder, context, account, newMessages, unreadCount, accountDescr, sender, data.messages);
configureNotification(
builder,
(n.shouldRing()) ? n.getRingtone() : null,
(n.shouldVibrate()) ? n.getVibration() : null,
(n.isLed()) ? Integer.valueOf(n.getLedColor()) : null,
K9.NOTIFICATION_LED_BLINK_SLOW,
ringAndVibrate);
notifMgr.notify(account.getAccountNumber(), builder.build());
}
private TaskStackBuilder buildAccountsBackStack(Context context) {
TaskStackBuilder stack = TaskStackBuilder.create(context);
if (!skipAccountsInBackStack(context)) {
stack.addNextIntent(new Intent(context, Accounts.class).putExtra(Accounts.EXTRA_STARTUP, false));
}
return stack;
}
private TaskStackBuilder buildFolderListBackStack(Context context, Account account) {
TaskStackBuilder stack = buildAccountsBackStack(context);
stack.addNextIntent(FolderList.actionHandleAccountIntent(context, account, false));
return stack;
}
private TaskStackBuilder buildUnreadBackStack(Context context, final Account account) {
TaskStackBuilder stack = buildAccountsBackStack(context);
LocalSearch search = Accounts.createUnreadSearch(context, account);
stack.addNextIntent(MessageList.intentDisplaySearch(context, search, true, false, false));
return stack;
}
private TaskStackBuilder buildMessageListBackStack(Context context, Account account, String folder) {
TaskStackBuilder stack = skipFolderListInBackStack(context, account, folder)
? buildAccountsBackStack(context)
: buildFolderListBackStack(context, account);
if (folder != null) {
LocalSearch search = new LocalSearch(folder);
search.addAllowedFolder(folder);
search.addAccountUuid(account.getUuid());
stack.addNextIntent(MessageList.intentDisplaySearch(context, search, false, true, true));
}
return stack;
}
private TaskStackBuilder buildMessageViewBackStack(Context context, MessageReference message) {
Account account = Preferences.getPreferences(context).getAccount(message.getAccountUuid());
TaskStackBuilder stack = buildMessageListBackStack(context, account, message.getFolderName());
stack.addNextIntent(MessageList.actionDisplayMessageIntent(context, message));
return stack;
}
private boolean skipFolderListInBackStack(Context context, Account account, String folder) {
return folder != null && folder.equals(account.getAutoExpandFolderName());
}
private boolean skipAccountsInBackStack(Context context) {
return Preferences.getPreferences(context).getAccounts().size() == 1;
}
/**
* Configure the notification sound and LED
*
* @param builder
* {@link NotificationCompat.Builder} instance used to configure the notification.
* Never {@code null}.
* @param ringtone
* String name of ringtone. {@code null}, if no ringtone should be played.
* @param vibrationPattern
* {@code long[]} vibration pattern. {@code null}, if no vibration should be played.
* @param ledColor
* Color to flash LED. {@code null}, if no LED flash should happen.
* @param ledSpeed
* Either {@link K9#NOTIFICATION_LED_BLINK_SLOW} or
* {@link K9#NOTIFICATION_LED_BLINK_FAST}.
* @param ringAndVibrate
* {@code true}, if ringtone/vibration are allowed. {@code false}, otherwise.
*/
private void configureNotification(NotificationCompat.Builder builder, String ringtone,
long[] vibrationPattern, Integer ledColor, int ledSpeed, boolean ringAndVibrate) {
// if it's quiet time, then we shouldn't be ringing, buzzing or flashing
if (K9.isQuietTime()) {
return;
}
if (ringAndVibrate) {
if (ringtone != null && !TextUtils.isEmpty(ringtone)) {
builder.setSound(Uri.parse(ringtone));
}
if (vibrationPattern != null) {
builder.setVibrate(vibrationPattern);
}
}
if (ledColor != null) {
int ledOnMS;
int ledOffMS;
if (ledSpeed == K9.NOTIFICATION_LED_BLINK_SLOW) {
ledOnMS = K9.NOTIFICATION_LED_ON_TIME;
ledOffMS = K9.NOTIFICATION_LED_OFF_TIME;
} else {
ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
builder.setLights(ledColor, ledOnMS, ledOffMS);
}
}
/**
* Configure lock screen notifications on platforms that support it
*
* @param builder Unlocked notification
* @param context Context
* @param account Account being notified
* @param newMessages Number of new messages being notified for
* @param unreadCount Total number of unread messages in this account
* @param accountDescription Formatted account name for display
* @param formattedSender Formatted sender name for display
* @param messages List of messages if notifying for multiple messages. Null otherwise.
*/
private void configureLockScreenNotification(NotificationCompat.Builder builder,
Context context,
Account account,
int newMessages,
int unreadCount,
CharSequence accountDescription,
CharSequence formattedSender,
List<? extends Message> messages) {
if (!platformSupportsLockScreenNotifications()) {
return;
}
builder.setSmallIcon(R.drawable.ic_notify_new_mail_vector);
builder.setColor(account.getChipColor());
NotificationCompat.Builder publicNotification = new NotificationCompat.Builder(context);
publicNotification.setSmallIcon(R.drawable.ic_notify_new_mail_vector);
publicNotification.setColor(account.getChipColor());
publicNotification.setNumber(unreadCount);
final String title = context.getResources().getQuantityString(
R.plurals.notification_new_messages_title, newMessages, newMessages);
publicNotification.setContentTitle(title);
switch (K9.getLockScreenNotificationVisibility()) {
case NOTHING:
builder.setVisibility(NotificationCompat.VISIBILITY_SECRET);
break;
case APP_NAME:
// This is the Android default, but we should be explicit in case that changes in the future.
builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
break;
case SENDERS:
if (newMessages == 1) {
publicNotification.setContentText(formattedSender);
} else {
// Use a LinkedHashSet so that we preserve ordering (newest to oldest), but still remove duplicates
Set<CharSequence> senders = new LinkedHashSet<CharSequence>(NUM_SENDERS_IN_LOCK_SCREEN_NOTIFICATION);
for (Message message : messages) {
senders.add(getMessageSender(context, account, message));
if (senders.size() == NUM_SENDERS_IN_LOCK_SCREEN_NOTIFICATION) {
break;
}
}
publicNotification.setContentText(TextUtils.join(", ", senders));
}
builder.setPublicVersion(publicNotification.build());
break;
case EVERYTHING:
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
break;
case MESSAGE_COUNT:
default:
publicNotification.setContentText(accountDescription);
builder.setPublicVersion(publicNotification.build());
break;
}
}
/** Cancel a notification of new email messages */
public void notifyAccountCancel(Context context, Account account) {
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(account.getAccountNumber());
notifMgr.cancel(-1000 - account.getAccountNumber());
notificationData.remove(account.getAccountNumber());
}
public void deleteAccount(Context context, Account account) {
notifyAccountCancel(context, account);
memorizingListener.removeAccount(account);
}
/**
* Save a draft message.
* @param account Account we are saving for.
* @param message Message to save.
* @return Message representing the entry in the local store.
*/
public Message saveDraft(final Account account, final Message message, long existingDraftId) {
Message localMessage = null;
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
if (existingDraftId != INVALID_MESSAGE_ID) {
String uid = localFolder.getMessageUidById(existingDraftId);
message.setUid(uid);
}
// Save the message to the store.
localFolder.appendMessages(Collections.singletonList(message));
// Fetch the message back from the store. This is the Message that's returned to the caller.
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[] {
localFolder.getName(),
localMessage.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, null, e);
}
return localMessage;
}
public long getId(Message message) {
long id;
if (message instanceof LocalMessage) {
id = ((LocalMessage) message).getId();
} else {
Log.w(K9.LOG_TAG, "MessagingController.getId() called without a LocalMessage");
id = INVALID_MESSAGE_ID;
}
return id;
}
public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) {
if (aMode == Account.FolderMode.NONE
|| (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
|| (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
|| (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS)) {
return true;
} else {
return false;
}
}
static AtomicInteger sequencing = new AtomicInteger(0);
static class Command implements Comparable<Command> {
public Runnable runnable;
public MessagingListener listener;
public String description;
boolean isForeground;
int sequence = sequencing.getAndIncrement();
@Override
public int compareTo(Command other) {
if (other.isForeground && !isForeground) {
return 1;
} else if (!other.isForeground && isForeground) {
return -1;
} else {
return (sequence - other.sequence);
}
}
}
public MessagingListener getCheckMailListener() {
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener) {
if (this.checkMailListener != null) {
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null) {
addListener(this.checkMailListener);
}
}
public Collection<Pusher> getPushers() {
return pushers.values();
}
public boolean setupPushing(final Account account) {
try {
Pusher previousPusher = pushers.remove(account);
if (previousPusher != null) {
previousPusher.stop();
}
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode();
List<String> names = new ArrayList<String>();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false)) {
if (folder.getName().equals(account.getErrorFolderName())
|| folder.getName().equals(account.getOutboxFolderName())) {
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which should never be pushed");
*/
continue;
}
folder.open(Folder.OPEN_MODE_RW);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fPushClass = folder.getPushClass();
if (modeMismatch(aDisplayMode, fDisplayClass)) {
// Never push a folder that isn't displayed
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode);
*/
continue;
}
if (modeMismatch(aPushMode, fPushClass)) {
// Do not push folders in the wrong class
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in push mode " + fPushClass + " while account is in push mode " + aPushMode);
*/
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName());
names.add(folder.getName());
}
if (!names.isEmpty()) {
PushReceiver receiver = new MessagingControllerPushReceiver(context, account, this);
int maxPushFolders = account.getMaxPushFolders();
if (names.size() > maxPushFolders) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size()
+ ", greater than limit of " + maxPushFolders + ", truncating");
names = names.subList(0, maxPushFolders);
}
try {
Store store = account.getRemoteStore();
if (!store.isPushCapable()) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping");
return false;
}
Pusher pusher = store.getPusher(receiver);
if (pusher != null) {
Pusher oldPusher = pushers.putIfAbsent(account, pusher);
if (oldPusher == null) {
pusher.start(names);
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not get remote store", e);
return false;
}
return true;
} else {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription());
return false;
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e);
}
return false;
}
public void stopAllPushing() {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Stopping all pushers");
Iterator<Pusher> iter = pushers.values().iterator();
while (iter.hasNext()) {
Pusher pusher = iter.next();
iter.remove();
pusher.stop();
}
}
public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription()
+ ", folder " + remoteFolder.getName());
final CountDownLatch latch = new CountDownLatch(1);
putBackground("Push messageArrived of account " + account.getDescription()
+ ", folder " + remoteFolder.getName(), null, new Runnable() {
@Override
public void run() {
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(remoteFolder.getName());
localFolder.open(Folder.OPEN_MODE_RW);
account.setRingNotified(false);
int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly);
int unreadMessageCount = localFolder.getUnreadMessageCount();
localFolder.setLastPush(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount);
if (unreadMessageCount == 0) {
notifyAccountCancel(context, account);
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount);
}
} catch (Exception e) {
String rootMessage = getRootCauseMessage(e);
String errorMessage = "Push failed: " + rootMessage;
try {
// Oddly enough, using a local variable gets rid of a
// potential null pointer access warning with Eclipse.
LocalFolder folder = localFolder;
folder.setStatus(errorMessage);
} catch (Exception se) {
Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se);
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage);
}
addErrorMessage(account, null, e);
} finally {
closeFolder(localFolder);
latch.countDown();
}
}
});
try {
latch.await();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released");
}
public void systemStatusChanged() {
for (MessagingListener l : getListeners()) {
l.systemStatusChanged();
}
}
enum MemorizingState { STARTED, FINISHED, FAILED }
static class Memory {
Account account;
String folderName;
MemorizingState syncingState = null;
MemorizingState sendingState = null;
MemorizingState pushingState = null;
MemorizingState processingState = null;
String failureMessage = null;
int syncingTotalMessagesInMailbox;
int syncingNumNewMessages;
int folderCompleted = 0;
int folderTotal = 0;
String processingCommandTitle = null;
Memory(Account nAccount, String nFolderName) {
account = nAccount;
folderName = nFolderName;
}
String getKey() {
return getMemoryKey(account, folderName);
}
}
static String getMemoryKey(Account taccount, String tfolderName) {
return taccount.getDescription() + ":" + tfolderName;
}
static class MemorizingListener extends MessagingListener {
Map<String, Memory> memories = new HashMap<String, Memory>(31);
Memory getMemory(Account account, String folderName) {
Memory memory = memories.get(getMemoryKey(account, folderName));
if (memory == null) {
memory = new Memory(account, folderName);
memories.put(memory.getKey(), memory);
}
return memory;
}
synchronized void removeAccount(Account account) {
Iterator<Entry<String, Memory>> memIt = memories.entrySet().iterator();
while (memIt.hasNext()) {
Entry<String, Memory> memoryEntry = memIt.next();
String uuidForMemory = memoryEntry.getValue().account.getUuid();
if (uuidForMemory.equals(account.getUuid())) {
memIt.remove();
}
}
}
@Override
public synchronized void synchronizeMailboxStarted(Account account, String folder) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FINISHED;
memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox;
memory.syncingNumNewMessages = numNewMessages;
}
@Override
public synchronized void synchronizeMailboxFailed(Account account, String folder,
String message) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FAILED;
memory.failureMessage = message;
}
synchronized void refreshOther(MessagingListener other) {
if (other != null) {
Memory syncStarted = null;
Memory sendStarted = null;
Memory processingStarted = null;
for (Memory memory : memories.values()) {
if (memory.syncingState != null) {
switch (memory.syncingState) {
case STARTED:
syncStarted = memory;
break;
case FINISHED:
other.synchronizeMailboxFinished(memory.account, memory.folderName,
memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages);
break;
case FAILED:
other.synchronizeMailboxFailed(memory.account, memory.folderName,
memory.failureMessage);
break;
}
}
if (memory.sendingState != null) {
switch (memory.sendingState) {
case STARTED:
sendStarted = memory;
break;
case FINISHED:
other.sendPendingMessagesCompleted(memory.account);
break;
case FAILED:
other.sendPendingMessagesFailed(memory.account);
break;
}
}
if (memory.pushingState != null) {
switch (memory.pushingState) {
case STARTED:
other.setPushActive(memory.account, memory.folderName, true);
break;
case FINISHED:
other.setPushActive(memory.account, memory.folderName, false);
break;
case FAILED:
break;
}
}
if (memory.processingState != null) {
switch (memory.processingState) {
case STARTED:
processingStarted = memory;
break;
case FINISHED:
case FAILED:
other.pendingCommandsFinished(memory.account);
break;
}
}
}
Memory somethingStarted = null;
if (syncStarted != null) {
other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName);
somethingStarted = syncStarted;
}
if (sendStarted != null) {
other.sendPendingMessagesStarted(sendStarted.account);
somethingStarted = sendStarted;
}
if (processingStarted != null) {
other.pendingCommandsProcessing(processingStarted.account);
if (processingStarted.processingCommandTitle != null) {
other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle);
} else {
other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle);
}
somethingStarted = processingStarted;
}
if (somethingStarted != null && somethingStarted.folderTotal > 0) {
other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal);
}
}
}
@Override
public synchronized void setPushActive(Account account, String folderName, boolean active) {
Memory memory = getMemory(account, folderName);
memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED);
}
@Override
public synchronized void sendPendingMessagesStarted(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void sendPendingMessagesCompleted(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FINISHED;
}
@Override
public synchronized void sendPendingMessagesFailed(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FAILED;
}
@Override
public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) {
Memory memory = getMemory(account, folderName);
memory.folderCompleted = completed;
memory.folderTotal = total;
}
@Override
public synchronized void pendingCommandsProcessing(Account account) {
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void pendingCommandsFinished(Account account) {
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.FINISHED;
}
@Override
public synchronized void pendingCommandStarted(Account account, String commandTitle) {
Memory memory = getMemory(account, null);
memory.processingCommandTitle = commandTitle;
}
@Override
public synchronized void pendingCommandCompleted(Account account, String commandTitle) {
Memory memory = getMemory(account, null);
memory.processingCommandTitle = null;
}
}
private void actOnMessages(List<LocalMessage> messages, MessageActor actor) {
Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>();
for (LocalMessage message : messages) {
if ( message == null) {
continue;
}
Folder folder = message.getFolder();
Account account = message.getAccount();
Map<Folder, List<Message>> folderMap = accountMap.get(account);
if (folderMap == null) {
folderMap = new HashMap<Folder, List<Message>>();
accountMap.put(account, folderMap);
}
List<Message> messageList = folderMap.get(folder);
if (messageList == null) {
messageList = new LinkedList<Message>();
folderMap.put(folder, messageList);
}
messageList.add(message);
}
for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet()) {
Account account = entry.getKey();
//account.refresh(Preferences.getPreferences(K9.app));
Map<Folder, List<Message>> folderMap = entry.getValue();
for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet()) {
Folder folder = folderEntry.getKey();
List<Message> messageList = folderEntry.getValue();
actor.act(account, folder, messageList);
}
}
}
interface MessageActor {
public void act(final Account account, final Folder folder, final List<Message> messages);
}
}
|
package de.mrapp.android.adapter.util;
/**
* An utility class, which offers static methods to ensure, that attributes
* satisfy specific conditions. Otherwise exceptions are thrown.
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public final class Condition {
/**
* Creates a new utility class, which offers static methods to ensure, that
* attributes satisfy specific conditions.
*/
private Condition() {
}
/**
* Ensures, that a reference is not null. Otherwise a
* {@link NullPointerException} with a specific message will be thrown.
*
* @param reference
* The reference, which should be ensured to be not null, as an
* instance of the class {@link Object}
* @param exceptionMessage
* The message of the {@link NullPointerException}, which is
* thrown, if the given reference is null, as a {@link String}
*/
public static void ensureNotNull(final Object reference,
final String exceptionMessage) {
if (reference == null) {
throw new NullPointerException(exceptionMessage);
}
}
public static void ensureNotEmpty(final String string,
final String exceptionMessage) {
if (string.length() == 0) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that an {@link Integer} value is at least a specific value.
* Otherwise an {@link IndexOutOfBoundsException} with a specific message
* will be thrown.
*
* @param value
* The value, which should be checked, as an {@link Integer}
* value
* @param referenceValue
* The value, the given value must at least, as an
* {@link Integer} value
* @param exceptionMessage
* The message of the {@link IndexOutOfBoundsException}, which is
* thrown, if the given value is less than the reference value,
* as a {@link String}
*/
public static void ensureAtLeast(final int value, final int referenceValue,
final String exceptionMessage) {
if (value < referenceValue) {
throw new IndexOutOfBoundsException(exceptionMessage);
}
}
/**
* Ensures, that an {@link Integer} value is at maximum a specific value.
* Otherwise an {@link IndexOutOfBoundsException} with a specific message
* will be thrown.
*
* @param value
* The value, which should be checked, as an {@link Integer}
* value
* @param referenceValue
* The value, the given value must be at maximum, as an
* {@link Integer} value
* @param exceptionMessage
* The message of the {@link IndexOutOfBoundsException}, which is
* thrown, if the given value is greater than the reference
* value, as a {@link String}
*/
public static void ensureAtMaximum(final int value,
final int referenceValue, final String exceptionMessage) {
if (value > referenceValue) {
throw new IndexOutOfBoundsException(exceptionMessage);
}
}
}
|
package com.intuit.karate.report;
import com.intuit.karate.Results;
import com.intuit.karate.Suite;
import com.intuit.karate.core.FeatureResult;
import com.intuit.karate.core.TagResults;
import com.intuit.karate.core.TimelineResults;
/**
*
* @author pthomas3
*/
public interface SuiteReports {
default Report featureReport(Suite suite, FeatureResult featureResult) {
return Report.template("karate-feature.html")
.reportDir(suite.reportDir)
.reportFileName(featureResult.getFeature().getPackageQualifiedName() + ".html")
.variable("results", featureResult.toKarateJson())
.build();
}
default Report tagsReport(Suite suite, TagResults tagResults) {
return Report.template("karate-tags.html")
.reportDir(suite.reportDir)
.variable("results", tagResults.toKarateJson())
.build();
}
default Report timelineReport(Suite suite, TimelineResults timelineResults) {
return Report.template("karate-timeline.html")
.reportDir(suite.reportDir)
.variable("results", timelineResults.toKarateJson())
.build();
}
default Report summaryReport(Suite suite, Results results) {
return Report.template("karate-summary.html")
.reportDir(suite.reportDir)
.variable("results", results.toKarateJson())
.build();
}
public static final SuiteReports DEFAULT = new SuiteReports() {
// defaults
};
}
|
package io.druid.server;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.api.client.repackaged.com.google.common.base.Throwables;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import com.google.inject.Inject;
import com.metamx.common.guava.Accumulator;
import com.metamx.common.guava.Accumulators;
import com.metamx.common.guava.Sequence;
import com.metamx.common.guava.Sequences;
import com.metamx.common.guava.Yielder;
import com.metamx.common.guava.YieldingAccumulator;
import com.metamx.common.guava.YieldingAccumulators;
import com.metamx.emitter.EmittingLogger;
import com.metamx.emitter.service.ServiceEmitter;
import com.metamx.emitter.service.ServiceMetricEvent;
import io.druid.guice.annotations.Json;
import io.druid.guice.annotations.Smile;
import io.druid.query.DataSourceUtil;
import io.druid.query.Query;
import io.druid.query.QueryInterruptedException;
import io.druid.query.QuerySegmentWalker;
import io.druid.server.log.RequestLogger;
import org.joda.time.DateTime;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.UUID;
@Path("/druid/v2/")
public class QueryResource
{
private static final EmittingLogger log = new EmittingLogger(QueryResource.class);
private static final Joiner COMMA_JOIN = Joiner.on(",");
public static final String APPLICATION_SMILE = "application/smile";
public static final String APPLICATION_JSON = "application/json";
private final ObjectMapper jsonMapper;
private final ObjectMapper smileMapper;
private final QuerySegmentWalker texasRanger;
private final ServiceEmitter emitter;
private final RequestLogger requestLogger;
private final QueryManager queryManager;
@Inject
public QueryResource(
@Json ObjectMapper jsonMapper,
@Smile ObjectMapper smileMapper,
QuerySegmentWalker texasRanger,
ServiceEmitter emitter,
RequestLogger requestLogger,
QueryManager queryManager
)
{
this.jsonMapper = jsonMapper.copy();
this.jsonMapper.getFactory().configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
this.smileMapper = smileMapper.copy();
this.smileMapper.getFactory().configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
this.texasRanger = texasRanger;
this.emitter = emitter;
this.requestLogger = requestLogger;
this.queryManager = queryManager;
}
@DELETE
@Path("{id}")
@Produces("application/json")
public Response getServer(@PathParam("id") String queryId)
{
queryManager.cancelQuery(queryId);
return Response.status(Response.Status.ACCEPTED).build();
}
@POST
public Response doPost(
@Context HttpServletRequest req,
@Context final HttpServletResponse resp
) throws ServletException, IOException
{
final long start = System.currentTimeMillis();
Query query = null;
byte[] requestQuery = null;
String queryId = null;
final boolean isSmile = APPLICATION_SMILE.equals(req.getContentType());
ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;
final ObjectWriter jsonWriter = req.getParameter("pretty") == null
? objectMapper.writer()
: objectMapper.writerWithDefaultPrettyPrinter();
try {
requestQuery = ByteStreams.toByteArray(req.getInputStream());
query = objectMapper.readValue(requestQuery, Query.class);
queryId = query.getId();
if (queryId == null) {
queryId = UUID.randomUUID().toString();
query = query.withId(queryId);
}
if (log.isDebugEnabled()) {
log.debug("Got query [%s]", query);
}
Sequence res = query.run(texasRanger);
final Sequence results;
if (res == null) {
results = Sequences.empty();
} else {
results = res;
}
final Yielder yielder = results.toYielder(
null,
new YieldingAccumulator()
{
@Override
public Object accumulate(Object accumulated, Object in)
{
yield();
return in;
}
}
);
try {
long requestTime = System.currentTimeMillis() - start;
emitter.emit(
new ServiceMetricEvent.Builder()
.setUser2(DataSourceUtil.getMetricName(query.getDataSource()))
.setUser4(query.getType())
.setUser5(COMMA_JOIN.join(query.getIntervals()))
.setUser6(String.valueOf(query.hasFilters()))
.setUser7(req.getRemoteAddr())
.setUser8(queryId)
.setUser9(query.getDuration().toPeriod().toStandardMinutes().toString())
.build("request/time", requestTime)
);
requestLogger.log(
new RequestLogLine(
new DateTime(),
req.getRemoteAddr(),
query,
new QueryStats(
ImmutableMap.<String, Object>of(
"request/time", requestTime,
"success", true
)
)
)
);
return Response
.ok(
new StreamingOutput()
{
@Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException
{
// json serializer will always close the yielder
jsonWriter.writeValue(outputStream, yielder);
outputStream.close();
}
},
isSmile ? APPLICATION_JSON : APPLICATION_SMILE
)
.header("X-Druid-Query-Id", queryId)
.build();
}
catch (Exception e) {
// make sure to close yieder if anything happened before starting to serialize the response.
yielder.close();
throw Throwables.propagate(e);
}
finally {
// do not close yielder here, since we do not want to close the yielder prior to
// StreamingOutput having iterated over all the results
}
}
catch (QueryInterruptedException e) {
try {
log.info("%s [%s]", e.getMessage(), queryId);
requestLogger.log(
new RequestLogLine(
new DateTime(),
req.getRemoteAddr(),
query,
new QueryStats(ImmutableMap.<String, Object>of("success", false, "interrupted", true, "reason", e.toString()))
)
);
} catch (Exception e2) {
log.error(e2, "Unable to log query [%s]!", query);
}
return Response.serverError().entity(
jsonWriter.writeValueAsString(
ImmutableMap.of(
"error", e.getMessage()
)
)
).build();
}
catch (Exception e) {
final String queryString =
query == null
? (isSmile ? "smile_unknown" : new String(requestQuery, Charsets.UTF_8))
: query.toString();
log.warn(e, "Exception occurred on request [%s]", queryString);
try {
requestLogger.log(
new RequestLogLine(
new DateTime(),
req.getRemoteAddr(),
query,
new QueryStats(ImmutableMap.<String, Object>of("success", false, "exception", e.toString()))
)
);
}
catch (Exception e2) {
log.error(e2, "Unable to log query [%s]!", queryString);
}
log.makeAlert(e, "Exception handling request")
.addData("exception", e.toString())
.addData("query", queryString)
.addData("peer", req.getRemoteAddr())
.emit();
return Response.serverError().entity(
jsonWriter.writeValueAsString(
ImmutableMap.of(
"error", e.getMessage() == null ? "null exception" : e.getMessage()
)
)
).build();
}
}
}
|
package org.languagetool.gui;
import org.languagetool.AnalyzedSentence;
import org.languagetool.JLanguageTool;
import org.languagetool.Language;
import org.languagetool.language.RuleFilenameException;
import org.languagetool.rules.Rule;
import org.languagetool.server.HTTPServer;
import org.languagetool.server.HTTPServerConfig;
import org.languagetool.server.PortBindingException;
import org.languagetool.tools.JnaTools;
import org.languagetool.tools.LanguageIdentifierTools;
import org.languagetool.tools.StringTools;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.text.DefaultEditorKit;
/**
* A simple GUI to check texts with.
*
* @author Daniel Naber
*/
public final class Main {
static final String EXTERNAL_LANGUAGE_SUFFIX = " (ext.)";
static final String HTML_FONT_START = "<font face='Arial,Helvetica'>";
static final String HTML_FONT_END = "</font>";
static final String HTML_GREY_FONT_START = "<font face='Arial,Helvetica' color='#666666'>";
private static final String TRAY_ICON = "/TrayIcon.png";
private static final String TRAY_SERVER_ICON = "/TrayIconWithServer.png";
private static final String TRAY_SMALL_ICON = "/TrayIconSmall.png";
private static final String TRAY_SMALL_SERVER_ICON = "/TrayIconSmallWithServer.png";
private static final String TRAY_TOOLTIP = "LanguageTool";
private static final int WINDOW_WIDTH = 600;
private static final int WINDOW_HEIGHT = 550;
private final ResourceBundle messages;
private JFrame frame;
private JTextArea textArea;
private JTextPane resultArea;
private ResultArea resultAreaHelper;
private LanguageComboBox languageBox;
private CheckboxMenuItem enableHttpServerItem;
private HTTPServer httpServer;
private TrayIcon trayIcon;
private boolean closeHidesToTray;
private boolean isInTray;
private LanguageToolSupport ltSupport;
private OpenAction openAction;
private SaveAction saveAction;
private SaveAsAction saveAsAction;
private AutoCheckAction autoCheckAction;
private CheckAction checkAction;
private File currentFile;
private UndoRedoSupport undoRedo;
private long startTime;
private Main() {
LanguageIdentifierTools.addLtProfiles();
messages = JLanguageTool.getMessageBundle();
}
private void loadFile() {
final File file = Tools.openFileDialog(frame, new PlainTextFileFilter());
if (file == null) {
// user clicked cancel
return;
}
try {
try (FileInputStream inputStream = new FileInputStream(file)) {
final String fileContents = StringTools.readStream(inputStream, null);
textArea.setText(fileContents);
currentFile = file;
updateTitle();
}
} catch (IOException e) {
Tools.showError(e);
}
}
private void saveFile(boolean newFile) {
if (currentFile == null || newFile) {
final JFileChooser jfc = new JFileChooser();
jfc.setFileFilter(new PlainTextFileFilter());
jfc.showSaveDialog(frame);
File file = jfc.getSelectedFile();
if (file == null) {
// user clicked cancel
return;
}
currentFile = file;
updateTitle();
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(currentFile));
writer.write(textArea.getText());
} catch (IOException ex) {
Tools.showError(ex);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {
Tools.showError(ex);
}
}
}
}
private void addLanguage() {
final LanguageManagerDialog lmd = new LanguageManagerDialog(frame, Language.getExternalLanguages());
lmd.show();
try {
Language.reInit(lmd.getLanguages());
} catch (RuleFilenameException e) {
Tools.showErrorMessage(e, frame);
}
languageBox.populateLanguageBox();
languageBox.selectLanguage(ltSupport.getLanguageTool().getLanguage());
}
private void showOptions() {
final JLanguageTool langTool = ltSupport.getLanguageTool();
final List<Rule> rules = langTool.getAllRules();
final ConfigurationDialog configDialog = ltSupport.getCurrentConfigDialog();
configDialog.show(rules); // this blocks until OK/Cancel is clicked in the dialog
Configuration config = ltSupport.getConfig();
config.setDisabledRuleIds(configDialog.getDisabledRuleIds());
config.setEnabledRuleIds(configDialog.getEnabledRuleIds());
config.setDisabledCategoryNames(configDialog.getDisabledCategoryNames());
config.setMotherTongue(configDialog.getMotherTongue());
config.setRunServer(configDialog.getRunServer());
config.setUseGUIConfig(configDialog.getUseGUIConfig());
config.setServerPort(configDialog.getServerPort());
try { //save config - needed for the server
config.saveConfiguration(langTool.getLanguage());
} catch (IOException e) {
Tools.showError(e);
}
// Stop server, start new server if requested:
stopServer();
maybeStartServer();
}
private Component getFrame() {
return frame;
}
private void updateTitle() {
if (currentFile == null) {
frame.setTitle("LanguageTool " + JLanguageTool.VERSION);
} else {
frame.setTitle(currentFile.getName() + " - LanguageTool " + JLanguageTool.VERSION);
}
}
private void createGUI() {
frame = new JFrame("LanguageTool " + JLanguageTool.VERSION);
setLookAndFeel();
openAction = new OpenAction();
saveAction = new SaveAction();
saveAsAction = new SaveAsAction();
checkAction = new CheckAction();
autoCheckAction = new AutoCheckAction(true);
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new CloseListener());
final URL iconUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(TRAY_ICON);
frame.setIconImage(new ImageIcon(iconUrl).getImage());
textArea = new JTextArea();
// TODO: wrong line number is displayed for lines that are wrapped automatically:
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.addKeyListener(new ControlReturnTextCheckingListener());
resultArea = new JTextPane();
undoRedo = new UndoRedoSupport(this.textArea, messages);
frame.setJMenuBar(createMenuBar());
final JPanel panel = new JPanel();
panel.setOpaque(false); // to get rid of the gray background
panel.setLayout(new GridBagLayout());
final GridBagConstraints buttonCons = new GridBagConstraints();
final JPanel insidePanel = new JPanel();
insidePanel.setOpaque(false);
insidePanel.setLayout(new GridBagLayout());
buttonCons.gridx = 0;
buttonCons.gridy = 0;
buttonCons.anchor = GridBagConstraints.WEST;
insidePanel.add(new JLabel(" " + messages.getString("textLanguage") + " "), buttonCons);
languageBox = new LanguageComboBox(messages, EXTERNAL_LANGUAGE_SUFFIX);
languageBox.setRenderer(new LanguageComboBoxRenderer(messages, EXTERNAL_LANGUAGE_SUFFIX));
buttonCons.gridx = 1;
buttonCons.gridy = 0;
insidePanel.add(languageBox, buttonCons);
buttonCons.gridx = 0;
buttonCons.gridy = 0;
panel.add(insidePanel);
buttonCons.gridx = 2;
buttonCons.gridy = 0;
final JCheckBox autoDetectBox = new JCheckBox(messages.getString("atd"));
buttonCons.gridx = 1;
buttonCons.gridy = 1;
buttonCons.gridwidth = 2;
buttonCons.anchor = GridBagConstraints.WEST;
insidePanel.add(autoDetectBox, buttonCons);
final Container contentPane = frame.getContentPane();
final GridBagLayout gridLayout = new GridBagLayout();
contentPane.setLayout(gridLayout);
final GridBagConstraints cons = new GridBagConstraints();
cons.gridx = 0;
cons.gridy = 1;
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.FIRST_LINE_START;
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
toolbar.setFloatable(false);
contentPane.add(toolbar,cons);
JButton openbutton = new JButton(openAction);
openbutton.setHideActionText(true);
openbutton.setFocusable(false);
toolbar.add(openbutton);
JButton savebutton = new JButton(saveAction);
savebutton.setHideActionText(true);
savebutton.setFocusable(false);
toolbar.add(savebutton);
JButton saveasbutton = new JButton(saveAsAction);
saveasbutton.setHideActionText(true);
saveasbutton.setFocusable(false);
toolbar.add(saveasbutton);
JButton spellbutton = new JButton(this.checkAction);
spellbutton.setHideActionText(true);
spellbutton.setFocusable(false);
toolbar.add(spellbutton);
JToggleButton autospellbutton = new JToggleButton(autoCheckAction);
autospellbutton.setHideActionText(true);
autospellbutton.setFocusable(false);
toolbar.add(autospellbutton);
cons.insets = new Insets(5, 5, 5, 5);
cons.fill = GridBagConstraints.BOTH;
cons.weightx = 10.0f;
cons.weighty = 10.0f;
cons.gridx = 0;
cons.gridy = 2;
cons.weighty = 5.0f;
final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JScrollPane(textArea), new JScrollPane(resultArea));
splitPane.setDividerLocation(200);
contentPane.add(splitPane, cons);
cons.fill = GridBagConstraints.NONE;
cons.gridx = 0;
cons.gridy = 2;
cons.weighty = 0.0f;
cons.insets = new Insets(1, 10, 10, 1);
cons.gridy = 3;
contentPane.add(panel, cons);
ltSupport = new LanguageToolSupport(this.frame, this.textArea);
resultAreaHelper = new ResultArea(messages, ltSupport, resultArea);
languageBox.selectLanguage(ltSupport.getLanguageTool().getLanguage());
languageBox.setEnabled(!ltSupport.getConfig().getAutoDetect());
autoDetectBox.setSelected(ltSupport.getConfig().getAutoDetect());
languageBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
{
// we cannot re-use the existing LT object anymore
ltSupport.setLanguage((Language) languageBox.getSelectedItem());
}
}
});
autoDetectBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean selected = (e.getStateChange() == ItemEvent.SELECTED);
languageBox.setEnabled(!selected);
ltSupport.getConfig().setAutoDetect(selected);
if (selected) {
Language detected = ltSupport.autoDetectLanguage(textArea.getText());
languageBox.selectLanguage(detected);
}
}
});
ltSupport.addLanguageToolListener(new LanguageToolListener() {
@Override
public void languageToolEventOccured(LanguageToolEvent event) {
if (event.getType() == LanguageToolEvent.Type.CHECKING_STARTED) {
if(event.getCaller() == getFrame()) {
startTime = System.currentTimeMillis();
setWaitCursor();
checkAction.setEnabled(false);
}
} else if (event.getType() == LanguageToolEvent.Type.CHECKING_FINISHED) {
if(event.getCaller() == getFrame()) {
checkAction.setEnabled(true);
unsetWaitCursor();
resultAreaHelper.setRunTime(System.currentTimeMillis() - startTime);
resultAreaHelper.displayResult();
}
}
else if (event.getType() == LanguageToolEvent.Type.LANGUAGE_CHANGED) {
languageBox.selectLanguage(ltSupport.getLanguageTool().getLanguage());
}
}
});
textArea.setText(messages.getString("guiDemoText"));
frame.pack();
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setLocationByPlatform(true);
maybeStartServer();
}
private String getLabel(String key) {
return StringTools.getLabel(messages.getString(key));
}
private int getMnemonic(String key) {
return StringTools.getMnemonic(messages.getString(key));
}
private KeyStroke getMenuKeyStroke(int keyEvent) {
return KeyStroke.getKeyStroke(keyEvent, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
final JMenu fileMenu = new JMenu(getLabel("guiMenuFile"));
fileMenu.setMnemonic(getMnemonic("guiMenuFile"));
final JMenu editMenu = new JMenu(getLabel("guiMenuEdit"));
editMenu.setMnemonic(getMnemonic("guiMenuEdit"));
final JMenu grammarMenu = new JMenu(getLabel("guiMenuGrammar"));
grammarMenu.setMnemonic(getMnemonic("guiMenuGrammar"));
final JMenu helpMenu = new JMenu(getLabel("guiMenuHelp"));
helpMenu.setMnemonic(getMnemonic("guiMenuHelp"));
fileMenu.add(openAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
fileMenu.addSeparator();
fileMenu.add(new HideAction());
fileMenu.addSeparator();
fileMenu.add(new QuitAction());
grammarMenu.add(checkAction);
JCheckBoxMenuItem item = new JCheckBoxMenuItem(autoCheckAction);
grammarMenu.add(item);
grammarMenu.add(new CheckClipboardAction());
grammarMenu.add(new TagTextAction());
grammarMenu.add(new AddRulesAction());
grammarMenu.add(new OptionsAction());
helpMenu.add(new AboutAction());
undoRedo.undoAction.putValue(Action.NAME, getLabel("guiMenuUndo"));
undoRedo.undoAction.putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuUndo"));
undoRedo.redoAction.putValue(Action.NAME, getLabel("guiMenuRedo"));
undoRedo.redoAction.putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuRedo"));
editMenu.add(undoRedo.undoAction);
editMenu.add(undoRedo.redoAction);
editMenu.addSeparator();
Action cutAction = this.textArea.getActionMap().get(DefaultEditorKit.cutAction);
cutAction.putValue(Action.SMALL_ICON, getImageIcon("sc_cut.png"));
cutAction.putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_cut.png"));
cutAction.putValue(Action.NAME, getLabel("guiMenuCut"));
cutAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_T);
editMenu.add(cutAction);
Action copyAction = textArea.getActionMap().get(DefaultEditorKit.copyAction);
copyAction.putValue(Action.SMALL_ICON, getImageIcon("sc_copy.png"));
copyAction.putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_copy.png"));
copyAction.putValue(Action.NAME, getLabel("guiMenuCopy"));
copyAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);
editMenu.add(copyAction);
Action pasteAction = textArea.getActionMap().get(DefaultEditorKit.pasteAction);
pasteAction.putValue(Action.SMALL_ICON, getImageIcon("sc_paste.png"));
pasteAction.putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_paste.png"));
pasteAction.putValue(Action.NAME, getLabel("guiMenuPaste"));
pasteAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_P);
editMenu.add(pasteAction);
editMenu.addSeparator();
Action selectAllAction = textArea.getActionMap().get(DefaultEditorKit.selectAllAction);
selectAllAction.putValue(Action.NAME, getLabel("guiMenuSelectAll"));
selectAllAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A);
editMenu.add(selectAllAction);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(grammarMenu);
menuBar.add(helpMenu);
return menuBar;
}
private void setLookAndFeel() {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ignored) {
// Well, what can we do...
}
}
private PopupMenu makePopupMenu() {
final PopupMenu popup = new PopupMenu();
final ActionListener rmbListener = new TrayActionRMBListener();
// Enable or disable embedded HTTP server:
enableHttpServerItem = new CheckboxMenuItem(StringTools.getLabel(messages.getString("tray_menu_enable_server")));
enableHttpServerItem.setState(httpServer != null && httpServer.isRunning());
enableHttpServerItem.addItemListener(new TrayActionItemListener());
popup.add(enableHttpServerItem);
// Check clipboard text:
final MenuItem checkClipboardItem =
new MenuItem(StringTools.getLabel(messages.getString("guiMenuCheckClipboard")));
checkClipboardItem.addActionListener(rmbListener);
popup.add(checkClipboardItem);
// Open main window:
final MenuItem restoreItem = new MenuItem(StringTools.getLabel(messages.getString("guiMenuShowMainWindow")));
restoreItem.addActionListener(rmbListener);
popup.add(restoreItem);
// Exit:
final MenuItem exitItem = new MenuItem(StringTools.getLabel(messages.getString("guiMenuQuit")));
exitItem.addActionListener(rmbListener);
popup.add(exitItem);
return popup;
}
private void checkClipboardText() {
final String s = getClipboardText();
textArea.setText(s);
}
private void hideToTray() {
if (!isInTray) {
final SystemTray tray = SystemTray.getSystemTray();
final String iconPath = tray.getTrayIconSize().height > 16 ? TRAY_ICON : TRAY_SMALL_ICON;
final URL iconUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(iconPath);
final Image img = Toolkit.getDefaultToolkit().getImage(iconUrl);
final PopupMenu popup = makePopupMenu();
try {
trayIcon = new TrayIcon(img, TRAY_TOOLTIP, popup);
trayIcon.addMouseListener(new TrayActionListener());
setTrayIcon();
tray.add(trayIcon);
} catch (AWTException e1) {
Tools.showError(e1);
}
}
isInTray = true;
frame.setVisible(false);
}
private void tagText() {
if (StringTools.isEmpty(textArea.getText().trim())) {
textArea.setText(messages.getString("enterText2"));
return;
}
setWaitCursor();
new Thread() {
@Override
public void run() {
try {
tagTextAndDisplayResults();
} finally {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
unsetWaitCursor();
}
});
}
}
}.start();
}
private void quitOrHide() {
if (closeHidesToTray) {
hideToTray();
} else {
quit();
}
}
private void quit() {
stopServer();
try {
Configuration config = ltSupport.getConfig();
config.setLanguage(ltSupport.getLanguageTool().getLanguage());
config.saveConfiguration(ltSupport.getLanguageTool().getLanguage());
} catch (IOException e) {
Tools.showError(e);
}
frame.setVisible(false);
JLanguageTool.removeTemporaryFiles();
System.exit(0);
}
private void setTrayIcon() {
if (trayIcon != null) {
final SystemTray tray = SystemTray.getSystemTray();
final boolean httpServerRunning = httpServer != null && httpServer.isRunning();
final boolean smallTray = tray.getTrayIconSize().height <= 16;
final String iconPath;
if (httpServerRunning) {
trayIcon.setToolTip(messages.getString("tray_tooltip_server_running"));
iconPath = smallTray ? TRAY_SMALL_SERVER_ICON : TRAY_SERVER_ICON;
} else {
trayIcon.setToolTip(TRAY_TOOLTIP);
iconPath = smallTray ? TRAY_SMALL_ICON : TRAY_ICON;
}
final URL iconUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(iconPath);
final Image img = Toolkit.getDefaultToolkit().getImage(iconUrl);
trayIcon.setImage(img);
}
}
private void showGUI() {
frame.setVisible(true);
}
private void restoreFromTray() {
frame.setVisible(true);
}
// show GUI and check the text from clipboard/selection:
private void restoreFromTrayAndCheck() {
final String s = getClipboardText();
restoreFromTray();
textArea.setText(s);
}
private String getClipboardText() {
// get text from clipboard or selection:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (clipboard == null) { // on Windows
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
String s;
final Transferable data = clipboard.getContents(this);
try {
if (data != null
&& data.isDataFlavorSupported(DataFlavor.getTextPlainUnicodeFlavor())) {
final DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor();
final Reader sr = df.getReaderForText(data);
s = StringTools.readerToString(sr);
} else {
s = "";
}
} catch (Exception ex) {
if (data != null) {
s = data.toString();
} else {
s = "";
}
}
return s;
}
private boolean maybeStartServer() {
Configuration config = ltSupport.getConfig();
if (config.getRunServer()) {
try {
final HTTPServerConfig serverConfig = new HTTPServerConfig(config.getServerPort(), false);
httpServer = new HTTPServer(serverConfig, true);
httpServer.run();
if (enableHttpServerItem != null) {
enableHttpServerItem.setState(httpServer.isRunning());
setTrayIcon();
}
} catch (PortBindingException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
return httpServer != null && httpServer.isRunning();
}
private void stopServer() {
if (httpServer != null) {
httpServer.stop();
if (enableHttpServerItem != null) {
enableHttpServerItem.setState(httpServer.isRunning());
setTrayIcon();
}
httpServer = null;
}
}
private void checkTextAndDisplayResults() {
if (StringTools.isEmpty(textArea.getText().trim())) {
textArea.setText(messages.getString("enterText2"));
return;
}
ltSupport.checkImmediately(getFrame());
}
private String getStackTraceAsHtml(Exception e) {
return "<br><br><b><font color=\"red\">"
+ org.languagetool.tools.Tools.getFullStackTrace(e).replace("\n", "<br/>")
+ "</font></b><br>";
}
private void setWaitCursor() {
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// For some reason we also have to set the cursor here so it also shows
// when user starts checking text with Ctrl+Return:
textArea.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
resultArea.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
private void unsetWaitCursor() {
frame.setCursor(Cursor.getDefaultCursor());
textArea.setCursor(Cursor.getDefaultCursor());
resultArea.setCursor(Cursor.getDefaultCursor());
}
private void tagTextAndDisplayResults() {
final JLanguageTool langTool = ltSupport.getLanguageTool();
// tag text
final List<String> sentences = langTool.sentenceTokenize(textArea.getText());
final StringBuilder sb = new StringBuilder();
try {
for (String sent : sentences) {
final AnalyzedSentence analyzedText = langTool.getAnalyzedSentence(sent);
final String analyzedTextString = StringTools.escapeHTML(analyzedText.toString(", ")).
replace("[", "<font color='#888888'>[").replace("]", "]</font>");
sb.append(analyzedTextString).append("\n");
}
} catch (Exception e) {
sb.append(getStackTraceAsHtml(e));
}
// This method is thread safe
resultArea.setText(HTML_FONT_START + sb.toString() + HTML_FONT_END);
}
private void setTrayMode(boolean trayMode) {
this.closeHidesToTray = trayMode;
}
public static void main(final String[] args) {
JnaTools.setBugWorkaroundProperty();
final Main prg = new Main();
if (args.length == 1 && (args[0].equals("-t") || args[0].equals("--tray"))) {
// dock to systray on startup
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
prg.createGUI();
prg.setTrayMode(true);
prg.hideToTray();
} catch (Exception e) {
Tools.showError(e);
System.exit(1);
}
}
});
} else if (args.length >= 1) {
System.out.println("Usage: java org.languagetool.gui.Main [-t|--tray]");
System.out.println(" -t, --tray: dock LanguageTool to system tray on startup");
} else {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
prg.createGUI();
prg.showGUI();
} catch (Exception e) {
Tools.showError(e);
}
}
});
}
}
private class ControlReturnTextCheckingListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if ((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) == KeyEvent.CTRL_DOWN_MASK) {
checkTextAndDisplayResults();
}
}
}
}
// The System Tray stuff
class TrayActionItemListener implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
try {
final ConfigurationDialog configDialog = ltSupport.getCurrentConfigDialog();
final Configuration config = ltSupport.getConfig();
if (e.getStateChange() == ItemEvent.SELECTED) {
config.setRunServer(true);
final boolean serverStarted = maybeStartServer();
enableHttpServerItem.setState(serverStarted);
config.setRunServer(serverStarted);
config.saveConfiguration(ltSupport.getLanguageTool().getLanguage());
if (configDialog != null) {
configDialog.setRunServer(true);
}
} else if (e.getStateChange() == ItemEvent.DESELECTED) {
config.setRunServer(false);
config.saveConfiguration(ltSupport.getLanguageTool().getLanguage());
if (configDialog != null) {
configDialog.setRunServer(false);
}
stopServer();
}
} catch (IOException ex) {
Tools.showError(ex);
}
}
}
class TrayActionRMBListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (isCommand(e, "guiMenuCheckClipboard")) {
restoreFromTrayAndCheck();
} else if (isCommand(e, "guiMenuShowMainWindow")) {
restoreFromTray();
} else if (isCommand(e, "guiMenuQuit")) {
quit();
} else {
JOptionPane.showMessageDialog(null, "Unknown action: "
+ e.getActionCommand(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
private boolean isCommand(ActionEvent e, String label) {
return e.getActionCommand().equalsIgnoreCase(StringTools.getLabel(messages.getString(label)));
}
}
class TrayActionListener implements MouseListener {
@Override
public void mouseClicked(@SuppressWarnings("unused")MouseEvent e) {
if (frame.isVisible() && frame.isActive()) {
frame.setVisible(false);
} else if (frame.isVisible() && !frame.isActive()) {
frame.toFront();
restoreFromTrayAndCheck();
} else {
restoreFromTrayAndCheck();
}
}
@Override
public void mouseEntered(@SuppressWarnings("unused") MouseEvent e) {}
@Override
public void mouseExited(@SuppressWarnings("unused")MouseEvent e) {}
@Override
public void mousePressed(@SuppressWarnings("unused")MouseEvent e) {}
@Override
public void mouseReleased(@SuppressWarnings("unused")MouseEvent e) {}
}
class CloseListener implements WindowListener {
@Override
public void windowClosing(@SuppressWarnings("unused")WindowEvent e) {
quitOrHide();
}
@Override
public void windowActivated(@SuppressWarnings("unused")WindowEvent e) {}
@Override
public void windowClosed(@SuppressWarnings("unused")WindowEvent e) {}
@Override
public void windowDeactivated(@SuppressWarnings("unused")WindowEvent e) {}
@Override
public void windowDeiconified(@SuppressWarnings("unused")WindowEvent e) {}
@Override
public void windowIconified(@SuppressWarnings("unused")WindowEvent e) {}
@Override
public void windowOpened(@SuppressWarnings("unused")WindowEvent e) {}
}
static class PlainTextFileFilter extends FileFilter {
@Override
public boolean accept(final File f) {
final boolean isTextFile = f.getName().toLowerCase().endsWith(".txt");
return isTextFile || f.isDirectory();
}
@Override
public String getDescription() {
return "*.txt";
}
}
class OpenAction extends AbstractAction {
public OpenAction() {
super(getLabel("guiMenuOpen"));
putValue(Action.SHORT_DESCRIPTION, messages.getString("guiMenuOpenShortDesc"));
putValue(Action.LONG_DESCRIPTION, messages.getString("guiMenuOpenLongDesc"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuOpen"));
putValue(Action.ACCELERATOR_KEY, getMenuKeyStroke(KeyEvent.VK_O));
putValue(Action.SMALL_ICON, getImageIcon("sc_open.png"));
putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_open.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
loadFile();
}
}
class SaveAction extends AbstractAction {
public SaveAction() {
super(getLabel("guiMenuSave"));
putValue(Action.SHORT_DESCRIPTION, messages.getString("guiMenuSaveShortDesc"));
putValue(Action.LONG_DESCRIPTION, messages.getString("guiMenuSaveLongDesc"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuSave"));
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
putValue(Action.SMALL_ICON, getImageIcon("sc_save.png"));
putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_save.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
saveFile(false);
}
}
class SaveAsAction extends AbstractAction {
public SaveAsAction() {
super(getLabel("guiMenuSaveAs"));
putValue(Action.SHORT_DESCRIPTION, messages.getString("guiMenuSaveAsShortDesc"));
putValue(Action.LONG_DESCRIPTION, messages.getString("guiMenuSaveAsLongDesc"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuSaveAs"));
putValue(Action.SMALL_ICON, getImageIcon("sc_saveas.png"));
putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_saveas.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
saveFile(true);
}
}
class CheckClipboardAction extends AbstractAction {
public CheckClipboardAction() {
super(getLabel("guiMenuCheckClipboard"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuCheckClipboard"));
putValue(Action.ACCELERATOR_KEY, getMenuKeyStroke(KeyEvent.VK_Y));
}
@Override
public void actionPerformed(ActionEvent e) {
checkClipboardText();
}
}
class TagTextAction extends AbstractAction {
public TagTextAction() {
super(getLabel("guiTagText"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiTagText"));
putValue(Action.ACCELERATOR_KEY, getMenuKeyStroke(KeyEvent.VK_T));
}
@Override
public void actionPerformed(ActionEvent e) {
tagText();
}
}
class AddRulesAction extends AbstractAction {
public AddRulesAction() {
super(getLabel("guiMenuAddRules"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuAddRules"));
}
@Override
public void actionPerformed(ActionEvent e) {
addLanguage();
}
}
class OptionsAction extends AbstractAction {
public OptionsAction() {
super(getLabel("guiMenuOptions"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuOptions"));
putValue(Action.ACCELERATOR_KEY, getMenuKeyStroke(KeyEvent.VK_S));
}
@Override
public void actionPerformed(ActionEvent e) {
showOptions();
}
}
class HideAction extends AbstractAction {
public HideAction() {
super(getLabel("guiMenuHide"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuHide"));
putValue(Action.ACCELERATOR_KEY, getMenuKeyStroke(KeyEvent.VK_D));
}
@Override
public void actionPerformed(ActionEvent e) {
hideToTray();
}
}
class QuitAction extends AbstractAction {
public QuitAction() {
super(getLabel("guiMenuQuit"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuQuit"));
putValue(Action.ACCELERATOR_KEY, getMenuKeyStroke(KeyEvent.VK_Q));
}
@Override
public void actionPerformed(ActionEvent e) {
quit();
}
}
class AboutAction extends AbstractAction {
public AboutAction() {
super(getLabel("guiMenuAbout"));
putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuAbout"));
}
@Override
public void actionPerformed(ActionEvent e) {
AboutDialog about = new AboutDialog(messages, getFrame());
about.show();
}
}
class CheckAction extends AbstractAction {
public CheckAction() {
super(getLabel("checkText"));
putValue(Action.SHORT_DESCRIPTION, messages.getString("checkTextShortDesc"));
putValue(Action.LONG_DESCRIPTION, messages.getString("checkTextLongDesc"));
putValue(Action.MNEMONIC_KEY, getMnemonic("checkText"));
putValue(Action.SMALL_ICON, getImageIcon("sc_spelldialog.png"));
putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_spelldialog.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
checkTextAndDisplayResults();
}
}
class AutoCheckAction extends AbstractAction {
private boolean enable;
public AutoCheckAction(boolean initial) {
super(getLabel("autoCheckText"));
putValue(Action.SHORT_DESCRIPTION, messages.getString("autoCheckTextShortDesc"));
putValue(Action.LONG_DESCRIPTION, messages.getString("autoCheckTextLongDesc"));
putValue(Action.MNEMONIC_KEY, getMnemonic("autoCheckText"));
putValue(Action.SMALL_ICON, getImageIcon("sc_spellonline.png"));
putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_spellonline.png"));
enable = initial;
putValue(Action.SELECTED_KEY, enable);
}
@Override
public void actionPerformed(ActionEvent e) {
enable = !enable;
putValue(Action.SELECTED_KEY, enable);
ltSupport.setBackgroundCheckEnabled(enable);
}
}
private ImageIcon getImageIcon(String filename) {
Image image = Toolkit.getDefaultToolkit().getImage(
JLanguageTool.getDataBroker().getFromResourceDirAsUrl(filename));
return new ImageIcon(image);
}
}
|
package ru.atom.lecture08.websocket;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import java.io.IOException;
public class EventClient {
public static void main(String[] args) {
// connection url
String uri = "ws://localhost:8080/events";
StandardWebSocketClient client = new StandardWebSocketClient();
WebSocketSession session = null;
try {
// The socket that receives events
EventHandler socket = new EventHandler();
// Make a handshake with server
ListenableFuture<WebSocketSession> fut = client.doHandshake(socket, uri);
// Wait for Connect
session = fut.get();
// Send a message
session.sendMessage(new TextMessage("Hello"));
// Close session
session.close();
} catch (Throwable t) {
t.printStackTrace(System.err);
} finally {
try {
if (session != null) {
session.close();
}
} catch (IOException ignored) {
}
}
}
}
|
package net.cachapa.expandablelayout;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import net.cachapa.expandablelayout.util.FastOutSlowInInterpolator;
import static net.cachapa.expandablelayout.ExpandableLayout.State.COLLAPSED;
import static net.cachapa.expandablelayout.ExpandableLayout.State.COLLAPSING;
import static net.cachapa.expandablelayout.ExpandableLayout.State.EXPANDED;
import static net.cachapa.expandablelayout.ExpandableLayout.State.EXPANDING;
public class ExpandableLayout extends FrameLayout {
public interface State {
int COLLAPSED = 0;
int COLLAPSING = 1;
int EXPANDING = 2;
int EXPANDED = 3;
}
public static final String KEY_SUPER_STATE = "super_state";
public static final String KEY_EXPANSION = "expansion";
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
private static final int DEFAULT_DURATION = 300;
private int duration = DEFAULT_DURATION;
private float parallax;
private float expansion;
private int orientation;
private int state;
private Interpolator interpolator = new FastOutSlowInInterpolator();
private ValueAnimator animator;
private OnExpansionUpdateListener listener;
public ExpandableLayout(Context context) {
this(context, null);
}
public ExpandableLayout(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandableLayout);
duration = a.getInt(R.styleable.ExpandableLayout_el_duration, DEFAULT_DURATION);
expansion = a.getBoolean(R.styleable.ExpandableLayout_el_expanded, false) ? 1 : 0;
orientation = a.getInt(R.styleable.ExpandableLayout_android_orientation, VERTICAL);
parallax = a.getFloat(R.styleable.ExpandableLayout_el_parallax, 1);
a.recycle();
state = expansion == 0 ? COLLAPSED : EXPANDED;
setParallax(parallax);
}
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle bundle = new Bundle();
expansion = isExpanded() ? 1 : 0;
bundle.putFloat(KEY_EXPANSION, expansion);
bundle.putParcelable(KEY_SUPER_STATE, superState);
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable parcelable) {
Bundle bundle = (Bundle) parcelable;
expansion = bundle.getFloat(KEY_EXPANSION);
state = expansion == 1 ? EXPANDED : COLLAPSED;
Parcelable superState = bundle.getParcelable(KEY_SUPER_STATE);
super.onRestoreInstanceState(superState);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int size = orientation == LinearLayout.HORIZONTAL ? width : height;
setVisibility(expansion == 0 && size == 0 ? GONE : VISIBLE);
int expansionDelta = size - Math.round(size * expansion);
if (parallax > 0) {
float parallaxDelta = expansionDelta * parallax;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (orientation == HORIZONTAL) {
int direction = -1;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
direction = 1;
}
child.setTranslationX(direction * parallaxDelta);
} else {
child.setTranslationY(-parallaxDelta);
}
}
}
if (orientation == HORIZONTAL) {
setMeasuredDimension(width - expansionDelta, height);
} else {
setMeasuredDimension(width, height - expansionDelta);
}
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
if (animator != null) {
animator.cancel();
}
super.onConfigurationChanged(newConfig);
}
/**
* Get expansion state
*
* @return one of {@link State}
*/
public int getState() {
return state;
}
public boolean isExpanded() {
return state == EXPANDING || state == EXPANDED;
}
public void toggle() {
toggle(true);
}
public void toggle(boolean animate) {
if (isExpanded()) {
collapse(animate);
} else {
expand(animate);
}
}
public void expand() {
expand(true);
}
public void expand(boolean animate) {
setExpanded(true, animate);
}
public void collapse() {
collapse(true);
}
public void collapse(boolean animate) {
setExpanded(false, animate);
}
/**
* Convenience method - same as calling setExpanded(expanded, true)
*/
public void setExpanded(boolean expand) {
setExpanded(expand, true);
}
public void setExpanded(boolean expand, boolean animate) {
if (expand && isExpanded()) {
return;
}
if (!expand && !isExpanded()) {
return;
}
int targetExpansion = expand ? 1 : 0;
if (animate) {
animateSize(targetExpansion);
} else {
setExpansionInternal(targetExpansion);
}
}
public int getDuration() {
return duration;
}
public void setInterpolator(Interpolator interpolator) {
this.interpolator = interpolator;
}
public void setDuration(int duration) {
this.duration = duration;
}
public float getExpansion() {
return expansion;
}
public void setExpansion(float expansion) {
if (this.expansion == expansion) {
return;
}
// Infer state from previous value
float delta = expansion - this.expansion;
if (expansion == 0) {
state = COLLAPSED;
} else if (expansion == 1) {
state = EXPANDED;
} else if (delta < 0) {
state = COLLAPSING;
} else if (delta > 0) {
state = EXPANDING;
}
setExpansionInternal(expansion);
}
private void setExpansionInternal(float expansion) {
// update the state
state = expansion == 0 ? COLLAPSED : EXPANDED;
setVisibility(state == COLLAPSED ? GONE : VISIBLE);
this.expansion = expansion;
requestLayout();
if (listener != null) {
listener.onExpansionUpdate(expansion, state);
}
}
public float getParallax() {
return parallax;
}
public void setParallax(float parallax) {
// Make sure parallax is between 0 and 1
parallax = Math.min(1, Math.max(0, parallax));
this.parallax = parallax;
}
public int getOrientation() {
return orientation;
}
public void setOrientation(int orientation) {
if (orientation < 0 || orientation > 1) {
throw new IllegalArgumentException("Orientation must be either 0 (horizontal) or 1 (vertical)");
}
this.orientation = orientation;
}
public void setOnExpansionUpdateListener(OnExpansionUpdateListener listener) {
this.listener = listener;
}
private void animateSize(int targetExpansion) {
if (animator != null) {
animator.cancel();
animator = null;
}
animator = ValueAnimator.ofFloat(expansion, targetExpansion);
animator.setInterpolator(interpolator);
animator.setDuration(duration);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
setExpansionInternal((float) valueAnimator.getAnimatedValue());
}
});
animator.addListener(new ExpansionListener(targetExpansion));
animator.start();
}
public interface OnExpansionUpdateListener {
/**
* Callback for expansion updates
*
* @param expansionFraction Value between 0 (collapsed) and 1 (expanded) representing the the expansion progress
* @param state One of {@link State} repesenting the current expansion state
*/
void onExpansionUpdate(float expansionFraction, int state);
}
private class ExpansionListener implements Animator.AnimatorListener {
private int targetExpansion;
private boolean canceled;
public ExpansionListener(int targetExpansion) {
this.targetExpansion = targetExpansion;
}
@Override
public void onAnimationStart(Animator animation) {
state = targetExpansion == 0 ? COLLAPSING : EXPANDING;
}
@Override
public void onAnimationEnd(Animator animation) {
if (!canceled) {
setExpansionInternal(targetExpansion);
}
}
@Override
public void onAnimationCancel(Animator animation) {
canceled = true;
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
}
|
package com.mikepenz.fastadapter;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.mikepenz.fastadapter.listeners.ClickEventHook;
import com.mikepenz.fastadapter.listeners.EventHook;
import com.mikepenz.fastadapter.listeners.LongClickEventHook;
import com.mikepenz.fastadapter.listeners.OnBindViewHolderListener;
import com.mikepenz.fastadapter.listeners.OnBindViewHolderListenerImpl;
import com.mikepenz.fastadapter.listeners.OnClickListener;
import com.mikepenz.fastadapter.listeners.OnCreateViewHolderListener;
import com.mikepenz.fastadapter.listeners.OnCreateViewHolderListenerImpl;
import com.mikepenz.fastadapter.listeners.OnLongClickListener;
import com.mikepenz.fastadapter.listeners.OnTouchListener;
import com.mikepenz.fastadapter.listeners.TouchEventHook;
import com.mikepenz.fastadapter.select.SelectExtension;
import com.mikepenz.fastadapter.utils.AdapterPredicate;
import com.mikepenz.fastadapter.utils.DefaultTypeInstanceCache;
import com.mikepenz.fastadapter.utils.EventHookUtil;
import com.mikepenz.fastadapter.utils.Triple;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.collection.ArrayMap;
import androidx.core.util.Pair;
import androidx.recyclerview.widget.RecyclerView;
import static com.mikepenz.fastadapter.adapters.ItemAdapter.items;
/**
* The `FastAdapter` class is the core managing class of the `FastAdapter` library, it handles all `IAdapter` implementations, keeps track of the item types which can be displayed
* and correctly provides the size and position and identifier information to the {@link RecyclerView}.
* <p>
* It also comes with {@link IAdapterExtension} allowing to further modify its behaviour.
* Additionally it allows to attach various different listener's, and also {@link EventHook}s on per item and view basis.
* <p>
* See the sample application for more details
*
* @param <Item> Defines the type of items this `FastAdapter` manages (in case of multiple different types, use `IItem`)
*/
public class FastAdapter<Item extends IItem> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = "FastAdapter";
// we remember all adapters
//priority queue...
final private ArrayList<IAdapter<Item>> mAdapters = new ArrayList<>();
// we remember all possible types so we can create a new view efficiently
private ITypeInstanceCache<Item> mTypeInstanceCache;
// cache the sizes of the different adapters so we can access the items more performant
final private SparseArray<IAdapter<Item>> mAdapterSizes = new SparseArray<>();
// the total size
private int mGlobalSize = 0;
// event hooks for the items
private List<EventHook<Item>> eventHooks;
// the extensions we support
final private Map<Class, IAdapterExtension<Item>> mExtensions = new ArrayMap<>();
private SelectExtension<Item> mSelectExtension = new SelectExtension<>();
// legacy bindView mode. if activated we will forward onBindView without payloads to the method with payloads
private boolean mLegacyBindViewMode = false;
// if set to `false` will not attach any listeners to the list. click events will have to be handled manually
private boolean mAttachDefaultListeners = true;
// verbose
private boolean mVerbose = false;
// the listeners which can be hooked on an item
private OnClickListener<Item> mOnPreClickListener;
private OnClickListener<Item> mOnClickListener;
private OnLongClickListener<Item> mOnPreLongClickListener;
private OnLongClickListener<Item> mOnLongClickListener;
private OnTouchListener<Item> mOnTouchListener;
//the listeners for onCreateViewHolder or onBindViewHolder
private OnCreateViewHolderListener mOnCreateViewHolderListener = new OnCreateViewHolderListenerImpl();
private OnBindViewHolderListener mOnBindViewHolderListener = new OnBindViewHolderListenerImpl();
private static int floorIndex(SparseArray<?> sparseArray, int key) {
int index = sparseArray.indexOfKey(key);
if (index < 0) {
index = ~index - 1;
}
return index;
}
/**
* default CTOR
*/
public FastAdapter() {
setHasStableIds(true);
}
/**
* enables the verbose log for the adapter
*
* @return this
*/
public FastAdapter<Item> enableVerboseLog() {
this.mVerbose = true;
return this;
}
/**
* Sets an type instance cache to this fast adapter instance.
* The cache will manage the type instances to create new views more efficient.
* Normally an shared cache is used over all adapter instances.
*
* @param mTypeInstanceCache a custom `TypeInstanceCache` implementation
*/
public void setTypeInstanceCache(ITypeInstanceCache<Item> mTypeInstanceCache) {
this.mTypeInstanceCache = mTypeInstanceCache;
}
/**
* @return the current type instance cache
*/
public ITypeInstanceCache<Item> getTypeInstanceCache() {
if (mTypeInstanceCache == null) {
mTypeInstanceCache = new DefaultTypeInstanceCache<>();
}
return mTypeInstanceCache;
}
/**
* creates a new FastAdapter with the provided adapters
* if adapters is null, a default ItemAdapter is defined
*
* @param adapter the adapters which this FastAdapter should use
* @return a new FastAdapter
*/
@SuppressWarnings("unchecked")
public static <Item extends IItem, A extends IAdapter> FastAdapter<Item> with(A adapter) {
FastAdapter<Item> fastAdapter = new FastAdapter<>();
fastAdapter.addAdapter(0, adapter);
return fastAdapter;
}
/**
* creates a new FastAdapter with the provided adapters
* if adapters is null, a default ItemAdapter is defined
*
* @param adapters the adapters which this FastAdapter should use
* @return a new FastAdapter
*/
public static <Item extends IItem, A extends IAdapter> FastAdapter<Item> with(@Nullable Collection<A> adapters) {
return with(adapters, null);
}
/**
* creates a new FastAdapter with the provided adapters
* if adapters is null, a default ItemAdapter is defined
*
* @param adapters the adapters which this FastAdapter should use
* @return a new FastAdapter
*/
@SuppressWarnings("unchecked")
public static <Item extends IItem, A extends IAdapter> FastAdapter<Item> with(@Nullable Collection<A> adapters, @Nullable Collection<IAdapterExtension<Item>> extensions) {
FastAdapter<Item> fastAdapter = new FastAdapter<>();
if (adapters == null) {
fastAdapter.mAdapters.add((IAdapter<Item>) items());
} else {
fastAdapter.mAdapters.addAll((Collection<IAdapter<Item>>) adapters);
}
for (int i = 0; i < fastAdapter.mAdapters.size(); i++) {
fastAdapter.mAdapters.get(i).withFastAdapter(fastAdapter).setOrder(i);
}
fastAdapter.cacheSizes();
if (extensions != null) {
for (IAdapterExtension<Item> extension : extensions) {
fastAdapter.addExtension(extension);
}
}
return fastAdapter;
}
/**
* add's a new adapter at the specific position
*
* @param index the index where the new adapter should be added
* @param adapter the new adapter to be added
* @return this
*/
public <A extends IAdapter<Item>> FastAdapter<Item> addAdapter(int index, A adapter) {
mAdapters.add(index, adapter);
adapter.withFastAdapter(this);
adapter.mapPossibleTypes(adapter.getAdapterItems());
for (int i = 0; i < mAdapters.size(); i++) {
mAdapters.get(i).setOrder(i);
}
cacheSizes();
return this;
}
/**
* Tries to get an adapter by a specific order
*
* @param order the order (position) to search the adapter at
* @return the IAdapter if found
*/
@Nullable
public IAdapter<Item> adapter(int order) {
if (mAdapters.size() <= order) {
return null;
}
return mAdapters.get(order);
}
/**
* @param extension
* @return
*/
public <E extends IAdapterExtension<Item>> FastAdapter<Item> addExtension(E extension) {
if (mExtensions.containsKey(extension.getClass())) {
throw new IllegalStateException("The given extension was already registered with this FastAdapter instance");
}
mExtensions.put(extension.getClass(), extension);
extension.init(this);
return this;
}
/**
* @return the AdapterExtensions we provided
*/
public Collection<IAdapterExtension<Item>> getExtensions() {
return mExtensions.values();
}
/**
* @param clazz the extension class, to retrieve its instance
* @return the found IAdapterExtension or null if it is not found
*/
@Nullable
@SuppressWarnings("unchecked")
public <T extends IAdapterExtension<Item>> T getExtension(Class<? super T> clazz) {
return (T) mExtensions.get(clazz);
}
/**
* adds a new event hook for an item
* NOTE: this has to be called before adding the first items, as this won't be called anymore after the ViewHolders were created
*
* @param eventHook the event hook to be added for an item
* @return this
* @deprecated please use `withEventHook`
*/
@Deprecated
public FastAdapter<Item> withItemEvent(EventHook<Item> eventHook) {
return withEventHook(eventHook);
}
/**
* @return the eventHooks handled by this FastAdapter
*/
public List<EventHook<Item>> getEventHooks() {
return eventHooks;
}
/**
* adds a new event hook for an item
* NOTE: this has to be called before adding the first items, as this won't be called anymore after the ViewHolders were created
*
* @param eventHook the event hook to be added for an item
* @return this
*/
public FastAdapter<Item> withEventHook(EventHook<Item> eventHook) {
if (eventHooks == null) {
eventHooks = new LinkedList<>();
}
eventHooks.add(eventHook);
return this;
}
/**
* adds new event hooks for an item
* NOTE: this has to be called before adding the first items, as this won't be called anymore after the ViewHolders were created
*
* @param eventHooks the event hooks to be added for an item
* @return this
*/
public FastAdapter<Item> withEventHooks(@Nullable Collection<? extends EventHook<Item>> eventHooks) {
if (eventHooks == null) {
return this;
}
if (this.eventHooks == null) {
this.eventHooks = new LinkedList<>();
}
this.eventHooks.addAll(eventHooks);
return this;
}
/**
* Define the OnClickListener which will be used for a single item
*
* @param onClickListener the OnClickListener which will be used for a single item
* @return this
*/
public FastAdapter<Item> withOnClickListener(OnClickListener<Item> onClickListener) {
this.mOnClickListener = onClickListener;
return this;
}
/**
* @return the set OnClickListener
*/
public OnClickListener<Item> getOnClickListener() {
return mOnClickListener;
}
/**
* Define the OnPreClickListener which will be used for a single item and is called after all internal methods are done
*
* @param onPreClickListener the OnPreClickListener which will be called after a single item was clicked and all internal methods are done
* @return this
*/
public FastAdapter<Item> withOnPreClickListener(OnClickListener<Item> onPreClickListener) {
this.mOnPreClickListener = onPreClickListener;
return this;
}
/**
* Define the OnLongClickListener which will be used for a single item
*
* @param onLongClickListener the OnLongClickListener which will be used for a single item
* @return this
*/
public FastAdapter<Item> withOnLongClickListener(OnLongClickListener<Item> onLongClickListener) {
this.mOnLongClickListener = onLongClickListener;
return this;
}
/**
* Define the OnLongClickListener which will be used for a single item and is called after all internal methods are done
*
* @param onPreLongClickListener the OnLongClickListener which will be called after a single item was clicked and all internal methods are done
* @return this
*/
public FastAdapter<Item> withOnPreLongClickListener(OnLongClickListener<Item> onPreLongClickListener) {
this.mOnPreLongClickListener = onPreLongClickListener;
return this;
}
/**
* Define the TouchListener which will be used for a single item
*
* @param onTouchListener the TouchListener which will be used for a single item
* @return this
*/
public FastAdapter<Item> withOnTouchListener(OnTouchListener<Item> onTouchListener) {
this.mOnTouchListener = onTouchListener;
return this;
}
/**
* allows you to set a custom OnCreateViewHolderListener which will be used before and after the ViewHolder is created
* You may check the OnCreateViewHolderListenerImpl for the default behavior
*
* @param onCreateViewHolderListener the OnCreateViewHolderListener (you may use the OnCreateViewHolderListenerImpl)
*/
public FastAdapter<Item> withOnCreateViewHolderListener(OnCreateViewHolderListener onCreateViewHolderListener) {
this.mOnCreateViewHolderListener = onCreateViewHolderListener;
return this;
}
/**
* allows you to set an custom OnBindViewHolderListener which is used to bind the view. This will overwrite the libraries behavior.
* You may check the OnBindViewHolderListenerImpl for the default behavior
*
* @param onBindViewHolderListener the OnBindViewHolderListener
*/
public FastAdapter<Item> withOnBindViewHolderListener(OnBindViewHolderListener onBindViewHolderListener) {
this.mOnBindViewHolderListener = onBindViewHolderListener;
return this;
}
/**
* select between the different selection behaviors.
* there are now 2 different variants of selection. you can toggle this via `withSelectWithItemUpdate(boolean)` (where false == default - variant 1)
* 1.) direct selection via the view "selected" state, we also make sure we do not animate here so no notifyItemChanged is called if we repeatly press the same item
* 2.) we select the items via a notifyItemChanged. this will allow custom selected logics within your views (isSelected() - do something...) and it will also animate the change via the provided itemAnimator. because of the animation of the itemAnimator the selection will have a small delay (time of animating)
*
* @param selectWithItemUpdate true if notifyItemChanged should be called upon select
* @return this
*/
public FastAdapter<Item> withSelectWithItemUpdate(boolean selectWithItemUpdate) {
mSelectExtension.withSelectWithItemUpdate(selectWithItemUpdate);
return this;
}
/**
* Enable this if you want multiSelection possible in the list
*
* @param multiSelect true to enable multiSelect
* @return this
*/
public FastAdapter<Item> withMultiSelect(boolean multiSelect) {
mSelectExtension.withMultiSelect(multiSelect);
return this;
}
/**
* Disable this if you want the selection on a single tap
*
* @param selectOnLongClick false to do select via single click
* @return this
*/
public FastAdapter<Item> withSelectOnLongClick(boolean selectOnLongClick) {
mSelectExtension.withSelectOnLongClick(selectOnLongClick);
return this;
}
/**
* If false, a user can't deselect an item via click (you can still do this programmatically)
*
* @param allowDeselection true if a user can deselect an already selected item via click
* @return this
*/
public FastAdapter<Item> withAllowDeselection(boolean allowDeselection) {
mSelectExtension.withAllowDeselection(allowDeselection);
return this;
}
/**
* set if no item is selectable
*
* @param selectable true if items are selectable
* @return this
*/
public FastAdapter<Item> withSelectable(boolean selectable) {
if (selectable) {
addExtension(mSelectExtension);
} else {
mExtensions.remove(mSelectExtension.getClass());
}
//TODO revisit this --> false means anyways that it is not in the extension list!
mSelectExtension.withSelectable(selectable);
return this;
}
/**
* set to true if you want the FastAdapter to forward all calls from onBindViewHolder(final RecyclerView.ViewHolder holder, int position) to onBindViewHolder(final RecyclerView.ViewHolder holder, int position, List payloads)
*
* @param legacyBindViewMode true if you want to activate it (default = false)
* @return this
*/
public FastAdapter<Item> withLegacyBindViewMode(boolean legacyBindViewMode) {
this.mLegacyBindViewMode = legacyBindViewMode;
return this;
}
/**
* if set to `false` will not attach any listeners to the list. click events will have to be handled manually
* It is important to remember, if deactivated no listeners won't be attached at a later time either, as the
* listeners are only attached at ViewHolder creation time.
*
* @param mAttachDefaultListeners false if you want no listeners attached to the item (default = true)
* @return this
*/
public FastAdapter<Item> withAttachDefaultListeners(boolean mAttachDefaultListeners) {
this.mAttachDefaultListeners = mAttachDefaultListeners;
return this;
}
/**
* set a listener that get's notified whenever an item is selected or deselected
*
* @param selectionListener the listener that will be notified about selection changes
* @return this
*/
public FastAdapter<Item> withSelectionListener(ISelectionListener<Item> selectionListener) {
mSelectExtension.withSelectionListener(selectionListener);
return this;
}
/**
* @return if items are selectable
*/
public boolean isSelectable() {
return mSelectExtension.isSelectable();
}
/**
* re-selects all elements stored in the savedInstanceState
* IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items!
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @return this
*/
public FastAdapter<Item> withSavedInstanceState(Bundle savedInstanceState) {
return withSavedInstanceState(savedInstanceState, "");
}
/**
* re-selects all elements stored in the savedInstanceState
* IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items!
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @param prefix a prefix added to the savedInstance key so we can store multiple states
* @return this
*/
public FastAdapter<Item> withSavedInstanceState(@Nullable Bundle savedInstanceState, String prefix) {
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.withSavedInstanceState(savedInstanceState, prefix);
}
return this;
}
/**
* register a new type into the TypeInstances to be able to efficiently create thew ViewHolders
*
* @param item an IItem which will be shown in the list
*/
@SuppressWarnings("unchecked")
public void registerTypeInstance(Item item) {
if (getTypeInstanceCache().register(item)) {
//check if the item implements hookable when its added for the first time
if (item instanceof IHookable) {
withEventHooks(((IHookable<Item>) item).getEventHooks());
}
}
}
/**
* gets the TypeInstance remembered within the FastAdapter for an item
*
* @param type the int type of the item
* @return the Item typeInstance
*/
public Item getTypeInstance(int type) {
return getTypeInstanceCache().get(type);
}
/**
* clears the internal mapper - be sure, to remap everything before going on
*/
public void clearTypeInstance() {
getTypeInstanceCache().clear();
}
/**
* helper method to get the position from a holder
* overwrite this if you have an adapter adding additional items inbetwean
*
* @param holder the viewHolder of the item
* @return the position of the holder
*/
public int getHolderAdapterPosition(@NonNull RecyclerView.ViewHolder holder) {
return holder.getAdapterPosition();
}
/**
* the ClickEventHook to hook onto the itemView of a viewholder
*/
private ClickEventHook<Item> fastAdapterViewClickListener = new ClickEventHook<Item>() {
@Override
public void onClick(View v, int pos, FastAdapter<Item> fastAdapter, Item item) {
IAdapter<Item> adapter = fastAdapter.getAdapter(pos);
if (adapter != null && item != null && item.isEnabled()) {
boolean consumed = false;
//on the very first we call the click listener from the item itself (if defined)
if (item instanceof IClickable && ((IClickable) item).getOnPreItemClickListener() != null) {
consumed = ((IClickable<Item>) item).getOnPreItemClickListener().onClick(v, adapter, item, pos);
}
//first call the onPreClickListener which would allow to prevent executing of any following code, including selection
if (!consumed && fastAdapter.mOnPreClickListener != null) {
consumed = fastAdapter.mOnPreClickListener.onClick(v, adapter, item, pos);
}
// handle our extensions
for (IAdapterExtension<Item> ext : fastAdapter.mExtensions.values()) {
if (!consumed) {
consumed = ext.onClick(v, pos, fastAdapter, item);
} else {
break;
}
}
//before calling the global adapter onClick listener call the item specific onClickListener
if (!consumed && item instanceof IClickable && ((IClickable) item).getOnItemClickListener() != null) {
consumed = ((IClickable<Item>) item).getOnItemClickListener().onClick(v, adapter, item, pos);
}
//call the normal click listener after selection was handlded
if (!consumed && fastAdapter.mOnClickListener != null) {
fastAdapter.mOnClickListener.onClick(v, adapter, item, pos);
}
}
}
};
/**
* the LongClickEventHook to hook onto the itemView of a viewholder
*/
private LongClickEventHook<Item> fastAdapterViewLongClickListener = new LongClickEventHook<Item>() {
@Override
public boolean onLongClick(View v, int pos, FastAdapter<Item> fastAdapter, Item item) {
boolean consumed = false;
IAdapter<Item> adapter = fastAdapter.getAdapter(pos);
if (adapter != null && item != null && item.isEnabled()) {
//first call the OnPreLongClickListener which would allow to prevent executing of any following code, including selection
if (fastAdapter.mOnPreLongClickListener != null) {
consumed = fastAdapter.mOnPreLongClickListener.onLongClick(v, adapter, item, pos);
}
// handle our extensions
for (IAdapterExtension<Item> ext : fastAdapter.mExtensions.values()) {
if (!consumed) {
consumed = ext.onLongClick(v, pos, fastAdapter, item);
} else {
break;
}
}
//call the normal long click listener after selection was handled
if (!consumed && fastAdapter.mOnLongClickListener != null) {
consumed = fastAdapter.mOnLongClickListener.onLongClick(v, adapter, item, pos);
}
}
return consumed;
}
};
/**
* the TouchEventHook to hook onto the itemView of a viewholder
*/
private TouchEventHook<Item> fastAdapterViewTouchListener = new TouchEventHook<Item>() {
@Override
public boolean onTouch(View v, MotionEvent event, int position, FastAdapter<Item> fastAdapter, Item item) {
boolean consumed = false;
// handle our extensions
for (IAdapterExtension<Item> ext : fastAdapter.mExtensions.values()) {
if (!consumed) {
consumed = ext.onTouch(v, event, position, fastAdapter, item);
} else {
break;
}
}
if (fastAdapter.mOnTouchListener != null) {
IAdapter<Item> adapter = fastAdapter.getAdapter(position);
if (adapter != null) {
return fastAdapter.mOnTouchListener.onTouch(v, event, adapter, item, position);
}
}
return consumed;
}
};
/**
* Creates the ViewHolder by the viewType
*
* @param parent the parent view (the RecyclerView)
* @param viewType the current viewType which is bound
* @return the ViewHolder with the bound data
*/
@Override
@SuppressWarnings("unchecked")
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mVerbose) Log.v(TAG, "onCreateViewHolder: " + viewType);
final RecyclerView.ViewHolder holder = mOnCreateViewHolderListener.onPreCreateViewHolder(this, parent, viewType);
//set the adapter
holder.itemView.setTag(R.id.fastadapter_item_adapter, FastAdapter.this);
if (mAttachDefaultListeners) {
//handle click behavior
EventHookUtil.attachToView(fastAdapterViewClickListener, holder, holder.itemView);
//handle long click behavior
EventHookUtil.attachToView(fastAdapterViewLongClickListener, holder, holder.itemView);
//handle touch behavior
EventHookUtil.attachToView(fastAdapterViewTouchListener, holder, holder.itemView);
}
return mOnCreateViewHolderListener.onPostCreateViewHolder(this, holder);
}
/**
* Binds the data to the created ViewHolder and sets the listeners to the holder.itemView
* Note that you should use the `onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads`
* as it allows you to implement a more efficient adapter implementation
*
* @param holder the viewHolder we bind the data on
* @param position the global position
*/
@Override
@SuppressWarnings("unchecked")
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (mLegacyBindViewMode) {
if (mVerbose) {
Log.v(TAG, "onBindViewHolderLegacy: " + position + "/" + holder.getItemViewType() + " isLegacy: true");
}
//set the R.id.fastadapter_item_adapter tag to the adapter so we always have the proper bound adapter available
holder.itemView.setTag(R.id.fastadapter_item_adapter, this);
//now we bind the item to this viewHolder
mOnBindViewHolderListener.onBindViewHolder(holder, position, Collections.EMPTY_LIST);
}
}
/**
* Binds the data to the created ViewHolder and sets the listeners to the holder.itemView
*
* @param holder the viewHolder we bind the data on
* @param position the global position
* @param payloads the payloads for the bindViewHolder event containing data which allows to improve view animating
*/
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List<Object> payloads) {
//we do not want the binding to happen twice (the legacyBindViewMode
if (!mLegacyBindViewMode) {
if (mVerbose)
Log.v(TAG, "onBindViewHolder: " + position + "/" + holder.getItemViewType() + " isLegacy: false");
//set the R.id.fastadapter_item_adapter tag to the adapter so we always have the proper bound adapter available
holder.itemView.setTag(R.id.fastadapter_item_adapter, this);
//now we bind the item to this viewHolder
mOnBindViewHolderListener.onBindViewHolder(holder, position, payloads);
}
super.onBindViewHolder(holder, position, payloads);
}
/**
* Unbinds the data to the already existing ViewHolder and removes the listeners from the holder.itemView
*
* @param holder the viewHolder we unbind the data from
*/
@Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
if (mVerbose) Log.v(TAG, "onViewRecycled: " + holder.getItemViewType());
super.onViewRecycled(holder);
mOnBindViewHolderListener.unBindViewHolder(holder, holder.getAdapterPosition());
}
/**
* is called in onViewDetachedFromWindow when the view is detached from the window
*
* @param holder the viewHolder for the view which got detached
*/
@Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
if (mVerbose) Log.v(TAG, "onViewDetachedFromWindow: " + holder.getItemViewType());
super.onViewDetachedFromWindow(holder);
mOnBindViewHolderListener.onViewDetachedFromWindow(holder, holder.getAdapterPosition());
}
/**
* is called in onViewAttachedToWindow when the view is detached from the window
*
* @param holder the viewHolder for the view which got detached
*/
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
if (mVerbose) Log.v(TAG, "onViewAttachedToWindow: " + holder.getItemViewType());
super.onViewAttachedToWindow(holder);
mOnBindViewHolderListener.onViewAttachedToWindow(holder, holder.getAdapterPosition());
}
/**
* is called when the ViewHolder is in a transient state. return true if you want to reuse
* that view anyways
*
* @param holder the viewHolder for the view which failed to recycle
* @return true if we want to recycle anyways (false - it get's destroyed)
*/
@Override
public boolean onFailedToRecycleView(RecyclerView.ViewHolder holder) {
if (mVerbose) Log.v(TAG, "onFailedToRecycleView: " + holder.getItemViewType());
return mOnBindViewHolderListener.onFailedToRecycleView(holder, holder.getAdapterPosition()) || super.onFailedToRecycleView(holder);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
if (mVerbose) Log.v(TAG, "onAttachedToRecyclerView");
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
if (mVerbose) Log.v(TAG, "onDetachedFromRecyclerView");
super.onDetachedFromRecyclerView(recyclerView);
}
/**
* Searches for the given item and calculates its global position
*
* @param item the item which is searched for
* @return the global position, or -1 if not found
*/
public int getPosition(Item item) {
if (item.getIdentifier() == -1) {
Log.e("FastAdapter", "You have to define an identifier for your item to retrieve the position via this method");
return -1;
}
return getPosition(item.getIdentifier());
}
/**
* Searches for the given item and calculates its global position
*
* @param identifier the identifier of an item which is searched for
* @return the global position, or -1 if not found
*/
public int getPosition(long identifier) {
int position = 0;
for (IAdapter<Item> adapter : mAdapters) {
if (adapter.getOrder() < 0) {
continue;
}
int relativePosition = adapter.getAdapterPosition(identifier);
if (relativePosition != -1) {
return position + relativePosition;
}
position = adapter.getAdapterItemCount();
}
return -1;
}
/**
* gets the IItem by a position, from all registered adapters
*
* @param position the global position
* @return the found IItem or null
*/
public Item getItem(int position) {
//if we are out of range just return null
if (position < 0 || position >= mGlobalSize) {
return null;
}
//now get the adapter which is responsible for the given position
int index = floorIndex(mAdapterSizes, position);
return mAdapterSizes.valueAt(index).getAdapterItem(position - mAdapterSizes.keyAt(index));
}
/**
* gets the IItem given an identifier, from all registered adapters
*
* @param identifier the identifier of the searched item
* @return the found Pair<IItem, Integer> (the found item, and it's global position if it is currently displayed) or null
*/
@SuppressWarnings("unchecked")
public Pair<Item, Integer> getItemById(final long identifier) {
if (identifier == -1) {
return null;
}
Triple result = recursive(new AdapterPredicate() {
@Override
public boolean apply(@NonNull IAdapter lastParentAdapter, int lastParentPosition, @NonNull IItem item, int position) {
return item.getIdentifier() == identifier;
}
}, true);
if (result.second == null) {
return null;
} else {
return new Pair(result.second, result.third);
}
}
/**
* Internal method to get the Item as ItemHolder which comes with the relative position within its adapter
* Finds the responsible adapter for the given position
*
* @param position the global position
* @return the adapter which is responsible for this position
*/
public RelativeInfo<Item> getRelativeInfo(int position) {
if (position < 0 || position >= getItemCount()) {
return new RelativeInfo<>();
}
RelativeInfo<Item> relativeInfo = new RelativeInfo<>();
int index = floorIndex(mAdapterSizes, position);
if (index != -1) {
relativeInfo.item = mAdapterSizes.valueAt(index).getAdapterItem(position - mAdapterSizes.keyAt(index));
relativeInfo.adapter = mAdapterSizes.valueAt(index);
relativeInfo.position = position;
}
return relativeInfo;
}
/**
* Gets the adapter for the given position
*
* @param position the global position
* @return the adapter responsible for this global position
*/
@Nullable
public IAdapter<Item> getAdapter(int position) {
//if we are out of range just return null
if (position < 0 || position >= mGlobalSize) {
return null;
}
if (mVerbose) Log.v(TAG, "getAdapter");
//now get the adapter which is responsible for the given position
return mAdapterSizes.valueAt(floorIndex(mAdapterSizes, position));
}
/**
* finds the int ItemViewType from the IItem which exists at the given position
*
* @param position the global position
* @return the viewType for this position
*/
@Override
public int getItemViewType(int position) {
return getItem(position).getType();
}
/**
* finds the int ItemId from the IItem which exists at the given position
*
* @param position the global position
* @return the itemId for this position
*/
@Override
public long getItemId(int position) {
return getItem(position).getIdentifier();
}
/**
* calculates the total ItemCount over all registered adapters
*
* @return the global count
*/
public int getItemCount() {
return mGlobalSize;
}
/**
* calculates the item count up to a given (excluding this) order number
*
* @param order the number up to which the items are counted
* @return the total count of items up to the adapter order
*/
public int getPreItemCountByOrder(int order) {
//if we are empty just return 0 count
if (mGlobalSize == 0) {
return 0;
}
int size = 0;
//count the number of items before the adapter with the given order
for (int i = 0; i < Math.min(order, mAdapters.size()); i++) {
size = size + mAdapters.get(i).getAdapterItemCount();
}
//get the count of items which are before this order
return size;
}
/**
* calculates the item count up to a given (excluding this) adapter (defined by the global position of the item)
*
* @param position the global position of an adapter item
* @return the total count of items up to the adapter which holds the given position
*/
public int getPreItemCount(int position) {
//if we are empty just return 0 count
if (mGlobalSize == 0) {
return 0;
}
//get the count of items which are before this order
return mAdapterSizes.keyAt(floorIndex(mAdapterSizes, position));
}
/**
* add the values to the bundle for saveInstanceState
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @return the passed bundle with the newly added data
*/
public Bundle saveInstanceState(@Nullable Bundle savedInstanceState) {
return saveInstanceState(savedInstanceState, "");
}
/**
* add the values to the bundle for saveInstanceState
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @param prefix a prefix added to the savedInstance key so we can store multiple states
* @return the passed bundle with the newly added data
*/
public Bundle saveInstanceState(@Nullable Bundle savedInstanceState, String prefix) {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.saveInstanceState(savedInstanceState, prefix);
}
return savedInstanceState;
}
/**
* we cache the sizes of our adapters so get accesses are faster
*/
protected void cacheSizes() {
mAdapterSizes.clear();
int size = 0;
for (IAdapter<Item> adapter : mAdapters) {
if (adapter.getAdapterItemCount() > 0) {
mAdapterSizes.append(size, adapter);
size = size + adapter.getAdapterItemCount();
}
}
//we also have to add this for the first adapter otherwise the floorIndex method will return the wrong value
if (size == 0 && mAdapters.size() > 0) {
mAdapterSizes.append(0, mAdapters.get(0));
}
mGlobalSize = size;
}
//Convenient getters
/**
* @return the `ClickEventHook` which is attached by default (if not deactivated) via `withAttachDefaultListeners`
* @see #withAttachDefaultListeners(boolean)
*/
public ClickEventHook<Item> getViewClickListener() {
return fastAdapterViewClickListener;
}
/**
* @return the `LongClickEventHook` which is attached by default (if not deactivated) via `withAttachDefaultListeners`
* @see #withAttachDefaultListeners(boolean)
*/
public LongClickEventHook<Item> getViewLongClickListener() {
return fastAdapterViewLongClickListener;
}
/**
* @return the `TouchEventHook` which is attached by default (if not deactivated) via `withAttachDefaultListeners`
* @see #withAttachDefaultListeners(boolean)
*/
public TouchEventHook<Item> getViewTouchListener() {
return fastAdapterViewTouchListener;
}
//Selection stuff
/**
* @return the selectExtension defined for this FastAdaper
* @deprecated deprecated in favor of {@link #getExtension(Class)}
*/
@Deprecated
public SelectExtension<Item> getSelectExtension() {
return mSelectExtension;
}
/**
* @return a set with the global positions of all selected items
* @deprecated deprecated in favor of {@link SelectExtension#getSelections()} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public Set<Integer> getSelections() {
return mSelectExtension.getSelections();
}
/**
* @return a set with the items which are currently selected
* @deprecated deprecated in favor of {@link SelectExtension#getSelectedItems()} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public Set<Item> getSelectedItems() {
return mSelectExtension.getSelectedItems();
}
/**
* toggles the selection of the item at the given position
*
* @param position the global position
* @deprecated deprecated in favor of {@link SelectExtension#toggleSelection(int)} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void toggleSelection(int position) {
mSelectExtension.toggleSelection(position);
}
/**
* selects all items at the positions in the iteratable
*
* @param positions the global positions to select
* @deprecated deprecated in favor of {@link SelectExtension#select(Iterable)} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void select(Iterable<Integer> positions) {
mSelectExtension.select(positions);
}
/**
* selects an item and remembers its position in the selections list
*
* @param position the global position
* @deprecated deprecated in favor of {@link SelectExtension#select(int)}, Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void select(int position) {
mSelectExtension.select(position, false, false);
}
/**
* selects an item and remembers its position in the selections list
*
* @param position the global position
* @param fireEvent true if the onClick listener should be called
* @deprecated deprecated in favor of {@link SelectExtension#select(int, boolean)} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void select(int position, boolean fireEvent) {
mSelectExtension.select(position, fireEvent, false);
}
/**
* selects an item and remembers its position in the selections list
*
* @param position the global position
* @param fireEvent true if the onClick listener should be called
* @param considerSelectableFlag true if the select method should not select an item if its not selectable
* @deprecated deprecated in favor of {@link SelectExtension#select(int, boolean, boolean)} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void select(int position, boolean fireEvent, boolean considerSelectableFlag) {
mSelectExtension.select(position, fireEvent, considerSelectableFlag);
}
/**
* deselects all selections
*
* @deprecated deprecated in favor of {@link SelectExtension#deselect()} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void deselect() {
mSelectExtension.deselect();
}
/**
* select all items
*
* @deprecated deprecated in favor of {@link SelectExtension#select()} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void select() {
mSelectExtension.select(false);
}
/**
* select all items
*
* @param considerSelectableFlag true if the select method should not select an item if its not selectable
* @deprecated deprecated in favor of {@link SelectExtension#select(boolean)} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void select(boolean considerSelectableFlag) {
mSelectExtension.select(considerSelectableFlag);
}
/**
* deselects all items at the positions in the iteratable
*
* @param positions the global positions to deselect
* @deprecated deprecated in favor of {@link SelectExtension#deselect(Iterable)} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void deselect(Iterable<Integer> positions) {
mSelectExtension.deselect(positions);
}
/**
* deselects an item and removes its position in the selections list
*
* @param position the global position
* @deprecated deprecated in favor of {@link SelectExtension#deselect(int)} , Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void deselect(int position) {
mSelectExtension.deselect(position);
}
/**
* deselects an item and removes its position in the selections list
* also takes an iterator to remove items from the map
*
* @param position the global position
* @param entries the iterator which is used to deselect all
* @deprecated deprecated in favor of {@link SelectExtension#deselect(int, Iterator)}, Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public void deselect(int position, Iterator<Integer> entries) {
mSelectExtension.deselect(position, entries);
}
/**
* deletes all current selected items
*
* @return a list of the IItem elements which were deleted
* @deprecated deprecated in favor of {@link SelectExtension#deleteAllSelectedItems()}, Retrieve it via {@link #getExtension(Class)}
*/
@Deprecated
public List<Item> deleteAllSelectedItems() {
return mSelectExtension.deleteAllSelectedItems();
}
//wrap the notify* methods so we can have our required selection adjustment code
/**
* wraps notifyDataSetChanged
*/
public void notifyAdapterDataSetChanged() {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.notifyAdapterDataSetChanged();
}
cacheSizes();
notifyDataSetChanged();
}
/**
* wraps notifyItemInserted
*
* @param position the global position
*/
public void notifyAdapterItemInserted(int position) {
notifyAdapterItemRangeInserted(position, 1);
}
/**
* wraps notifyItemRangeInserted
*
* @param position the global position
* @param itemCount the count of items inserted
*/
public void notifyAdapterItemRangeInserted(int position, int itemCount) {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.notifyAdapterItemRangeInserted(position, itemCount);
}
cacheSizes();
notifyItemRangeInserted(position, itemCount);
}
/**
* wraps notifyItemRemoved
*
* @param position the global position
*/
public void notifyAdapterItemRemoved(int position) {
notifyAdapterItemRangeRemoved(position, 1);
}
/**
* wraps notifyItemRangeRemoved
*
* @param position the global position
* @param itemCount the count of items removed
*/
public void notifyAdapterItemRangeRemoved(int position, int itemCount) {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.notifyAdapterItemRangeRemoved(position, itemCount);
}
cacheSizes();
notifyItemRangeRemoved(position, itemCount);
}
/**
* wraps notifyItemMoved
*
* @param fromPosition the global fromPosition
* @param toPosition the global toPosition
*/
public void notifyAdapterItemMoved(int fromPosition, int toPosition) {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.notifyAdapterItemMoved(fromPosition, toPosition);
}
notifyItemMoved(fromPosition, toPosition);
}
/**
* wraps notifyItemChanged
*
* @param position the global position
*/
public void notifyAdapterItemChanged(int position) {
notifyAdapterItemChanged(position, null);
}
/**
* wraps notifyItemChanged
*
* @param position the global position
* @param payload additional payload
*/
public void notifyAdapterItemChanged(int position, @Nullable Object payload) {
notifyAdapterItemRangeChanged(position, 1, payload);
}
/**
* wraps notifyItemRangeChanged
*
* @param position the global position
* @param itemCount the count of items changed
*/
public void notifyAdapterItemRangeChanged(int position, int itemCount) {
notifyAdapterItemRangeChanged(position, itemCount, null);
}
/**
* wraps notifyItemRangeChanged
*
* @param position the global position
* @param itemCount the count of items changed
* @param payload an additional payload
*/
public void notifyAdapterItemRangeChanged(int position, int itemCount, @Nullable Object payload) {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.notifyAdapterItemRangeChanged(position, itemCount, payload);
}
if (payload == null) {
notifyItemRangeChanged(position, itemCount);
} else {
notifyItemRangeChanged(position, itemCount, payload);
}
}
/**
* convenient helper method to get the Item from a holder
*
* @param holder the ViewHolder for which we want to retrieve the item
* @return the Item found for this ViewHolder
*/
@SuppressWarnings("unchecked")
public static <Item extends IItem> Item getHolderAdapterItem(@Nullable RecyclerView.ViewHolder holder) {
if (holder != null) {
Object tag = holder.itemView.getTag(com.mikepenz.fastadapter.R.id.fastadapter_item_adapter);
if (tag instanceof FastAdapter) {
FastAdapter fastAdapter = ((FastAdapter) tag);
int pos = fastAdapter.getHolderAdapterPosition(holder);
if (pos != RecyclerView.NO_POSITION) {
return (Item) fastAdapter.getItem(pos);
}
}
}
return null;
}
/**
* convenient helper method to get the Item from a holder
*
* @param holder the ViewHolder for which we want to retrieve the item
* @param position the position for which we want to retrieve the item
* @return the Item found for the given position and that ViewHolder
*/
@SuppressWarnings("unchecked")
public static <Item extends IItem> Item getHolderAdapterItem(@Nullable RecyclerView.ViewHolder holder, int position) {
if (holder != null) {
Object tag = holder.itemView.getTag(com.mikepenz.fastadapter.R.id.fastadapter_item_adapter);
if (tag instanceof FastAdapter) {
return (Item) ((FastAdapter) tag).getItem(position);
}
}
return null;
}
/**
* convenient helper method to get the Item from a holder via the defined tag
*
* @param holder the ViewHolder for which we want to retrieve the item
* @return the Item found for the given position and that ViewHolder
*/
@SuppressWarnings("unchecked")
public static <Item extends IItem> Item getHolderAdapterItemTag(@Nullable RecyclerView.ViewHolder holder) {
if (holder != null) {
Object item = holder.itemView.getTag(com.mikepenz.fastadapter.R.id.fastadapter_item);
if (item instanceof IItem) {
return (Item) item;
}
}
return null;
}
/**
* util function which recursively iterates over all items and subItems of the given adapter.
* It executes the given `predicate` on every item and will either stop if that function returns true, or continue (if stopOnMatch is false)
*
* @param predicate the predicate to run on every item, to check for a match or do some changes (e.g. select)
* @param stopOnMatch defines if we should stop iterating after the first match
* @return Triple<Boolean, IItem, Integer> The first value is true (it is always not null), the second contains the item and the third the position (if the item is visible) if we had a match, (always false and null and null in case of stopOnMatch == false)
*/
@NonNull
public Triple<Boolean, Item, Integer> recursive(AdapterPredicate<Item> predicate, boolean stopOnMatch) {
return recursive(predicate, 0, stopOnMatch);
}
/**
* util function which recursively iterates over all items and subItems of the given adapter.
* It executes the given `predicate` on every item and will either stop if that function returns true, or continue (if stopOnMatch is false)
*
* @param predicate the predicate to run on every item, to check for a match or do some changes (e.g. select)
* @param globalStartPosition the start position at which we star tto recursively iterate over the items. (This will not stop at the end of a sub hierarchy!)
* @param stopOnMatch defines if we should stop iterating after the first match
* @return Triple<Boolean, IItem, Integer> The first value is true (it is always not null), the second contains the item and the third the position (if the item is visible) if we had a match, (always false and null and null in case of stopOnMatch == false)
*/
@NonNull
public Triple<Boolean, Item, Integer> recursive(AdapterPredicate<Item> predicate, int globalStartPosition, boolean stopOnMatch) {
for (int i = globalStartPosition; i < getItemCount(); i++) {
//retrieve the item + it's adapter
RelativeInfo<Item> relativeInfo = getRelativeInfo(i);
Item item = relativeInfo.item;
if (predicate.apply(relativeInfo.adapter, i, item, i) && stopOnMatch) {
return new Triple<>(true, item, i);
}
if (item instanceof IExpandable) {
Triple<Boolean, Item, Integer> res = FastAdapter.recursiveSub(relativeInfo.adapter, i, (IExpandable) item, predicate, stopOnMatch);
if (res.first && stopOnMatch) {
return res;
}
}
}
return new Triple<>(false, null, null);
}
/**
* Util function which recursively iterates over all items of a `IExpandable` parent if and only if it is `expanded` and has `subItems`
* This is usually only used in
*
* @param lastParentAdapter the last `IAdapter` managing the last (visible) parent item (that might also be a parent of a parent, ..)
* @param lastParentPosition the global position of the last (visible) parent item, holding this sub item (that might also be a parent of a parent, ..)
* @param parent the `IExpandableParent` to start from
* @param predicate the predicate to run on every item, to check for a match or do some changes (e.g. select)
* @param stopOnMatch defines if we should stop iterating after the first match
* @param <Item> the type of the `Item`
* @return Triple<Boolean, IItem, Integer> The first value is true (it is always not null), the second contains the item and the third the position (if the item is visible) if we had a match, (always false and null and null in case of stopOnMatch == false)
*/
@SuppressWarnings("unchecked")
public static <Item extends IItem> Triple<Boolean, Item, Integer> recursiveSub(IAdapter<Item> lastParentAdapter, int lastParentPosition, IExpandable parent, AdapterPredicate<Item> predicate, boolean stopOnMatch) {
//in case it's expanded it can be selected via the normal way
if (!parent.isExpanded() && parent.getSubItems() != null) {
for (int ii = 0; ii < parent.getSubItems().size(); ii++) {
Item sub = (Item) parent.getSubItems().get(ii);
if (predicate.apply(lastParentAdapter, lastParentPosition, sub, -1) && stopOnMatch) {
return new Triple<>(true, sub, null);
}
if (sub instanceof IExpandable) {
Triple<Boolean, Item, Integer> res = FastAdapter.recursiveSub(lastParentAdapter, lastParentPosition, (IExpandable) sub, predicate, stopOnMatch);
if (res.first) {
return res;
}
}
}
}
return new Triple<>(false, null, null);
}
/**
* an internal class to return the IItem and relativePosition and its adapter at once. used to save one iteration inside the getInternalItem method
*/
public static class RelativeInfo<Item extends IItem> {
public IAdapter<Item> adapter = null;
public Item item = null;
public int position = -1;
}
/**
* A ViewHolder provided from the FastAdapter to allow handling the important event's within the ViewHolder
* instead of the item
*
* @param <Item>
*/
public static abstract class ViewHolder<Item extends IItem> extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
}
/**
* binds the data of this item onto the viewHolder
*/
public abstract void bindView(Item item, List<Object> payloads);
/**
* View needs to release resources when its recycled
*/
public abstract void unbindView(Item item);
/**
* View got attached to the window
*/
public void attachToWindow(Item item) {
}
/**
* View got detached from the window
*/
public void detachFromWindow(Item item) {
}
/**
* View is in a transient state and could not be recycled
*
* @return return true if you want to recycle anyways (after clearing animations or so)
*/
public boolean failedToRecycle(Item item) {
return false;
}
}
}
|
package me.shkschneider.skeleton.java;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import me.shkschneider.skeleton.helper.LogHelper;
public class ClassHelper {
protected ClassHelper() {
// Empty
}
@Nullable
public static Class<?> get(@NonNull final String cls) {
try {
return Class.forName(cls);
}
catch (final ClassNotFoundException e) {
LogHelper.wtf(e);
return null;
}
}
public static String canonicalName(@NonNull final Class<?> cls) {
return cls.getCanonicalName();
}
public static String packageName(@NonNull final Class<?> cls) {
return canonicalName(cls).replaceFirst("\\.[^\\.]+$", "");
}
public static String simpleName(@NonNull final Class<?> cls) {
return cls.getSimpleName();
}
}
|
package liquibase.datatype.core;
import liquibase.database.Database;
import liquibase.database.core.*;
import liquibase.datatype.DataTypeInfo;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;
@DataTypeInfo(name="number", aliases = {"numeric", "java.sql.Types.NUMERIC"}, minParameters = 0, maxParameters = 2, priority = LiquibaseDataType.PRIORITY_DEFAULT)
public class NumberType extends LiquibaseDataType {
private boolean autoIncrement;
public boolean isAutoIncrement() {
return autoIncrement;
}
public void setAutoIncrement(boolean autoIncrement) {
this.autoIncrement = autoIncrement;
}
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
if (database instanceof MySQLDatabase
|| database instanceof DB2Database
|| database instanceof MSSQLDatabase
|| database instanceof HsqlDatabase
|| database instanceof DerbyDatabase
|| database instanceof PostgresDatabase
|| database instanceof FirebirdDatabase
|| database instanceof SybaseASADatabase
|| database instanceof SybaseDatabase) {
return new DatabaseDataType("numeric", getParameters());
}
if (database instanceof OracleDatabase) {
if (getParameters().length > 1 && getParameters()[0].equals("0") && getParameters()[1].equals("-127")) {
return new DatabaseDataType("NUMBER");
} else {
return new DatabaseDataType("NUMBER", getParameters());
}
}
return super.toDatabaseDataType(database);
}
}
|
package dr.evomodel.coalescent.hmc;
import dr.evolution.coalescent.IntervalType;
import dr.evolution.coalescent.TreeIntervals;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evomodel.coalescent.GMRFMultilocusSkyrideLikelihood;
import dr.evomodel.tree.TreeModel;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.hmc.HessianWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.xml.Reportable;
import java.util.List;
/**
* @author Marc A. Suchard
* @author Mandev Gill
*/
public class GMRFGradient implements GradientWrtParameterProvider, HessianWrtParameterProvider, Reportable {
private final GMRFMultilocusSkyrideLikelihood skygridLikelihood;
private final WrtParameter wrtParameter;
private final Parameter parameter;
public GMRFGradient(GMRFMultilocusSkyrideLikelihood skygridLikelihood,
WrtParameter wrtParameter) {
this.skygridLikelihood = skygridLikelihood;
this.wrtParameter = wrtParameter;
parameter = wrtParameter.getParameter(skygridLikelihood);
}
@Override
public Likelihood getLikelihood() {
return skygridLikelihood;
}
@Override
public Parameter getParameter() {
return parameter;
}
@Override
public int getDimension() {
return parameter.getDimension();
}
@Override
public double[] getGradientLogDensity() {
return wrtParameter.getGradientLogDensity(skygridLikelihood);
}
@Override
public double[] getDiagonalHessianLogDensity() {
return wrtParameter.getDiagonalHessianLogDensity(skygridLikelihood);
}
@Override
public double[][] getHessianLogDensity() {
throw new RuntimeException("Not yet implemented");
}
@Override
public String getReport() {
String header = skygridLikelihood + "." + wrtParameter.name + "\n";
header += GradientWrtParameterProvider.getReportAndCheckForError(this,
wrtParameter.getParameterLowerBound(), Double.POSITIVE_INFINITY,
tolerance) + " \n";
header += HessianWrtParameterProvider.getReportAndCheckForError(this, tolerance);
return header;
}
public enum WrtParameter {
LOG_POPULATION_SIZES("logPopulationSizes") {
@Override
Parameter getParameter(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getPopSizeParameter();
}
@Override
double[] getGradientLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getGradientWrtLogPopulationSize();
}
@Override
double[] getDiagonalHessianLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getDiagonalHessianWrtLogPopulationSize();
}
@Override
double getParameterLowerBound() { return Double.NEGATIVE_INFINITY; }
@Override
public void getWarning(GMRFMultilocusSkyrideLikelihood likelihood) {
}
},
PRECISION("precision") {
@Override
Parameter getParameter(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getPrecisionParameter();
}
@Override
double[] getGradientLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getGradientWrtPrecision();
}
@Override
double[] getDiagonalHessianLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getDiagonalHessianWrtPrecision();
}
@Override
double getParameterLowerBound() { return 0.0; }
@Override
public void getWarning(GMRFMultilocusSkyrideLikelihood likelihood) {
}
},
REGRESSION_COEFFICIENTS("regressionCoefficients") {
@Override
Parameter getParameter(GMRFMultilocusSkyrideLikelihood likelihood) {
List<Parameter> allBetas = likelihood.getBetaListParameter();
if (allBetas.size() > 1) {
throw new RuntimeException("This is not the correct way of handling multidimensional parameters");
}
return allBetas.get(0);
}
@Override
double[] getGradientLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getGradientWrtRegressionCoefficients();
}
@Override
double[] getDiagonalHessianLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return likelihood.getDiagonalHessianWrtRegressionCoefficients();
}
@Override
double getParameterLowerBound() { return Double.NEGATIVE_INFINITY; }
@Override
public void getWarning(GMRFMultilocusSkyrideLikelihood likelihood) {
}
},
NODE_HEIGHT("nodeHeight") {
Parameter parameter;
@Override
Parameter getParameter(GMRFMultilocusSkyrideLikelihood likelihood) {
if (parameter == null) {
TreeModel treeModel = (TreeModel) likelihood.getTree(0);
parameter = treeModel.createNodeHeightsParameter(true, true, false);
}
return parameter;
}
@Override
double[] getGradientLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return getGradientWrtNodeHeights(likelihood);
}
@Override
double[] getDiagonalHessianLogDensity(GMRFMultilocusSkyrideLikelihood likelihood) {
return new double[likelihood.getTree(0).getInternalNodeCount()];
}
@Override
double getParameterLowerBound() {
return 0.0;
}
public void getWarning(GMRFMultilocusSkyrideLikelihood likelihood) {
if (likelihood.nLoci() > 1) {
throw new RuntimeException("Not yet implemented for multiple loci.");
}
}
private double[] getGradientWrtNodeHeights(GMRFMultilocusSkyrideLikelihood likelihood) {
likelihood.getLogLikelihood();
Tree tree = likelihood.getTree(0);
double[] gradient = new double[tree.getInternalNodeCount()];
double[] currentGamma = likelihood.getPopSizeParameter().getParameterValues();
double ploidyFactor = 1 / likelihood.getPopulationFactor(0);
final TreeIntervals intervals = likelihood.getTreeIntervals(0);
int[] gridIndices = getGridIndexForInternalNodes(likelihood, 0);
for (int i = 0; i < intervals.getIntervalCount(); i++) {
if (intervals.getIntervalType(i) == IntervalType.COALESCENT) {
final int nodeIndex = getNodeHeightParameterIndex(intervals.getCoalescentNode(i), tree);
final int numLineage = intervals.getLineageCount(i);
final double currentPopSize = Math.exp(-currentGamma[gridIndices[nodeIndex]]);
gradient[nodeIndex] += -currentPopSize * numLineage * (numLineage - 1);
if (!tree.isRoot(intervals.getCoalescentNode(i))) {
final int nextNumLineage = intervals.getLineageCount(i + 1);
gradient[nodeIndex] -= -currentPopSize * nextNumLineage * (nextNumLineage - 1);
}
}
}
final double multiplier = 0.5 * ploidyFactor;
for (int i = 0; i < gradient.length; i++) {
gradient[i] *= multiplier;
}
return gradient;
}
private int getNodeHeightParameterIndex(NodeRef node, Tree tree) {
return node.getNumber() - tree.getExternalNodeCount();
}
private int[] getGridIndexForInternalNodes(GMRFMultilocusSkyrideLikelihood likelihood, int treeIndex) {
Tree tree = likelihood.getTree(treeIndex);
TreeIntervals intervals = likelihood.getTreeIntervals(treeIndex);
int[] indices = new int[tree.getInternalNodeCount()];
int gridIndex = 0;
double[] gridPoints = likelihood.getGridPoints();
for (int i = 0; i < intervals.getIntervalCount(); i++) {
if (intervals.getIntervalType(i) == IntervalType.COALESCENT) {
while(gridPoints[gridIndex] < intervals.getInterval(i) && gridIndex < gridPoints.length - 1) {
gridIndex++;
}
indices[getNodeHeightParameterIndex(intervals.getCoalescentNode(i), tree)] = gridIndex;
}
}
return indices;
}
};
WrtParameter(String name) {
this.name = name;
}
abstract Parameter getParameter(GMRFMultilocusSkyrideLikelihood likelihood);
abstract double[] getGradientLogDensity(GMRFMultilocusSkyrideLikelihood likelihood);
abstract double[] getDiagonalHessianLogDensity(GMRFMultilocusSkyrideLikelihood likelihood);
abstract double getParameterLowerBound();
public abstract void getWarning(GMRFMultilocusSkyrideLikelihood likelihood);
private final String name;
public static WrtParameter factory(String match) {
for (WrtParameter type : WrtParameter.values()) {
if (match.equalsIgnoreCase(type.name)) {
return type;
}
}
return null;
}
}
private final static Double tolerance = 1E-4;
}
|
package dr.inference.model;
import dr.inference.loggers.LogColumn;
import dr.math.LogTricks;
import dr.xml.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Marc A. Suchard
* @author Andrew Rambaut
*/
public class WeightedMixtureModel extends AbstractModelLikelihood {
public static final String MIXTURE_MODEL = "mixtureModel";
// public static final String MIXTURE_WEIGHTS = "weights";
public static final String NORMALIZE = "normalize";
public WeightedMixtureModel(List<Likelihood> likelihoodList, Parameter mixtureWeights) {
super(MIXTURE_MODEL);
this.likelihoodList = likelihoodList;
this.mixtureWeights = mixtureWeights;
addVariable(mixtureWeights);
}
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
}
protected void storeState() {
}
protected void restoreState() {
}
protected void acceptState() {
}
public Model getModel() {
return this;
}
public double getLogLikelihood() {
double logSum = Double.NEGATIVE_INFINITY;
for (int i = 0; i < likelihoodList.size(); ++i) {
double pi = mixtureWeights.getParameterValue(i);
if (pi > 0.0) {
logSum = LogTricks.logSum(logSum,
Math.log(pi) + likelihoodList.get(i).getLogLikelihood());
}
}
return logSum;
}
public void makeDirty() {
}
public LogColumn[] getColumns() {
return new LogColumn[0];
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return MIXTURE_MODEL;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Parameter weights = (Parameter) xo.getChild(Parameter.class);
List<Likelihood> likelihoodList = new ArrayList<Likelihood>();
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof Likelihood)
likelihoodList.add((Likelihood) xo.getChild(i));
}
if (weights.getDimension() != likelihoodList.size()) {
throw new XMLParseException("Dim of " + weights.getId() + " does not match the number of likelihoods");
}
if (xo.hasAttribute(NORMALIZE)) {
if (xo.getBooleanAttribute(NORMALIZE)) {
double sum = 0;
for (int i = 0; i < weights.getDimension(); i++)
sum += weights.getParameterValue(i);
for (int i = 0; i < weights.getDimension(); i++)
weights.setParameterValue(i, weights.getParameterValue(i) / sum);
}
}
if (!normalized(weights))
throw new XMLParseException("Parameter +" + weights.getId() + " must lie on the simplex");
return new WeightedMixtureModel(likelihoodList, weights);
}
private boolean normalized(Parameter p) {
double sum = 0;
for (int i = 0; i < p.getDimension(); i++)
sum += p.getParameterValue(i);
return (sum == 1.0);
}
|
/**
* Client is a chat client for the accompanying server.
* It gets the hostname and port to connect to from the user, and then acts
* as a GUI frontend to some sockets.
*/
// For networking
import java.net.*;
import java.io.*;
import java.util.*;
// For GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Client extends JFrame implements ActionListener
{
// IO elements that need to be accessed in several methods
private static JTextArea display;
private static JTextField input;
private static PrintWriter outs;
// Plays sound effects for client events
private static SoundPlayer sounds;
// This is the window where the user enters port number and hostname
private static ClientSetup setup;
// This is true when we're ready to read / write data to the network
private static boolean initialized = false;
// Sets up the GUI elements, called once during setup
public Client(String host)
{
setTitle("Chat Client");
setSize(340, 220);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sounds = new SoundPlayer();
display = new JTextArea("Connecting to host: " + host);
display.setLineWrap(true);
JScrollPane scroll = new JScrollPane(display);
input = new JTextField();
input.addActionListener(this);
display.setEditable(false);
this.setLayout(new BorderLayout());
this.add(scroll, BorderLayout.CENTER); // Center makes it use all space
this.add(input, BorderLayout.SOUTH);
}
// This is called whenever the user presses return in the input box
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if( !source.equals(input) || initialized == false )
return;
String text = input.getText().trim(); // Get the text user has entered
input.setText(new String("")); // Clear text box
if( text.length() > 0 )
outs.println(text); // Send text across the network
}
// This is called to connect to a server and read from the socket
private void connectToServer( InetAddress host, int port )
{
try
{
// Open the socket and set up some handles for it
Socket sock = new Socket(host, port);
InputStream in = sock.getInputStream();
OutputStream out = sock.getOutputStream();
InputStreamReader ins = new InputStreamReader(in);
outs = new PrintWriter(out, true);
// Now ready to read and write data
initialized = true;
// Read from socket and print to GUI, until socket closes
while(true)
{
try
{
int recv = ins.read();
if( recv == -1 ) // If EOF
break;
String line = Character.toString((char)recv);
display.append(line);
display.selectAll();
int x = display.getSelectionEnd();
display.select(x,x);
if( !isActive() || !isFocused() )
sounds.play("new message");
}
catch(IOException e)
{
display.append("Error reading from socket: " +
e.getMessage() + "\n");
display.selectAll();
int x = display.getSelectionEnd();
display.select(x,x);
break; // If a socket is suddenly terminated we need to end
}
}
// Now clean up
display.append("
initialized = false;
sock.close();
}
catch( IOException e )
{
display.append("Something went wrong in setup: " +
e.getMessage());
}
}
public static void main( String [] args ) throws IOException
{
// Default values, we will not create
InetAddress host = null;
int port = 0;
// Set up UI for getting the host / port number
ClientSetup setup = new ClientSetup();
setup.setVisible(true);
// Get valid input from user
boolean validHost = false;
while( !validHost )
{
String [] address = setup.getAddress();
try
{
host = InetAddress.getByName(address[0]);
port = Integer.parseInt(address[1]);
if( port != 0 )
{
validHost = true;
setup.dispose();
}
}
catch(Exception e) // Something went wrong, their input is botched
{
JOptionPane.showMessageDialog(null,
"Please provide a valid hostname and port",
"Invalid Input",
JOptionPane.ERROR_MESSAGE);
validHost = false;
}
}
// This should always be true, but Java wants to be sure the vars
// are initialized
if( host != null && port != 0 )
{
// Set up the chat GUI
Client c = new Client(host.getHostName() + ":" + port + "\n");
c.setVisible(true);
c.connectToServer(host, port);
}
}
}
|
package de.doe;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
public class MoveGeneratorTest {
@Test
public void generateAllPawnMovesAndCheckSize() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", "..P..", ".....", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(1, moves.size());
}
@Test
public void generateAndCheckAllPawnMoves() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", "..P..", ".....", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(1, moves.size());
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 3)));
}
@Test
public void generateAllRookMovesAndCheckSize() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", "..R..", ".....", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(9, moves.size());
}
@Test
public void generateAndCheckAllRookMoves() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..R..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
// TODO vielleicht noch mal berlegen ob es sinnvoll ist
assertEquals(9, moves.size());
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 5)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 0)));
}
@Test
public void generateAllKnightMovesAndCheckSize() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..N..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(8, moves.size());
}
@Test
public void generateAndCheckAllKnightMoves() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..N..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(8, moves.size());
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 0)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 0)));
}
@Test
public void generateAllBishopMovesAndCheckSize() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..B..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(12, moves.size());
}
@Test
public void generateAndCheckAllBishopMoves() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..B..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(12, moves.size());
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 0)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 0)));
}
@Test
public void generateAllQueensMovesAndCheckSize() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..Q..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(17, moves.size());
}
@Test
public void generateAndCheckAllQueensMoves() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..Q..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(17, moves.size());
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 5)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 4)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 0, 0)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 0)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 4, 0)));
}
@Test
public void generateAllKingsMovesAndCheckSize() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..K..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(8, moves.size());
}
@Test
public void generateAndCheckAllKingsMoves() throws Exception {
Board board = new Board(TestUtils.getMultilineString("1 W", ".....", ".....", "..K..", ".....", "....."));
MoveGenerator generator = new MoveGenerator(board);
List<Move> moves = generator.getAllMoves();
assertEquals(8, moves.size());
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 3)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 2)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 1, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 2, 1)));
assertTrue(moves.contains(new Move(Player.WHITE, 2, 2, 3, 1)));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package maze;
import java.awt.Point;
/**
*
* @author Nels
*/
public class Block {
public int blockID;
public boolean visited;
public boolean legal;
public Point position;
public Block(){
blockID = 0;
visited = false;
legal = false;
}
public Block ( int xPosition, int yPosition, int blockID){
this.blockID = blockID;
visited = false;
legal = false;
this.position.x = xPosition;
this.position.y = yPosition;
}
}
|
import java.awt.Dimension;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import com.mpcmaid.gui.BaseFrame;
import com.mpcmaid.gui.MainFrame;
import com.mpcmaid.gui.Preferences;
/**
* Dummy main class with short name
*
* @author cyrille martraire
*/
public final class MPCMaid {
// splash screen
private static JWindow screen = null;
public static void showSplash() {
screen = new JWindow();
final URL resource = MainFrame.class.getResource("mpcmaidlogo400_400.png");
final JLabel label = new JLabel(new ImageIcon(resource));
screen.getContentPane().add(label);
screen.setLocationRelativeTo(null);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = screen.getPreferredSize();
screen
.setLocation(screenSize.width / 2 - (labelSize.width / 2), screenSize.height / 2
- (labelSize.height / 2));
screen.pack();
screen.setVisible(true);
label.repaint();
screen.repaint();
}
public static void hideSplash() {
if (screen == null) {
return;
}
screen.setVisible(false);
screen.dispose();
screen = null;
}
public static void main(String[] args) {
makeAsNativeAsPossible();
showSplash();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final BaseFrame baseFrame = new MainFrame();
// wait to show the splash
if (screen != null) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//baseFrame.setVisible(true);
baseFrame.show();
hideSplash();
}
});
}
public static final boolean isMacOsX() {
return System.getProperty("mrj.version") != null;
}
public static final void makeAsNativeAsPossible() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
try {
if (isMacOsX()) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "MPC Maid");
}
} catch (Exception e) {
}
try {
Preferences.getInstance().load();
} catch (Exception ignore) {
}
}
public String toString() {
return "MPCMaid";
}
}
|
package controllers;
import dao.ProfileDAO;
import models.Profile;
import view.SettingsView;
import com.fasterxml.jackson.databind.JsonNode;
import play.Logger;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security.Authenticated;
/**
* This is the controller class for the settings
*
* @author fabiomazzone
*/
@Authenticated(secured.UserSecured.class)
public class SettingsController extends Controller {
/**
* GET /profile/settings
*
* @return returns the Player Settings as JSON Object
*/
public Result index() {
Profile profile = ProfileDAO.getByUsername(request().username());
return ok(SettingsView.toJson(profile.settings));
}
/**
* POST /profile/settings
*
* @return returns a http responds code if the action was successfully or not
*/
public Result edit() {
Profile profile = ProfileDAO.getByUsername(request().username());
JsonNode json = request().body().asJson();
profile.setSettings(SettingsView.fromJson(json));
profile.update();
return redirect(routes.SettingsController.index());
}
}
|
package naftoreiclag.zingpower;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import naftoreiclag.zingpower.block.BlockCopperOre;
import naftoreiclag.zingpower.item.ItemCopperIngot;
import naftoreiclag.zingpower.util.MyStaticStrings;
import naftoreiclag.zingpower.world.WorldGenManager;
@Mod(modid = MyStaticStrings.MOD_ID, version = MyStaticStrings.MOD_VER)
public class ZingpowerMod
{
public static Block block_copperOre;
public static Item item_copperIngot;
WorldGenManager ev = new WorldGenManager();
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
block_copperOre = new BlockCopperOre();
GameRegistry.registerBlock(block_copperOre, block_copperOre.getUnlocalizedName());
OreDictionary.registerOre("oreCopper", block_copperOre);
item_copperIngot = new ItemCopperIngot();
GameRegistry.registerItem(item_copperIngot, item_copperIngot.getUnlocalizedName());
OreDictionary.registerOre("ingotCopper", item_copperIngot);
GameRegistry.registerWorldGenerator(ev, 1);
GameRegistry.addSmelting(block_copperOre, new ItemStack(item_copperIngot), 0.1f);
}
@EventHandler
public void init(FMLInitializationEvent event)
{
}
}
|
package net.hyperic.sigar;
/**
* CPU percentage usage
*/
public class CpuPerc {
private double user;
private double sys;
private double nice;
private double idle;
private double wait;
CpuPerc() {}
static CpuPerc calculate(Cpu oldCpu, Cpu curCpu) {
double diffUser, diffSys, diffNice, diffIdle, diffWait, diffTotal;
diffUser = curCpu.getUser() - oldCpu.getUser();
diffSys = curCpu.getSys() - oldCpu.getSys();
diffNice = curCpu.getNice() - oldCpu.getNice();
diffIdle = curCpu.getIdle() - oldCpu.getIdle();
diffWait = curCpu.getWait() - oldCpu.getWait();
// Sanity check -- sometimes these values waiver in between
// whole numbers when Cpu is checked very rapidly
diffUser = diffUser < 0 ? 0 : diffUser;
diffSys = diffSys < 0 ? 0 : diffSys;
diffNice = diffNice < 0 ? 0 : diffNice;
diffIdle = diffIdle < 0 ? 0 : diffIdle;
diffWait = diffWait < 0 ? 0 : diffWait;
diffTotal = diffUser + diffSys + diffNice + diffIdle + diffWait;
CpuPerc perc = new CpuPerc();
perc.user = diffUser / diffTotal;
perc.sys = diffSys / diffTotal;
perc.nice = diffNice / diffTotal;
perc.idle = diffIdle / diffTotal;
perc.wait = diffWait / diffTotal;
return perc;
}
public double getUser() {
return this.user;
}
public double getSys() {
return this.sys;
}
public double getNice() {
return this.nice;
}
public double getIdle() {
return this.idle;
}
public double getWait() {
return this.wait;
}
/**
* @return Sum of User + Sys + Nice + Wait
*/
public double getCombined() {
return this.user + this.sys + this.nice + this.wait;
}
public static String format(double val) {
String p = String.valueOf(val * 100.0);
//cant wait for sprintf.
int ix = p.indexOf(".") + 1;
String percent =
p.substring(0, ix) +
p.substring(ix, ix+1);
return percent + "%";
}
public String toString() {
return
"CPU states: " +
format(this.user) + " user, " +
format(this.sys) + " system, " +
format(this.nice) + " nice, " +
format(this.wait) + " wait, " +
format(this.idle) + " idle";
}
}
|
package aQute.bnd.header;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.*;
import aQute.bnd.osgi.*;
import aQute.bnd.version.*;
import aQute.lib.collections.*;
public class Attrs implements Map<String,String> {
public enum Type {
STRING(null, "String"), LONG(null, "Long"), VERSION(null, "Version"), DOUBLE(null, "Double"), STRINGS(STRING,
"List<String>"), LONGS(LONG, "List<Long>"), VERSIONS(VERSION, "List<Version>"), DOUBLES(DOUBLE,
"List<Double>");
Type sub;
String toString;
Type(Type sub, String toString) {
this.sub = sub;
this.toString = toString;
}
public String toString() {
return toString;
}
public Type plural() {
switch (this) {
case DOUBLE :
return DOUBLES;
case LONG :
return LONGS;
case STRING :
return STRINGS;
case VERSION :
return VERSIONS;
default :
return null;
}
}
}
static String EXTENDED = "[\\-0-9a-zA-Z\\._]+";
static String SCALAR = "String|Version|Long|Double";
static String LIST = "List\\s*<\\s*(" + SCALAR + ")\\s*>";
public static final Pattern TYPED = Pattern.compile("\\s*(" + EXTENDED + ")\\s*:\\s*(" + SCALAR + "|" + LIST
+ ")\\s*");
private Map<String,String> map;
private Map<String,Type> types;
static Map<String,String> EMPTY = Collections.emptyMap();
public static Attrs EMPTY_ATTRS = new Attrs();
static {
EMPTY_ATTRS.map = Collections.emptyMap();
}
public Attrs() {}
public Attrs(Attrs... attrs) {
for (Attrs a : attrs) {
if (a != null) {
putAll(a);
if (a.types != null)
types.putAll(a.types);
}
}
}
public void putAllTyped(Map<String,Object> attrs) {
for (Map.Entry<String,Object> entry : attrs.entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
putTyped(key, value);
}
}
public void putTyped(String key, Object value) {
if ( value == null) {
put(key,null);
return;
}
if (!(value instanceof String)) {
Type type;
if (value instanceof Collection)
value = ((Collection< ? >) value).toArray();
if (value.getClass().isArray()) {
type = Type.STRINGS;
int l = Array.getLength(value);
StringBuilder sb = new StringBuilder();
String del = null;
for (int i = 0; i < l; i++) {
Object member = Array.get(value, i);
if (member == null) {
// TODO What do we do with null members?
continue;
} else if (del == null) {
type = getObjectType(member).plural();
} else {
sb.append(del);
int n=sb.length();
sb.append(member);
while ( n < sb.length()) {
char c = sb.charAt(n);
if (c == '\\' || c== ',') {
sb.insert(n, '\\');
n++;
}
n++;
}
}
del = ",";
}
value = sb;
} else {
type = getObjectType(value);
}
key += ":" + type.toString();
}
put(key, value.toString());
}
private Type getObjectType(Object member) {
if (member instanceof Double)
return Type.DOUBLE;
if (member instanceof Long)
return Type.LONG;
if (member instanceof Version)
return Type.VERSION;
return Type.STRING;
}
public void clear() {
map.clear();
}
public boolean containsKey(String name) {
if (map == null)
return false;
return map.containsKey(name);
}
@SuppressWarnings("cast")
@Deprecated
public boolean containsKey(Object name) {
assert name instanceof String;
if (map == null)
return false;
return map.containsKey((String) name);
}
public boolean containsValue(String value) {
if (map == null)
return false;
return map.containsValue(value);
}
@SuppressWarnings("cast")
@Deprecated
public boolean containsValue(Object value) {
assert value instanceof String;
if (map == null)
return false;
return map.containsValue((String) value);
}
public Set<java.util.Map.Entry<String,String>> entrySet() {
if (map == null)
return EMPTY.entrySet();
return map.entrySet();
}
@SuppressWarnings("cast")
@Deprecated
public String get(Object key) {
assert key instanceof String;
if (map == null)
return null;
return map.get((String) key);
}
public String get(String key) {
if (map == null)
return null;
return map.get(key);
}
public String get(String key, String deflt) {
String s = get(key);
if (s == null)
return deflt;
return s;
}
public boolean isEmpty() {
return map == null || map.isEmpty();
}
public Set<String> keySet() {
if (map == null)
return EMPTY.keySet();
return map.keySet();
}
public String put(String key, String value) {
if (key == null)
return null;
if (map == null)
map = new LinkedHashMap<String,String>();
Matcher m = TYPED.matcher(key);
if (m.matches()) {
key = m.group(1);
String type = m.group(2);
Type t = Type.STRING;
if (type.startsWith("List")) {
type = m.group(3);
if ("String".equals(type))
t = Type.STRINGS;
else if ("Long".equals(type))
t = Type.LONGS;
else if ("Double".equals(type))
t = Type.DOUBLES;
else if ("Version".equals(type))
t = Type.VERSIONS;
} else {
if ("String".equals(type))
t = Type.STRING;
else if ("Long".equals(type))
t = Type.LONG;
else if ("Double".equals(type))
t = Type.DOUBLE;
else if ("Version".equals(type))
t = Type.VERSION;
}
if (types == null)
types = new LinkedHashMap<String,Type>();
types.put(key, t);
// TODO verify value?
}
return map.put(key, value);
}
public Type getType(String key) {
if (types == null)
return Type.STRING;
Type t = types.get(key);
if (t == null)
return Type.STRING;
return t;
}
public void putAll(Map< ? extends String, ? extends String> map) {
for (Map.Entry< ? extends String, ? extends String> e : map.entrySet())
put(e.getKey(), e.getValue());
}
@SuppressWarnings("cast")
@Deprecated
public String remove(Object var0) {
assert var0 instanceof String;
if (map == null)
return null;
return map.remove((String) var0);
}
public String remove(String var0) {
if (map == null)
return null;
return map.remove(var0);
}
public int size() {
if (map == null)
return 0;
return map.size();
}
public Collection<String> values() {
if (map == null)
return EMPTY.values();
return map.values();
}
public String getVersion() {
return get("version");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
append(sb);
return sb.toString();
}
public void append(StringBuilder sb) {
try {
String del = "";
for (Map.Entry<String,String> e : entrySet()) {
sb.append(del);
sb.append(e.getKey());
if (types != null) {
Type type = types.get(e.getKey());
if (type != null) {
sb.append(":").append(type);
}
}
sb.append("=");
Processor.quote(sb, e.getValue());
del = ";";
}
}
catch (Exception e) {
// Cannot happen
e.printStackTrace();
}
}
@Override
@Deprecated
public boolean equals(Object other) {
return super.equals(other);
}
@Override
@Deprecated
public int hashCode() {
return super.hashCode();
}
public boolean isEqual(Attrs other) {
if (this == other)
return true;
if (other == null || size() != other.size())
return false;
if (isEmpty())
return true;
SortedList<String> l = new SortedList<String>(keySet());
SortedList<String> lo = new SortedList<String>(other.keySet());
if (!l.isEqual(lo))
return false;
for (String key : keySet()) {
String value = get(key);
String valueo = other.get(key);
if (!(value == valueo || (value != null && value.equals(valueo))))
return false;
}
return true;
}
public Object getTyped(String adname) {
String s = get(adname);
if (s == null)
return null;
Type t = getType(adname);
return convert(t, s);
}
private Object convert(Type t, String s) {
if (t.sub == null) {
switch (t) {
case STRING :
return s;
case LONG :
return Long.parseLong(s.trim());
case VERSION :
return Version.parseVersion(s);
case DOUBLE :
return Double.parseDouble(s.trim());
case DOUBLES :
case LONGS :
case STRINGS :
case VERSIONS :
// Cannot happen since the sub is null
return null;
}
return null;
}
List<Object> list = new ArrayList<Object>();
List<String> split = splitListAttribute(s);
for (String p : split)
list.add(convert(t.sub, p));
return list;
}
static List<String> splitListAttribute(String input) throws IllegalArgumentException {
List<String> result = new LinkedList<String>();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '\\' :
i++;
if (i >= input.length())
throw new IllegalArgumentException("Trailing blackslash in multi-valued attribute value");
c = input.charAt(i);
builder.append(c);
break;
case ',' :
result.add(builder.toString());
builder = new StringBuilder();
break;
default :
builder.append(c);
break;
}
}
result.add(builder.toString());
return result;
}
}
|
package com.mygdx.game.objects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.collision.btBoxShape;
import com.badlogic.gdx.physics.bullet.collision.btCollisionShape;
import com.badlogic.gdx.physics.bullet.dynamics.btConeTwistConstraint;
import com.badlogic.gdx.physics.bullet.dynamics.btFixedConstraint;
import com.badlogic.gdx.physics.bullet.dynamics.btHingeConstraint;
import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ArrayMap;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.ObjectMap;
import com.mygdx.game.blender.BlenderObject;
import com.mygdx.game.blender.BlenderScene;
import com.mygdx.game.settings.GameSettings;
import java.util.Iterator;
public class Ragdoll extends GameModelBody {
private final static float PI = MathUtils.PI;
private final static float PI2 = 0.5f * PI;
private final static float PI4 = 0.25f * PI;
// public final Array<btTypedConstraint> ragdollConstraints = new Array<btTypedConstraint>();
public final ArrayMap<btRigidBody, NodeConnection> map = new ArrayMap<btRigidBody, NodeConnection>();
public final Array<Node> nodes = new Array<Node>();
public final Matrix4 baseBodyTransform = new Matrix4();
public final Matrix4 resetRotationTransform = new Matrix4();
public final Matrix4 tmpMatrix = new Matrix4();
public final Vector3 tmpVec = new Vector3();
public final Vector3 nodeTrans = new Vector3();
public final Vector3 baseTrans = new Vector3();
public boolean ragdollControl = false;
public Ragdoll(Model model,
String id,
Vector3 location,
Vector3 rotation,
Vector3 scale,
btCollisionShape shape,
float mass,
short belongsToFlag,
short collidesWithFlag,
boolean callback,
boolean noDeactivate,
String ragdollJson,
String armatureNodeId) {
super(model, id, location, rotation, scale, shape, mass,
belongsToFlag, collidesWithFlag, callback, noDeactivate);
createRagdoll(ragdollJson, armatureNodeId);
}
@Override
public void update(float deltaTime) {
super.update(deltaTime);
if (ragdollControl) {
updateArmatureToBodies();
} else {
updateBodiesToArmature();
}
}
@Override
public void dispose() {
super.dispose();
for (btRigidBody body : map.keys) {
body.dispose();
}
map.clear();
}
private void updateArmatureToBodies() {
// Let dynamicsworld control ragdoll. Loop over all ragdoll part collision shapes
// and their node connection data.
for (Iterator<ObjectMap.Entry<btRigidBody, NodeConnection>> iterator1
= map.iterator(); iterator1.hasNext(); ) {
ObjectMap.Entry<btRigidBody, NodeConnection> bodyEntry = iterator1.next();
btRigidBody partBody = bodyEntry.key;
NodeConnection connection = bodyEntry.value;
// Loop over each node connected to this collision shape
for (Iterator<ObjectMap.Entry<Node, Vector3>> iterator2
= connection.bodyNodeOffsets.iterator(); iterator2.hasNext(); ) {
ObjectMap.Entry<Node, Vector3> nodeEntry = iterator2.next();
// A node which is to follow this collision shape
Node node = nodeEntry.key;
// The offset of this node from the untranslated collision shape origin
Vector3 offset = nodeEntry.value;
// Set the node to the transform of the collision shape it follows
partBody.getWorldTransform(node.localTransform);
// Calculate difference in translation between the node/ragdoll part and the
// base capsule shape.
node.localTransform.getTranslation(nodeTrans);
baseBodyTransform.getTranslation(baseTrans);
nodeTrans.sub(baseTrans);
// Calculate the final node transform
node.localTransform.setTranslation(nodeTrans).translate(tmpVec.set(offset).scl(-1));
}
}
// Calculate the final transform of the model.
modelInstance.calculateTransforms();
}
private void updateBodiesToArmature() {
// Ragdoll parts should follow the model animation.
// Loop over each part and set it to the global transform of the armature node it should follow.
body.getWorldTransform(baseBodyTransform);
for (Iterator<ObjectMap.Entry<btRigidBody, NodeConnection>> iterator
= map.iterator(); iterator.hasNext(); ) {
ObjectMap.Entry<btRigidBody, NodeConnection> entry = iterator.next();
NodeConnection data = entry.value;
btRigidBody body = entry.key;
Node followNode = data.followNode;
Vector3 offset = data.bodyNodeOffsets.get(followNode);
body.proceedToTransform(tmpMatrix.set(baseBodyTransform)
.mul(followNode.globalTransform).translate(offset));
}
}
public void toggle(boolean setRagdollControl) {
if (setRagdollControl) {
updateBodiesToArmature();
// Ragdoll follows animation currently, set it to use physics control.
// Animations should be paused for this model.
ragdollControl = true;
// Get the current translation of the base collision shape (the capsule)
baseBodyTransform.getTranslation(baseTrans);
// Reset any rotation of the model caused by the motion state from the physics engine,
// but keep the translation.
modelInstance.transform =
resetRotationTransform.idt().inv().setToTranslation(baseTrans);
// Set the velocities of the ragdoll collision shapes to be the same as the base shape.
for (btRigidBody bodyPart : map.keys()) {
bodyPart.setLinearVelocity(body.getLinearVelocity().scl(1, 0, 1));
bodyPart.setAngularVelocity(body.getAngularVelocity());
bodyPart.setGravity(GameSettings.GRAVITY);
}
// We don't want to use the translation, rotation, scale values of the model when calculating the
// model transform, and we don't want the nodes inherit the transform of the parent node,
// since the physics engine will be controlling the nodes.
for (Node node : nodes) {
node.isAnimated = true;
node.inheritTransform = false;
}
} else {
// Ragdoll physics control is enabled, disable it, reset nodes and ragdoll components to animation.
ragdollControl = false;
modelInstance.transform = motionState.transform;
// Reset the nodes to default model animation state.
for (Node node : nodes) {
node.isAnimated = false;
node.inheritTransform = true;
}
modelInstance.calculateTransforms();
// Disable gravity to prevent problems with the physics engine adding too much velocity
// to the ragdoll
for (btRigidBody bodyPart : map.keys()) {
bodyPart.setGravity(Vector3.Zero);
}
}
}
public class NodeConnection {
// Stores the offset from the center of a rigid body to the node which connects to it
public ArrayMap<Node, Vector3> bodyNodeOffsets = new ArrayMap<Node, Vector3>();
// The node this bone should follow in animation mode
public Node followNode = null;
}
private void addPart(btRigidBody bodyPart, Node node, Vector3 nodeBodyOffset) {
if (!map.containsKey(bodyPart)) {
map.put(bodyPart, new NodeConnection());
}
NodeConnection conn = map.get(bodyPart);
conn.bodyNodeOffsets.put(node, nodeBodyOffset);
if (!nodes.contains(node, true)) {
nodes.add(node);
}
}
private void addFollowPart(btRigidBody bodyPart, Node node) {
if (!map.containsKey(bodyPart)) {
map.put(bodyPart, new NodeConnection());
}
NodeConnection conn = map.get(bodyPart);
conn.followNode = node;
// Set the follow offset to the middle of the armature bone
Vector3 offsetTranslation = new Vector3();
node.getChild(0).localTransform.getTranslation(offsetTranslation).scl(0.5f);
conn.bodyNodeOffsets.put(node, offsetTranslation);
if (!nodes.contains(node, true)) {
nodes.add(node);
}
}
private void createRagdoll(String ragdollJson, String armatureNodeId) {
Node armature = modelInstance.getNode(armatureNodeId, true, true);
// Load mass and shape half extent data from Blender json
ArrayMap<String, Vector3> halfExtMap = new ArrayMap<String, Vector3>();
ArrayMap<String, Float> massMap = new ArrayMap<String, Float>();
Array<BlenderObject.BEmpty> empties =
new Json().fromJson(Array.class, BlenderObject.BEmpty.class, Gdx.files.local(ragdollJson));
for (BlenderObject.BEmpty empty : empties) {
BlenderScene.blenderToGdxCoordinates(empty);
Vector3 halfExtents = new Vector3(empty.scale);
halfExtents.x = Math.abs(halfExtents.x);
halfExtents.y = Math.abs(halfExtents.y);
halfExtents.z = Math.abs(halfExtents.z);
halfExtMap.put(empty.name, halfExtents);
float partMass = Float.parseFloat(empty.custom_properties.get("mass"));
massMap.put(empty.name, super.mass * partMass);
}
ArrayMap<String, btCollisionShape> shapeMap = new ArrayMap<String, btCollisionShape>();
ArrayMap<String, btRigidBody> bodyMap = new ArrayMap<String, btRigidBody>();
// Create rigid bodies using the previously loaded mass and half extents.
// Put them along with the shapes into maps.
for (Iterator<ObjectMap.Entry<String, Vector3>> iterator = halfExtMap.iterator(); iterator.hasNext(); ) {
ObjectMap.Entry<String, Vector3> entry = iterator.next();
String partName = entry.key;
Vector3 partHalfExt = entry.value;
float partMass = massMap.get(partName);
btCollisionShape partShape = new btBoxShape(partHalfExt);
shapeMap.put(partName, partShape);
InvisibleBody phyCmp = new InvisibleBody(
partShape, partMass, new Matrix4(), this.belongsToFlag,
this.collidesWithFlag, false, true);
phyCmp.constructionInfo.dispose();
bodyMap.put(partName, phyCmp.body);
this.addFollowPart(phyCmp.body, armature.getChild(partName, true, true));
}
// Abdomen is the at the top of the armature hierarchy
this.addPart(bodyMap.get("abdomen"), armature, new Vector3(0, halfExtMap.get("abdomen").y * 1.6f, 0));
final Matrix4 localA = new Matrix4();
final Matrix4 localB = new Matrix4();
btHingeConstraint hingeC;
btConeTwistConstraint coneC;
btFixedConstraint fixedC;
String a, b;
// TODO: This part could probably be automated somehow...
// Set the ragdollConstraints
a = "abdomen";
b = "chest";
localA.setFromEulerAnglesRad(0, PI4, 0).trn(0, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(0, PI4, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(hingeC = new btHingeConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
hingeC.setLimit(-PI4, PI2);
a = "chest";
b = "neck";
localA.setFromEulerAnglesRad(0, 0, 0).trn(0, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(0, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(fixedC = new btFixedConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
a = "neck";
b = "head";
localA.setFromEulerAnglesRad(-PI2, 0, 0).trn(0, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(-PI2, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(coneC = new btConeTwistConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
coneC.setLimit(PI4, PI4, PI4);
a = "abdomen";
b = "left_thigh";
localA.setFromEulerAnglesRad(0, PI, 0).scl(-1, 1, 1).trn(halfExtMap.get(a).x * 0.5f, -halfExtMap.get
("abdomen").y, 0);
localB.setFromEulerAnglesRad(0, 0, 0).scl(-1, 1, 1).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(coneC = new btConeTwistConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
coneC.setLimit(PI4, PI4, PI4);
coneC.setDamping(10);
a = "abdomen";
b = "right_thigh";
localA.setFromEulerAnglesRad(0, PI, 0).trn(-halfExtMap.get(a).x * 0.5f, -halfExtMap.get
("abdomen").y, 0);
localB.setFromEulerAnglesRad(0, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(coneC = new btConeTwistConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
coneC.setLimit(PI4, PI4, PI4);
coneC.setDamping(10);
a = "left_thigh";
b = "left_shin";
localA.setFromEulerAnglesRad(-PI2, 0, 0).trn(0, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(-PI2, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(hingeC = new btHingeConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
hingeC.setLimit(0, PI4 * 3);
a = "right_thigh";
b = "right_shin";
localA.setFromEulerAnglesRad(-PI2, 0, 0).trn(0, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(-PI2, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(hingeC = new btHingeConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
hingeC.setLimit(0, PI4 * 3);
// TODO: causes shoulder rotation
a = "chest";
b = "left_upper_arm";
localA.setFromEulerAnglesRad(0, PI, 0).trn(halfExtMap.get(a).x + halfExtMap.get(b).x, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(PI4, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(coneC = new btConeTwistConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
coneC.setLimit(PI2, PI2, 0);
coneC.setDamping(10);
// TODO: as above
a = "chest";
b = "right_upper_arm";
localA.setFromEulerAnglesRad(0, PI, 0).trn(-halfExtMap.get(a).x - halfExtMap.get(b).x, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(-PI4, 0, 0).trn(0, -halfExtMap.get("right_upper_arm").y, 0);
this.constraints.add(coneC = new btConeTwistConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
coneC.setLimit(PI2, PI2, 0);
coneC.setDamping(10);
a = "left_upper_arm";
b = "left_forearm";
localA.setFromEulerAnglesRad(PI2, 0, 0).trn(0, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(PI2, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(hingeC = new btHingeConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
hingeC.setLimit(0, PI2);
a = "right_upper_arm";
b = "right_forearm";
localA.setFromEulerAnglesRad(PI2, 0, 0).trn(0, halfExtMap.get(a).y, 0);
localB.setFromEulerAnglesRad(PI2, 0, 0).trn(0, -halfExtMap.get(b).y, 0);
this.constraints.add(hingeC = new btHingeConstraint(bodyMap.get(a), bodyMap.get(b), localA, localB));
hingeC.setLimit(0, PI2);
}
}
|
package arez;
import arez.spy.ComputedValueActivatedEvent;
import arez.spy.ComputedValueDeactivatedEvent;
import arez.spy.ObservableValueChangedEvent;
import arez.spy.ObservableValueDisposedEvent;
import arez.spy.ObservableValueInfo;
import arez.spy.PropertyAccessor;
import arez.spy.PropertyMutator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* The observable represents state that can be observed within the system.
*/
public final class ObservableValue<T>
extends Node
{
/**
* The value of _workState when the ObservableValue is should longer be used.
*/
static final int DISPOSED = -2;
/**
* The value that _workState is set to to optimize the detection of duplicate,
* existing and new dependencies during tracking completion.
*/
static final int IN_CURRENT_TRACKING = -1;
/**
* The value that _workState is when the observer has been added as new dependency
* to derivation.
*/
static final int NOT_IN_CURRENT_TRACKING = 0;
private final ArrayList<Observer> _observers = new ArrayList<>();
/**
* True if deactivation has been requested.
* Used to avoid adding duplicates to pending deactivation list.
*/
private boolean _pendingDeactivation;
/**
* The workState variable contains some data used during processing of observable
* at various stages.
*
* Within the scope of a tracking transaction, it is set to the id of the tracking
* observer if the observable was observed. This enables an optimization that skips
* adding this observer to the same observer multiple times. This optimization sometimes
* ignored as nested transactions that observe the same observer will reset this value.
*
* When completing a tracking transaction the value may be set to {@link #IN_CURRENT_TRACKING}
* or {@link #NOT_IN_CURRENT_TRACKING} but should be set to {@link #NOT_IN_CURRENT_TRACKING} after
* {@link Transaction#completeTracking()} method is completed..
*/
private int _workState;
/**
* The state of the observer that is least stale.
* This cached value is used to avoid redundant propagations.
*/
private int _leastStaleObserverState = Flags.STATE_UP_TO_DATE;
/**
* The observer that created this observable if any.
*/
@Nullable
private final Observer _owner;
/**
* The component that this observable is contained within.
* This should only be set if {@link Arez#areNativeComponentsEnabled()} is true but may also be null if
* the observable is a "top-level" observable.
*/
@Nullable
private final Component _component;
/**
* The accessor method to retrieve the value.
* This should only be set if {@link Arez#arePropertyIntrospectorsEnabled()} is true but may also be elided if the
* value should not be accessed even by DevTools.
*/
@Nullable
private final PropertyAccessor<T> _accessor;
/**
* The mutator method to change the value.
* This should only be set if {@link Arez#arePropertyIntrospectorsEnabled()} is true but may also be elided if the
* value should not be mutated even by DevTools.
*/
@Nullable
private final PropertyMutator<T> _mutator;
/**
* Cached info object associated with element.
* This should be null if {@link Arez#areSpiesEnabled()} is false;
*/
@Nullable
private ObservableValueInfo _info;
ObservableValue( @Nullable final ArezContext context,
@Nullable final Component component,
@Nullable final String name,
@Nullable final Observer owner,
@Nullable final PropertyAccessor<T> accessor,
@Nullable final PropertyMutator<T> mutator )
{
super( context, name );
_component = Arez.areNativeComponentsEnabled() ? component : null;
_owner = owner;
_accessor = accessor;
_mutator = mutator;
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> Arez.areNativeComponentsEnabled() || null == component,
() -> "Arez-0054: ObservableValue named '" + getName() + "' has component specified but " +
"Arez.areNativeComponentsEnabled() is false." );
}
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( () -> Arez.arePropertyIntrospectorsEnabled() || null == accessor,
() -> "Arez-0055: ObservableValue named '" + getName() + "' has accessor specified but " +
"Arez.arePropertyIntrospectorsEnabled() is false." );
apiInvariant( () -> Arez.arePropertyIntrospectorsEnabled() || null == mutator,
() -> "Arez-0056: ObservableValue named '" + getName() + "' has mutator specified but " +
"Arez.arePropertyIntrospectorsEnabled() is false." );
}
if ( null != _owner )
{
// This invariant can not be checked if Arez.shouldEnforceTransactionType() is false as
// the variable has yet to be assigned and no transaction mode set. Thus just skip the
// check in this scenario.
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> !Arez.shouldEnforceTransactionType() || _owner.isComputedValue(),
() -> "Arez-0057: ObservableValue named '" + getName() + "' has owner specified " +
"but owner is not a derivation." );
}
assert !Arez.areNamesEnabled() || _owner.getName().equals( name );
}
if ( !hasOwner() )
{
if ( null != _component )
{
_component.addObservableValue( this );
}
else if ( Arez.areRegistriesEnabled() )
{
getContext().registerObservableValue( this );
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void dispose()
{
if ( isNotDisposed() )
{
getContext().safeAction( Arez.areNamesEnabled() ? getName() + ".dispose" : null, this::performDispose );
// All dependencies should have been released by the time it comes to deactivate phase.
// The ObservableValue has been marked as changed, forcing all observers to re-evaluate and
// ultimately this will result in their removal of this ObservableValue as a dependency as
// it is an error to invoke reportObserved(). Once all dependencies are removed then
// this ObservableValue will be deactivated if it is a ComputedValue. Thus no need to call
// queueForDeactivation() here.
if ( hasOwner() )
{
/*
* Dispose the owner first so that it is removed as a dependency and thus will not have a reaction
* scheduled.
*/
getOwner().dispose();
}
else
{
if ( willPropagateSpyEvents() )
{
reportSpyEvent( new ObservableValueDisposedEvent( asInfo() ) );
}
if ( null != _component )
{
_component.removeObservableValue( this );
}
else if ( Arez.areRegistriesEnabled() )
{
getContext().deregisterObservableValue( this );
}
}
}
}
private void performDispose()
{
getContext().getTransaction().reportDispose( this );
reportChanged();
_workState = DISPOSED;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDisposed()
{
return DISPOSED == _workState;
}
@Nullable
PropertyAccessor<T> getAccessor()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::arePropertyIntrospectorsEnabled,
() -> "Arez-0058: Attempt to invoke getAccessor() on ObservableValue named '" + getName() +
"' when Arez.arePropertyIntrospectorsEnabled() returns false." );
}
return _accessor;
}
@Nullable
PropertyMutator<T> getMutator()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::arePropertyIntrospectorsEnabled,
() -> "Arez-0059: Attempt to invoke getMutator() on ObservableValue named '" + getName() +
"' when Arez.arePropertyIntrospectorsEnabled() returns false." );
}
return _mutator;
}
void markAsPendingDeactivation()
{
_pendingDeactivation = true;
}
boolean isPendingDeactivation()
{
return _pendingDeactivation;
}
void resetPendingDeactivation()
{
_pendingDeactivation = false;
}
int getLastTrackerTransactionId()
{
return _workState;
}
void setLastTrackerTransactionId( final int lastTrackerTransactionId )
{
setWorkState( lastTrackerTransactionId );
}
void setWorkState( final int workState )
{
_workState = workState;
}
boolean isInCurrentTracking()
{
return IN_CURRENT_TRACKING == _workState;
}
void putInCurrentTracking()
{
_workState = IN_CURRENT_TRACKING;
}
void removeFromCurrentTracking()
{
_workState = NOT_IN_CURRENT_TRACKING;
}
@Nonnull
Observer getOwner()
{
assert null != _owner;
return _owner;
}
/**
* Return true if this observable can deactivate when it is no longer observed and activate when it is observed again.
*/
boolean canDeactivate()
{
return hasOwner() && !getOwner().isKeepAlive();
}
/**
* Return true if this observable is derived from an observer.
*/
boolean hasOwner()
{
return null != _owner;
}
/**
* Return true if observable is notifying observers.
*/
boolean isActive()
{
return null == _owner || _owner.isActive();
}
/**
* Deactivate the observable.
* This means that the observable no longer has any listeners and can release resources associated
* with generating values. (i.e. remove observers on any observables that are used to compute the
* value of this observable).
*/
void deactivate()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getContext().isTransactionActive(),
() -> "Arez-0060: Attempt to invoke deactivate on ObservableValue named '" + getName() +
"' when there is no active transaction." );
invariant( this::canDeactivate,
() -> "Arez-0061: Invoked deactivate on ObservableValue named '" + getName() + "' but " +
"ObservableValue can not be deactivated. Either owner is null or the associated " +
"ComputedValue has keepAlive enabled." );
}
assert null != _owner;
if ( _owner.isActive() )
{
/*
* It is possible for the owner to already be deactivated if dispose() is explicitly
* called within the transaction.
*/
_owner.setState( Flags.STATE_INACTIVE );
if ( willPropagateSpyEvents() )
{
reportSpyEvent( new ComputedValueDeactivatedEvent( _owner.getComputedValue().asInfo() ) );
}
}
}
/**
* Activate the observable.
* The reverse of {@link #deactivate()}.
*/
void activate()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getContext().isTransactionActive(),
() -> "Arez-0062: Attempt to invoke activate on ObservableValue named '" + getName() +
"' when there is no active transaction." );
invariant( () -> null != _owner,
() -> "Arez-0063: Invoked activate on ObservableValue named '" + getName() + "' when owner is null." );
assert null != _owner;
invariant( _owner::isInactive,
() -> "Arez-0064: Invoked activate on ObservableValue named '" + getName() + "' when " +
"ObservableValue is already active." );
}
assert null != _owner;
_owner.setState( Flags.STATE_UP_TO_DATE );
if ( willPropagateSpyEvents() )
{
reportSpyEvent( new ComputedValueActivatedEvent( _owner.getComputedValue().asInfo() ) );
}
}
@Nonnull
ArrayList<Observer> getObservers()
{
return _observers;
}
boolean hasObservers()
{
return getObservers().size() > 0;
}
boolean hasObserver( @Nonnull final Observer observer )
{
return getObservers().contains( observer );
}
void addObserver( @Nonnull final Observer observer )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getContext().isTransactionActive(),
() -> "Arez-0065: Attempt to invoke addObserver on ObservableValue named '" + getName() +
"' when there is no active transaction." );
invariantObserversLinked();
invariant( () -> !hasObserver( observer ),
() -> "Arez-0066: Attempting to add observer named '" + observer.getName() + "' to ObservableValue " +
"named '" + getName() + "' when observer is already observing ObservableValue." );
invariant( this::isNotDisposed,
() -> "Arez-0067: Attempting to add observer named '" + observer.getName() + "' to " +
"ObservableValue named '" + getName() + "' when ObservableValue is disposed." );
invariant( observer::isNotDisposed,
() -> "Arez-0068: Attempting to add observer named '" + observer.getName() + "' to ObservableValue " +
"named '" + getName() + "' when observer is disposed." );
invariant( () -> !hasOwner() ||
observer.canObserveLowerPriorityDependencies() ||
observer.getPriority().ordinal() >= getOwner().getPriority().ordinal(),
() -> "Arez-0183: Attempting to add observer named '" + observer.getName() + "' to ObservableValue " +
"named '" + getName() + "' where the observer is scheduled at a " + observer.getPriority() +
" priority but the ObservableValue's owner is scheduled at a " +
getOwner().getPriority() + " priority." );
invariant( () -> getContext().getTransaction().getTracker() == observer,
() -> "Arez-0203: Attempting to add observer named '" + observer.getName() + "' to ObservableValue " +
"named '" + getName() + "' but the observer is not the tracker in transaction named '" +
getContext().getTransaction().getName() + "'." );
}
rawAddObserver( observer );
}
void rawAddObserver( @Nonnull final Observer observer )
{
getObservers().add( observer );
final int state = observer.getLeastStaleObserverState();
if ( _leastStaleObserverState > state )
{
_leastStaleObserverState = state;
}
}
void removeObserver( @Nonnull final Observer observer )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getContext().isTransactionActive(),
() -> "Arez-0069: Attempt to invoke removeObserver on ObservableValue named '" + getName() + "' " +
"when there is no active transaction." );
invariantObserversLinked();
invariant( () -> hasObserver( observer ),
() -> "Arez-0070: Attempting to remove observer named '" + observer.getName() + "' from " +
"ObservableValue named '" + getName() + "' when observer is not observing ObservableValue." );
}
final ArrayList<Observer> observers = getObservers();
observers.remove( observer );
if ( observers.isEmpty() && canDeactivate() )
{
queueForDeactivation();
}
if ( Arez.shouldCheckInvariants() )
{
invariantObserversLinked();
}
}
void queueForDeactivation()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getContext().isTransactionActive(),
() -> "Arez-0071: Attempt to invoke queueForDeactivation on ObservableValue named '" + getName() +
"' when there is no active transaction." );
invariant( this::canDeactivate,
() -> "Arez-0072: Attempted to invoke queueForDeactivation() on ObservableValue named '" + getName() +
"' but ObservableValue is not able to be deactivated." );
invariant( () -> !hasObservers(),
() -> "Arez-0073: Attempted to invoke queueForDeactivation() on ObservableValue named '" + getName() +
"' but ObservableValue has observers." );
}
if ( !isPendingDeactivation() )
{
getContext().getTransaction().queueForDeactivation( this );
}
}
void setLeastStaleObserverState( final int leastStaleObserverState )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getContext().isTransactionActive(),
() -> "Arez-0074: Attempt to invoke setLeastStaleObserverState on ObservableValue named '" +
getName() + "' when there is no active transaction." );
invariant( () -> Flags.isActive( leastStaleObserverState ),
() -> "Arez-0075: Attempt to invoke setLeastStaleObserverState on ObservableValue named '" +
getName() + "' with invalid value " + Flags.getStateName( leastStaleObserverState ) + "." );
}
_leastStaleObserverState = leastStaleObserverState;
}
final int getLeastStaleObserverState()
{
return _leastStaleObserverState;
}
/**
* Notify Arez that this observable has been "observed" in the current transaction.
*/
public void reportObserved()
{
getContext().getTransaction().observe( this );
}
/**
* Notify Arez that this observable has been "observed" if a tracking transaction is active.
*/
public void reportObservedIfTrackingTransactionActive()
{
if ( getContext().isTrackingTransactionActive() )
{
reportObserved();
}
}
/**
* Check that pre-conditions are satisfied before changing observable value.
* In production mode this will typically be a no-op. This method should be invoked
* before state is modified.
*/
public void preReportChanged()
{
if ( Arez.shouldCheckInvariants() )
{
getContext().getTransaction().preReportChanged( this );
}
}
/**
* Notify Arez that this observable has changed.
* This is called when the observable has definitely changed.
*/
public void reportChanged()
{
if ( willPropagateSpyEvents() )
{
reportSpyEvent( new ObservableValueChangedEvent( asInfo(), getObservableValue() ) );
}
getContext().getTransaction().reportChanged( this );
}
void reportChangeConfirmed()
{
if ( willPropagateSpyEvents() )
{
reportSpyEvent( new ObservableValueChangedEvent( asInfo(), getObservableValue() ) );
}
getContext().getTransaction().reportChangeConfirmed( this );
}
void reportPossiblyChanged()
{
getContext().getTransaction().reportPossiblyChanged( this );
}
/**
* Return the value from observable if introspectors are enabled and an accessor has been supplied.
*/
@Nullable
private Object getObservableValue()
{
if ( Arez.arePropertyIntrospectorsEnabled() && null != getAccessor() )
{
try
{
return getAccessor().get();
}
catch ( final Throwable ignored )
{
}
}
return null;
}
/**
* Return the info associated with this class.
*
* @return the info associated with this class.
*/
@SuppressWarnings( "ConstantConditions" )
@Nonnull
ObservableValueInfo asInfo()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areSpiesEnabled,
() -> "Arez-0196: ObservableValue.asInfo() invoked but Arez.areSpiesEnabled() returned false." );
}
if ( Arez.areSpiesEnabled() && null == _info )
{
_info = new ObservableValueInfoImpl( getContext().getSpy(), this );
}
return Arez.areSpiesEnabled() ? _info : null;
}
void invariantOwner()
{
if ( Arez.shouldCheckInvariants() && null != _owner )
{
invariant( () -> Objects.equals( _owner.getComputedValue().getObservableValue(), this ),
() -> "Arez-0076: ObservableValue named '" + getName() + "' has owner specified but owner does " +
"not link to ObservableValue as derived value." );
}
}
void invariantObserversLinked()
{
if ( Arez.shouldCheckInvariants() )
{
getObservers().forEach( observer ->
invariant( () -> observer.getDependencies().contains( this ),
() -> "Arez-0077: ObservableValue named '" + getName() + "' has observer " +
"named '" + observer.getName() + "' which does not contain " +
"ObservableValue as dependency." ) );
}
}
void invariantLeastStaleObserverState()
{
if ( Arez.shouldCheckInvariants() )
{
final int leastStaleObserverState =
getObservers().stream().
map( Observer::getLeastStaleObserverState ).
min( Comparator.naturalOrder() ).orElse( Flags.STATE_UP_TO_DATE );
invariant( () -> leastStaleObserverState >= _leastStaleObserverState,
() -> "Arez-0078: Calculated leastStaleObserverState on ObservableValue named '" + getName() +
"' is '" + Flags.getStateName( leastStaleObserverState ) + "' which is unexpectedly less " +
"than cached value '" + Flags.getStateName( _leastStaleObserverState ) + "'." );
}
}
@Nullable
Component getComponent()
{
return _component;
}
int getWorkState()
{
return _workState;
}
}
|
// SamsoN - utilities for playn clients and servers
package samson.text;
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.Lists;
import samson.Samson;
/**
* Utility functions for translation string handling.
*/
public class Messages
{
/** Used to mark fully qualified message keys. */
public static final String QUAL_PREFIX = "%";
/** Used to separate the bundle qualifier from the message key in a fully qualified message
* key. */
public static final String QUAL_SEP = ":";
/**
* Call this to "taint" any string that has been entered by an entity outside the application
* so that the translation code knows not to attempt to translate this string when doing
* recursive translations.
*/
public static String taint (Object text) {
return TAINT_CHAR + text;
}
/**
* Returns whether or not the provided string is tainted. See {@link #taint}. Null strings
* are considered untainted.
*/
public static boolean isTainted (String text) {
return text != null && text.startsWith(TAINT_CHAR);
}
/**
* Removes the tainting character added to a string by {@link #taint}. If the provided string
* is not tainted, this silently returns the originally provided string.
*/
public static String untaint (String text) {
return isTainted(text) ? text.substring(TAINT_CHAR.length()) : text;
}
/**
* Composes a message key with an array of arguments. The message can subsequently be
* decomposed and translated without prior knowledge of how many arguments were provided.
*/
public static String compose (String key, Object... args) {
StringBuilder buf = new StringBuilder();
buf.append(key);
buf.append('|');
for (int i = 0; i < args.length; i++) {
if (i > 0) {
buf.append('|');
}
// escape the string while adding to the buffer
String arg = (args[i] == null) ? "" : String.valueOf(args[i]);
int alength = arg.length();
for (int p = 0; p < alength; p++) {
char ch = arg.charAt(p);
if (ch == '|') {
buf.append("\\!");
} else if (ch == '\\') {
buf.append("\\\\");
} else {
buf.append(ch);
}
}
}
return buf.toString();
}
/**
* Compose a message with String args. This is just a convenience so callers do not have to
* cast their String[] to an Object[].
*/
public static String compose (String key, String... args) {
return compose(key, (Object[]) args);
}
/**
* Unescapes characters that are escaped in a call to compose.
*/
public static String unescape (String value) {
int bsidx = value.indexOf('\\');
if (bsidx == -1) {
return value;
}
StringBuilder buf = new StringBuilder();
int vlength = value.length();
for (int ii = 0; ii < vlength; ii++) {
char ch = value.charAt(ii);
if (ch != '\\' || ii == vlength-1) {
buf.append(ch);
} else {
// look at the next character
ch = value.charAt(++ii);
buf.append((ch == '!') ? '|' : ch);
}
}
return buf.toString();
}
/**
* A convenience method for calling {@link #compose(String,Object[])} with an array of
* arguments that will be automatically tainted (see {@link #taint}).
*/
public static String tcompose (String key, Object... args) {
int acount = args.length;
String[] targs = new String[acount];
for (int ii = 0; ii < acount; ii++) {
targs[ii] = taint(args[ii]);
}
return compose(key, (Object[]) targs);
}
/**
* A convenience method for calling {@link #compose(String,String[])} with an array of argument
* that will be automatically tainted.
*/
public static String tcompose (String key, String... args) {
for (int ii = 0, nn = args.length; ii < nn; ii++) {
args[ii] = taint(args[ii]);
}
return compose(key, args);
}
/**
* Decomposes a compound key into its constituent parts. Arguments that were tainted during
* composition will remain tainted.
*/
public static String[] decompose (String compoundKey) {
String[] args = compoundKey.split("\\|");
for (int ii = 0; ii < args.length; ii++) {
args[ii] = unescape(args[ii]);
}
return args;
}
/**
* Returns a fully qualified message key which, when translated by some other bundle, will know
* to resolve and utilize the supplied bundle to translate this particular key.
*/
public static String qualify (String bundle, String key) {
// sanity check
if (bundle.indexOf(QUAL_PREFIX) != -1 ||
bundle.indexOf(QUAL_SEP) != -1) {
String errmsg = "Message bundle may not contain '" + QUAL_PREFIX +
"' or '" + QUAL_SEP + "' [bundle=" + bundle +
", key=" + key + "]";
throw new IllegalArgumentException(errmsg);
}
return QUAL_PREFIX + bundle + QUAL_SEP + key;
}
/**
* Returns the bundle name from a fully qualified message key.
*
* @see #qualify
*/
public static String getBundle (String qualifiedKey) {
if (!qualifiedKey.startsWith(QUAL_PREFIX)) {
throw new IllegalArgumentException(
qualifiedKey + " is not a fully qualified message key.");
}
int qsidx = qualifiedKey.indexOf(QUAL_SEP);
if (qsidx == -1) {
throw new IllegalArgumentException(
qualifiedKey + " is not a valid fully qualified key.");
}
return qualifiedKey.substring(QUAL_PREFIX.length(), qsidx);
}
/**
* Returns the unqualified portion of the key from a fully qualified message key.
*
* @see #qualify
*/
public static String getUnqualifiedKey (String qualifiedKey) {
if (!qualifiedKey.startsWith(QUAL_PREFIX)) {
throw new IllegalArgumentException(
qualifiedKey + " is not a fully qualified message key.");
}
int qsidx = qualifiedKey.indexOf(QUAL_SEP);
if (qsidx == -1) {
throw new IllegalArgumentException(
qualifiedKey + " is not a valid fully qualified key.");
}
return qualifiedKey.substring(qsidx+1);
}
/**
* Turn an array of strings into a composed string representing them. Optionally uses an "and"
* list.
*/
public static String composeAsList (String[] list, boolean and) {
return composeAsList(Lists.newArrayList(list), and);
}
/**
* Turn a list of strings into a composed string representing them. Optionally uses an "and"
* list.
*/
public static String composeAsList (List<String> list, boolean and) {
int size = list.size();
if (size == 1) {
return list.get(0);
}
if (size <= 9) {
return Messages.compose((and ? "m.andlist" : "m.list") + list.size(),
list.toArray());
}
ArrayList<String> subLists = Lists.newArrayList();
for (int ii = 0; ii < 8; ii ++) {
subLists.add(composeAsList(list.subList(ii * size/9, (ii+1) * size/9), false));
}
subLists.add(composeAsList(list.subList(8 * size/9, size), and));
return composeAsList(subLists, false);
}
public static String format (String pattern, Object... args) {
StringBuilder result = null;
for (int off = 0, len = pattern.length(); off < len; ++off) {
char ch = pattern.charAt(off);
int close = off;
// format elements, e.g. {0}
if (ch == '{') {
close = pattern.indexOf('}', off + 1);
if (close == -1) {
error("Close brace is missing", pattern, off);
return pattern;
}
// to save garbage collection, lazily create the result buffer
if (result == null) {
// initialize with the contents thus far
result = new StringBuilder();
result.append(pattern, 0, off);
}
subformat(pattern, off + 1, close, args, result);
} else {
if (result != null) {
result.append(ch);
}
}
off = close;
}
return result == null ? pattern : result.toString();
}
private static void subformat (String pattern, int start, int end, Object[] args,
StringBuilder result) {
int off = start;
while (off < end && pattern.charAt(off) != ',') {
off++;
}
try {
int index = Integer.parseInt(pattern.substring(start, off));
if (index < 0 || index >= args.length) {
error("Not enough arguments (got " + args.length + ")", pattern ,start);
}
result.append(args[index]);
} catch (NumberFormatException e) {
error("Expected a numeric index in format element", pattern, start);
}
}
private static void error (String str, String pattern, int offset) {
throw new IllegalArgumentException(
str + " in pattern \"" + pattern + "\", offset " + offset);
}
/** Text prefixed by this character will be considered tainted when doing recursive
* translations and won't be translated. */
protected static final String TAINT_CHAR = "~";
}
|
package xal.smf;
import xal.ca.*;
import xal.tools.data.*;
import xal.tools.transforms.ValueTransform;
import java.util.*;
/**
* Manage the mapping of handles to signals and channels for a node. A signal
* is the unique PV name used for accessing EPICS records. A handle is a
* high level name used to access a PV in a specific context. For example a
* channel suite instance typically represents a suite of PVs associated with
* a particular element. Consider a BPM element. It has several PVs associated
* with it. The handles are labels common to all BPMs such as "xAvg", "yAvg", ...
* The handle is used to access a particular PV when applied to an element. So
* for example "xAvg" applied to BPM 1 of the MEBT refers to the specific PV
* "MEBT_Diag:BPM01:xAvg". Thus a handle is to a ChannelSuite instance much like an
* instance variable is to an instance of a class.
*
* @author tap
*/
public class ChannelSuite implements DataListener {
static final public String DATA_LABEL = "channelsuite";
/** map of channels keyed by handle */
final private Map<String,Channel> CHANNEL_HANDLE_MAP;
/** channel factory for getting channels */
private ChannelFactory CHANNEL_FACTORY;
/** Signal Suite */
final private SignalSuite SIGNAL_SUITE;
/** Creates a new instance of ChannelSuite using the default channel factory */
public ChannelSuite() {
this( null );
}
/**
* Primary constructor for creating an instance of channel suite
* @param channelFactory channel factory (or null for default factory) for generating channels
*/
public ChannelSuite( final ChannelFactory channelFactory ) {
CHANNEL_FACTORY = channelFactory != null ? channelFactory : ChannelFactory.defaultFactory();
CHANNEL_HANDLE_MAP = new HashMap<String,Channel>();
SIGNAL_SUITE = new SignalSuite();
}
/** get the channel factory */
public ChannelFactory getChannelFactory() {
return CHANNEL_FACTORY;
}
/** set a new channel factory and clears the old channel map */
public void setChannelFactory(ChannelFactory channelFactory) {
CHANNEL_FACTORY = channelFactory;
CHANNEL_HANDLE_MAP.clear();
}
/**
* dataLabel() provides the name used to identify the class in an
* external data source.
* @return a tag that identifies the receiver's type
*/
public String dataLabel() { return DATA_LABEL; }
/**
* Update the data based on the information provided by the data provider.
* @param adaptor The adaptor from which to update the data
*/
public void update( final DataAdaptor adaptor ) {
SIGNAL_SUITE.update( adaptor );
}
/**
* Write data to the data adaptor for storage.
* @param adaptor The adaptor to which the receiver's data is written
*/
public void write( final DataAdaptor adaptor ) {
SIGNAL_SUITE.write( adaptor );
}
/**
* Programmatically add or replace a channel corresponding to the specified handle
* @param handle The handle referring to the signal
* @param signal PV signal associated with the handle
* @param settable indicates whether the channel is settable
* @param transformKey Key of the signal's transformation
* @param valid specifies whether the channel is marked valid
*/
public void putChannel( final String handle, final String signal, final boolean settable, final String transformKey, final boolean valid ) {
SIGNAL_SUITE.putChannel( handle, signal, settable, transformKey, valid );
}
/**
* Convenience method to programmatically add or replace a channel corresponding to the specified handle with valid set to true
* @param handle The handle referring to the signal
* @param signal PV signal associated with the handle
* @param settable indicates whether the channel is settable
* @param transformKey Key of the signal's transformation
*/
public void putChannel( final String handle, final String signal, final boolean settable, final String transformKey ) {
putChannel( handle, signal, settable, transformKey, true );
}
/**
* Convenience method to programmatically add or replace a channel corresponding to the specified handle with valid set to true and no transform
* @param handle The handle referring to the signal
* @param signal PV signal associated with the handle
* @param settable indicates whether the channel is settable
*/
public void putChannel( final String handle, final String signal, final boolean settable ) {
putChannel( handle, signal, settable, null );
}
/**
* Programmatically assign a transform for the specified name
* @param name key for associating the transform
* @param transform the value transform
*/
public void putTransform( final String name, final ValueTransform transform ) {
SIGNAL_SUITE.putTransform( name, transform );
}
/**
* See if this channel suite manages the specified signal.
* @param signal The PV signal to check for availability.
* @return true if the PV signal is available and false if not.
*/
protected boolean hasSignal( final String signal ) {
return SIGNAL_SUITE.hasSignal( signal );
}
/**
* See if this channel suite manages the specified handle.
* @param handle The handle to check for availability.
* @return true if the handle is available and false if not.
*/
final public boolean hasHandle( final String handle ) {
return SIGNAL_SUITE.hasHandle( handle );
}
/**
* Get all of the handles managed by the is channel suite.
* @return The handles managed by this channel suite.
*/
final public Collection<String> getHandles() {
return SIGNAL_SUITE.getHandles();
}
/**
* Get the channel signal corresponding to the handle.
* @param handle The handle for which to get the PV signal name.
* @return Get the PV signal name associated with the specified handle or null if it is not found.
*/
final public String getSignal( final String handle ) {
return SIGNAL_SUITE.getSignal( handle );
}
/**
* Get the transform associated with the specified handle.
* @param handle The handle for which to get the transform.
* @return The transform for the specified handle.
*/
final public ValueTransform getTransform( final String handle ) {
return SIGNAL_SUITE.getTransform( handle );
}
/**
* Determine whether the handle's corresponding PV is valid.
* @param handle The handle for which to get the validity.
* @return validity state of the PV or false if there is no entry for the handle
*/
final public boolean isValid( final String handle ) {
return SIGNAL_SUITE.isValid( handle );
}
/**
* Determine whether the handle's corresponding PV is settable.
* @param handle The handle for which to get the attribute.
* @return set parameter of the PV or false if there is no entry for the handle
*/
public boolean isSettable( final String handle ) {
return SIGNAL_SUITE.isSettable( handle );
}
/**
* Set settable property for the PV associated with the handle.
* @param handle The handle for which to set the settable property.
* @param settable Set parameter.
*/
public void setSettable( final String handle, final boolean settable ) {
SIGNAL_SUITE.setSettable( handle, settable );
}
/**
* Get the channel corresponding to the specified handle.
* @param handle The handle for which to get the associated Channel.
* @return The channel associated with the specified handle.
*/
public Channel getChannel( final String handle ) {
// first see if we have ever cached the channel
Channel channel = CHANNEL_HANDLE_MAP.get( handle );
if ( channel == null ) { // if the channel was never cached ...
final String signal = getSignal( handle ); // lookup the signal
if ( signal != null ) { // get the channel from the channel factory
final ValueTransform transform = getTransform( handle );
if ( transform != null ) {
channel = CHANNEL_FACTORY.getChannel( signal, transform );
}
else {
channel = CHANNEL_FACTORY.getChannel( signal );
}
channel.setValid( isValid( handle ) );
if (channel instanceof IServerChannel) {
((IServerChannel)channel).setSettable( SIGNAL_SUITE.isSettable(handle) );
}
}
// if we have a channel, cache it for future access
if ( channel != null ) {
CHANNEL_HANDLE_MAP.put( handle, channel );
}
}
return channel;
}
}
/**
* SignalSuite represents the map of handle/signal pairs that identifies a
* channel and associates it with a node via the handle.
*
* @author tap
*/
class SignalSuite {
/** hash set of handles that are settable by default */
final static private Set<String> SETTABLE_CHANNEL_HANDLES = new HashSet<>();
// assign the settable handles
static {
final String[] HANDLES = { "I_Set", "fieldSet", "cycleEnable", "cavAmpSet", "cavPhaseSet", "deltaTRFStart", "deltaTRFEnd", "tDelay", "blankBeam" };
for ( final String handle : HANDLES ) {
SETTABLE_CHANNEL_HANDLES.add( handle );
}
}
/** map of signal entries keyed by handle */
final private Map<String,SignalEntry> SIGNAL_MAP; // handle-PV name table
/** map of transforms keyed by name */
final private Map<String,ValueTransform> TRANSFORM_MAP; // handle-value transform table
/** Creates a new instance of SignalSuite */
public SignalSuite() {
SIGNAL_MAP = new HashMap<String,SignalEntry>();
TRANSFORM_MAP = new HashMap<String,ValueTransform>();
}
/** determine if the handle is a settable handle (fixed time lookup since using a Hash Set) */
private boolean isHandleSettable( final String handle ) {
return SETTABLE_CHANNEL_HANDLES.contains( handle );
}
/**
* Update the data based on the information provided by the data provider.
* @param adaptor The adaptor from which to update the data
*/
public void update( final DataAdaptor adaptor ) {
final List<DataAdaptor> channelAdaptors = adaptor.childAdaptors( "channel" );
for ( final DataAdaptor channelAdaptor : channelAdaptors ) {
final String handle = channelAdaptor.stringValue("handle");
if ( !hasHandle( handle ) ) {
SIGNAL_MAP.put( handle, new SignalEntry() );
}
final SignalEntry signalEntry = SIGNAL_MAP.get( handle );
final String signal = channelAdaptor.stringValue( "signal" );
if ( signal != null ) signalEntry.setSignal( signal );
// if the settable attribute is specified, then use its value otherwise fallback to the default settable handles lookup
if ( channelAdaptor.hasAttribute( "settable" ) ) {
final boolean settable = channelAdaptor.booleanValue( "settable" );
signalEntry.setSettable( settable );
} else if ( isHandleSettable( handle ) ) { // if settable is not explicitly specified, determine if the handle is settable by default
signalEntry.setSettable( true );
}
if ( channelAdaptor.hasAttribute( "valid" ) ) {
final boolean valid = channelAdaptor.booleanValue( "valid" );
signalEntry.setValid( valid );
}
if ( channelAdaptor.hasAttribute( "transform" ) ) {
final String transformKey = channelAdaptor.stringValue( "transform" );
signalEntry.setTransformKey( transformKey );
}
}
final List<DataAdaptor> transformAdaptors = adaptor.childAdaptors( "transform" );
for ( final DataAdaptor transformAdaptor : transformAdaptors ) {
final String name = transformAdaptor.stringValue( "name" );
final ValueTransform transform = TransformFactory.getTransform( transformAdaptor );
putTransform( name, transform );
}
}
/**
* Write data to the data adaptor for storage.
* @param adaptor The adaptor to which the receiver's data is written
*/
public void write( final DataAdaptor adaptor ) {
final Collection<Map.Entry<String,SignalEntry>> signalMapEntries = SIGNAL_MAP.entrySet();
for ( final Map.Entry<String,SignalEntry> entry : signalMapEntries ) {
final DataAdaptor channelAdaptor = adaptor.createChild("channel");
final SignalEntry signalEntry = entry.getValue();
channelAdaptor.setValue( "handle", entry.getKey() );
channelAdaptor.setValue( "signal", signalEntry.signal() );
channelAdaptor.setValue( "settable", signalEntry.settable() );
channelAdaptor.setValue( "valid", signalEntry.isValid() );
if ( signalEntry.getTransformKey() != null ) {
channelAdaptor.setValue( "transform", signalEntry.getTransformKey() );
}
}
}
/**
* Programmatically add or replace a signal entry corresponding to the specified handle
* @param handle The handle referring to the signal entry
* @param signal PV signal associated with the handle
* @param settable indicates whether the channel is settable
* @param transformKey Key of the signal's transformation
* @param valid specifies whether the channel is marked valid
*/
public void putChannel( final String handle, final String signal, final boolean settable, final String transformKey, final boolean valid ) {
final SignalEntry signalEntry = new SignalEntry( signal, settable, transformKey );
signalEntry.setValid( valid );
SIGNAL_MAP.put( handle, signalEntry );
}
/**
* Programmatically assign a transform for the specified name
* @param name key for associating the transform
* @param transform the value transform
*/
public void putTransform( final String name, final ValueTransform transform ) {
TRANSFORM_MAP.put( name, transform );
}
/**
* Check if this suite manages the specified PV signal.
* @param signal The PV signal name for which to check.
* @return true if this suite manages the specified signal and false otherwise.
*/
boolean hasSignal( final String signal ) {
for ( final SignalEntry entry : SIGNAL_MAP.values() ) {
if ( entry.signal().equals( signal ) ) return true;
}
return false;
}
/**
* Get the PV signal associated with the handle.
* @param handle The handle for which to get the associated PV signal.
* @return The signal associated with the specified handle.
*/
public String getSignal( final String handle ) {
final SignalEntry signalEntry = getSignalEntry( handle );
return signalEntry != null ? signalEntry.signal() : null;
}
/**
* Get all of the handles within this suite.
* @return The handles managed by this suite.
*/
public Collection<String> getHandles() {
return SIGNAL_MAP.keySet();
}
/**
* Check if the signal suite manages the handle.
* @param handle The handle for which to check availability.
* @return true if the handle is available and false otherwise.
*/
public boolean hasHandle( final String handle ) {
return SIGNAL_MAP.containsKey( handle );
}
/**
* Check if the signal entry associated with the specified handle has an
* associated value transform.
* @param handle The handle to check for an associated transform.
* @return true if the handle has an associated value transform and false otherwise.
*/
public boolean hasTransform( final String handle ) {
final SignalEntry signalEntry = getSignalEntry( handle );
return signalEntry != null ? ( signalEntry.getTransformKey() != null ) : false;
}
/**
* Get the transform associated with the specified handle.
* @param handle The handle for which to get the transform.
* @return The transform for the specified handle.
*/
public ValueTransform getTransform(String handle) {
final SignalEntry signalEntry = getSignalEntry( handle );
return signalEntry != null ? TRANSFORM_MAP.get( signalEntry.getTransformKey() ) : null;
}
/**
* Determine whether the handle's corresponding PV is valid.
* @param handle The handle for which to get the validity.
* @return validity state of the PV or false if there is no entry for the handle
*/
public boolean isValid( final String handle ) {
final SignalEntry signalEntry = getSignalEntry( handle );
return signalEntry != null ? signalEntry.isValid() : false;
}
/**
* Determine whether the handle's corresponding PV is settable.
* @param handle The handle for which to get the attribute.
* @return set parameter of the PV or false if there is no entry for the handle
*/
public boolean isSettable( final String handle ) {
final SignalEntry signalEntry = getSignalEntry( handle );
return signalEntry != null ? signalEntry.settable() : false;
}
/**
* Set settable property for the PV associated with the handle.
* @param handle The handle for which to set the settable property.
* @param settable Set parameter.
*/
public void setSettable(final String handle, final boolean settable) {
final SignalEntry signalEntry = getSignalEntry(handle);
if (signalEntry != null) {
signalEntry.setSettable(settable);
}
}
/**
* Get the signal entry for the handle.
* @param handle The handle for which to get the entry.
* @return signal entry for the handle or null if there is none
*/
private SignalEntry getSignalEntry( final String handle ) {
return SIGNAL_MAP.get( handle );
}
}
/**
* Entry in the signal map corresponding to a handle. In the signal map
* the key is a handle and the value is an instance of SignalEntry.
*/
class SignalEntry {
private String _signal; // the PV signal name
private boolean _settable; // whether the PV is settable
private boolean _valid; // whether the channel is marked valid
private String _transformkey; // Name of the transform if any
/** Primary Constructor */
public SignalEntry( final String signal, final boolean settable, final String transformKey ) {
_signal = signal;
_settable = settable;
_transformkey = transformKey;
_valid = true;
}
/** Constructor */
public SignalEntry() {
this( null, false, null );
}
/**
* Get whether the PV is settable or not.
* @return true if the PV is settable and false otherwise.
*/
public boolean settable() {
return _settable;
}
/** set the settable property */
public void setSettable( final boolean isSettable ) {
_settable = isSettable;
}
/** get the valid status of the PV */
public boolean isValid() {
return _valid;
}
/** mark the valid status of the PV */
public void setValid( final boolean isValid ) {
_valid = isValid;
}
/**
* Get the PV signal name.
* @return The PV signal name.
*/
public String signal() {
return _signal;
}
/** set the signal */
public void setSignal( final String signal ) {
_signal = signal;
}
/**
* Get the name of the associated transform used
* @return the name of the associated transform
*/
public String getTransformKey() {
return _transformkey;
}
/** set the transform key */
public void setTransformKey( final String transformKey ) {
_transformkey = transformKey;
}
}
|
package hudson.model;
import junit.framework.TestCase;
import java.util.GregorianCalendar;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class RunTest extends TestCase {
private List<? extends Run<?,?>.Artifact> createArtifactList(String... paths) {
Run<FreeStyleProject,FreeStyleBuild> r = new Run<FreeStyleProject,FreeStyleBuild>(null,new GregorianCalendar()) {};
Run<FreeStyleProject,FreeStyleBuild>.ArtifactList list = r.new ArtifactList();
for (String p : paths) {
list.add(r.new Artifact(p,p,p,"n"+list.size())); // Assuming all test inputs don't need urlencoding
}
list.computeDisplayName();
return list;
}
public void testArtifactListDisambiguation1() {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/j.xml");
assertEquals(a.get(0).getDisplayPath(),"c.xml");
assertEquals(a.get(1).getDisplayPath(),"g.xml");
assertEquals(a.get(2).getDisplayPath(),"j.xml");
}
public void testArtifactListDisambiguation2() {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/g.xml");
assertEquals(a.get(0).getDisplayPath(),"c.xml");
assertEquals(a.get(1).getDisplayPath(),"f/g.xml");
assertEquals(a.get(2).getDisplayPath(),"i/g.xml");
}
public void testArtifactListDisambiguation3() {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a.xml","a/a.xml");
assertEquals(a.get(0).getDisplayPath(),"a.xml");
assertEquals(a.get(1).getDisplayPath(),"a/a.xml");
}
}
|
// BatchGetRequestListener.java
// xal
package xal.ca;
/** interface for listeners of batch request events */
public interface BatchGetRequestListener<RecordType extends ChannelRecord> {
/**
* Event indicating that the batch request is complete
* @param request in which the event occurred
* @param recordCount number of records completed
* @param exceptionCount number of exceptions
*/
public void batchRequestCompleted( AbstractBatchGetRequest<RecordType> request, int recordCount, int exceptionCount );
/**
* Event indicating that an exception has been thrown for a channel
* @param request in which the event occurred
* @param channel for which the exception occured
* @param exception that occurred
*/
public void exceptionInBatch( AbstractBatchGetRequest<RecordType> request, Channel channel, Exception exception );
/**
* event indicating that a get event has been completed for a channel
* @param request in which the event occurred
* @param channel for which the record was received
* @param record which was received
*/
public void recordReceivedInBatch( AbstractBatchGetRequest<RecordType> request, Channel channel, RecordType record );
}
|
public class JavaVersionLibrary {
public static final String ROBOT_LIBRARY_VERSION = "1.0";
public Object kw() {
return null;
}
}
|
package carpentersblocks.block;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.IIcon;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import carpentersblocks.CarpentersBlocks;
import carpentersblocks.data.Torch;
import carpentersblocks.data.Torch.State;
import carpentersblocks.tileentity.TEBase;
import carpentersblocks.tileentity.TECarpentersTorch;
import carpentersblocks.util.BlockProperties;
import carpentersblocks.util.registry.BlockRegistry;
import carpentersblocks.util.registry.FeatureRegistry;
import carpentersblocks.util.registry.IconRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockCarpentersTorch extends BlockCoverable {
public BlockCarpentersTorch(Material material)
{
super(material);
}
@SideOnly(Side.CLIENT)
@Override
/**
* When this method is called, your block should register all the icons it needs with the given IconRegister. This
* is the only chance you get to register icons.
*/
public void registerBlockIcons(IIconRegister iconRegister)
{
IconRegistry.icon_torch_lit = iconRegister.registerIcon(CarpentersBlocks.MODID + ":" + "torch/torch_lit");
IconRegistry.icon_torch_head_smoldering = iconRegister.registerIcon(CarpentersBlocks.MODID + ":" + "torch/torch_head_smoldering");
IconRegistry.icon_torch_head_unlit = iconRegister.registerIcon(CarpentersBlocks.MODID + ":" + "torch/torch_head_unlit");
}
@SideOnly(Side.CLIENT)
@Override
/**
* Returns the icon on the side given the block metadata.
*/
public IIcon getIcon(int side, int metadata)
{
return IconRegistry.icon_torch_lit;
}
/**
* Called when block is activated (right-click), before normal processing resumes.
*/
@Override
protected void preOnBlockActivated(TEBase TE, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ, List<Boolean> altered, List<Boolean> decInv)
{
ItemStack itemStack = entityPlayer.getHeldItem();
if (itemStack != null && itemStack.getItem() instanceof ItemBlock) {
if (!Torch.getState(TE).equals(State.LIT)) {
Block block = BlockProperties.toBlock(itemStack);
if (block.equals(BlockRegistry.blockCarpentersTorch) || block.equals(Blocks.torch)) {
Torch.setState(TE, State.LIT);
altered.add(true);
}
}
}
}
@Override
/**
* Returns light value based on cover or side covers.
*/
public int getLightValue(IBlockAccess world, int x, int y, int z)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
int coverLight = super.getLightValue(world, x, y, z);
int torchLight = 0;
switch (Torch.getState(TE)) {
case LIT:
torchLight = 15;
break;
case SMOLDERING:
torchLight = 10;
break;
default: {}
}
return coverLight > torchLight ? coverLight : torchLight;
}
return super.getLightValue();
}
/**
* Returns a bounding box from the pool of bounding boxes (this means this box can change after the pool has been
* cleared to be reused)
*/
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4)
{
return null;
}
@Override
/**
* checks to see if you can place this block can be placed on that side of a block: BlockLever overrides
*/
public boolean canPlaceBlockOnSide(World world, int x, int y, int z, int side)
{
if (side > 0) {
ForgeDirection dir = ForgeDirection.getOrientation(side);
Block block = world.getBlock(x, y - 1, z);
return world.getBlock(x - dir.offsetX, y - dir.offsetY, z - dir.offsetZ).isSideSolid(world, x - dir.offsetX, y - dir.offsetY, z - dir.offsetZ, dir) || side == 1 && block != null && block.canPlaceTorchOnTop(world, x, y, z);
}
return false;
}
@Override
/**
* Called when a block is placed using its ItemBlock. Args: World, X, Y, Z, side, hitX, hitY, hitZ, block metadata
*/
public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata)
{
return side;
}
@Override
/**
* Called when the block is placed in the world.
*/
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLiving, ItemStack itemStack)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
int facing = world.getBlockMetadata(x, y, z);
Torch.setFacing(TE, facing);
Torch.setReady(TE);
}
super.onBlockPlacedBy(world, x, y, z, entityLiving, itemStack);
}
@Override
/**
* Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are
* their own) Args: x, y, z, neighbor blockID
*/
public void onNeighborBlockChange(World world, int x, int y, int z, Block block)
{
if (!world.isRemote) {
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null && Torch.isReady(TE) && !canPlaceBlockOnSide(world, x, y, z, Torch.getFacing(TE).ordinal())) {
dropBlockAsItem(world, x, y, z, 0, 0);
world.setBlockToAir(x, y, z);
}
}
super.onNeighborBlockChange(world, x, y, z, block);
}
/**
* Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. Args: world,
* x, y, z, startVec, endVec
*/
@Override
public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
ForgeDirection facing = Torch.getFacing(TE);
switch (facing) {
case NORTH:
setBlockBounds(0.5F - 0.15F, 0.2F, 1.0F - 0.15F * 2.0F, 0.5F + 0.15F, 0.8F, 1.0F);
break;
case SOUTH:
setBlockBounds(0.5F - 0.15F, 0.2F, 0.0F, 0.5F + 0.15F, 0.8F, 0.15F * 2.0F);
break;
case WEST:
setBlockBounds(1.0F - 0.15F * 2.0F, 0.2F, 0.5F - 0.15F, 1.0F, 0.8F, 0.5F + 0.15F);
break;
case EAST:
setBlockBounds(0.0F, 0.2F, 0.5F - 0.15F, 0.15F * 2.0F, 0.8F, 0.5F + 0.15F);
break;
default:
setBlockBounds(0.5F - 0.1F, 0.0F, 0.5F - 0.1F, 0.5F + 0.1F, 0.6F, 0.5F + 0.1F);
break;
}
}
return super.collisionRayTrace(world, x, y, z, startVec, endVec);
}
/**
* Ticks the block if it's been scheduled
*/
@Override
public void updateTick(World world, int x, int y, int z, Random random)
{
if (!world.isRemote) {
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
boolean barrierTop = world.isSideSolid(x, y + 1, z, ForgeDirection.UP) ||
world.isSideSolid(x, y + 1, z, ForgeDirection.DOWN);
boolean isWet = world.isRaining() &&
world.canBlockSeeTheSky(x, y, z) &&
world.getBiomeGenForCoords(x, z).rainfall > 0.0F &&
!barrierTop;
boolean canDropState = FeatureRegistry.enableTorchWeatherEffects;
switch (Torch.getState(TE))
{
case LIT:
if (canDropState && isWet) {
Torch.setState(TE, State.SMOLDERING);
}
break;
case SMOLDERING:
if (canDropState && isWet) {
Torch.setState(TE, State.UNLIT);
} else {
Torch.setState(TE, State.LIT);
}
break;
case UNLIT:
if (!canDropState || !isWet) {
Torch.setState(TE, State.SMOLDERING);
}
break;
default: {}
}
}
}
}
@Override
@SideOnly(Side.CLIENT)
/**
* A randomly called display update to be able to add particles or other items for display
*/
public void randomDisplayTick(World world, int x, int y, int z, Random random)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
State state = Torch.getState(TE);
if (!state.equals(State.UNLIT)) {
double[] headCoords = Torch.getHeadCoordinates(TE);
world.spawnParticle("smoke", headCoords[0], headCoords[1], headCoords[2], 0.0D, 0.0D, 0.0D);
if (state.equals(State.LIT)) {
world.spawnParticle("flame", headCoords[0], headCoords[1], headCoords[2], 0.0D, 0.0D, 0.0D);
}
}
}
}
@Override
public TileEntity createNewTileEntity(World world, int metadata)
{
return new TECarpentersTorch();
}
@Override
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return BlockRegistry.carpentersTorchRenderID;
}
}
|
// This file is part of Elveos.org.
// Elveos.org is free software: you can redistribute it and/or modify it
// option) any later version.
// Elveos.org is distributed in the hope that it will be useful, but WITHOUT
// more details.
package com.bloatit.data.queries;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import com.bloatit.data.DaoMember;
import com.bloatit.data.DaoTeam;
import com.bloatit.data.DaoUserContent;
import com.bloatit.data.SessionManager;
/**
* The Class DaoUserContentQuery is a generic way of querying for DaoUserContent
* using criterias.
*
* @param <T> the generic type
*/
public class DaoUserContentQuery<T extends DaoUserContent> extends DaoIdentifiableQuery<T> {
private static String CREATION_DATE = "creationDate";
private static String MEMBER = "member";
private static String MEMBER_LOGIN = "m.member";
private static String FILES = "files";
private static String IS_DELETED = "isDeleted";
private static String AS_TEAM = "asTeam";
/**
* Instantiates a new dao user content query.
*
* @param criteria the criteria to use for this query
*/
protected DaoUserContentQuery(final Criteria criteria) {
super(criteria);
criteria.createAlias("member", "m");
criteria.setReadOnly(true);
}
/**
* Instantiates a new dao user content query.
*/
public DaoUserContentQuery() {
this(SessionManager.getSessionFactory().getCurrentSession().createCriteria(DaoUserContent.class));
}
/**
* Group by member.
*/
public void groupByMember() {
add(Projections.groupProperty(MEMBER));
}
/**
* Group by as team.
*/
public void groupByAsTeam() {
add(Projections.groupProperty(AS_TEAM));
}
/**
* Order by member.
*
* @param order the order (ASC/DESC)
*/
public void orderByMember(final DaoAbstractQuery.OrderType order) {
if (order == OrderType.ASC) {
addOrder(Order.asc(MEMBER_LOGIN));
} else {
addOrder(Order.desc(MEMBER_LOGIN));
}
}
/**
* Order by as team.
*
* @param order the order (ASC/DESC)
*/
public void orderByAsTeam(final DaoAbstractQuery.OrderType order) {
if (order == OrderType.ASC) {
addOrder(Order.asc(AS_TEAM));
} else {
addOrder(Order.desc(AS_TEAM));
}
}
/**
* Order by creation date.
*
* @param order the order (ASC/DESC)
*/
public void orderByCreationDate(final OrderType order) {
if (order == OrderType.ASC) {
addOrder(Order.asc(CREATION_DATE));
} else {
addOrder(Order.desc(CREATION_DATE));
}
}
/**
* show Deleted content only.
*/
public void deletedOnly() {
add(Restrictions.eq(IS_DELETED, true));
SessionManager.getSessionFactory().getCurrentSession().disableFilter("usercontent.nonDeleted");
}
/**
* show Non deleted content only.
*/
public final void nonDeletedOnly() {
add(Restrictions.eq(IS_DELETED, false));
}
/**
* Show content without file
*/
public void withoutFile() {
add(Restrictions.isEmpty(FILES));
}
/**
* Show content with file.
*/
public void withFile() {
add(Restrictions.isNotEmpty(FILES));
}
/**
* Show content created as team.
*/
public void withAnyTeam() {
add(Restrictions.isNotNull(AS_TEAM));
}
/**
* Show content with no team
*/
public void withNoTeam() {
add(Restrictions.isNull(AS_TEAM));
}
/**
* Show content created from member.
*
* @param member the member
*/
public void fromMember(final DaoMember member) {
add(Restrictions.eq(MEMBER, member));
}
/**
* Show content created from team.
*
* @param team the team
*/
public void fromTeam(final DaoTeam team) {
add(Restrictions.eq(AS_TEAM, team));
}
}
|
package org.michaelbel.material.widget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import org.michaelbel.material.R;
import org.michaelbel.material.util.Utils;
import java.util.ArrayList;
@SuppressWarnings({"unused", "FieldCanBeLocal"})
public class ActionBar extends FrameLayout {
public static final int MENU_ICON = -1;
private ImageView mNavigationIconImageView;
private SimpleTextView mTitleTextView;
private SimpleTextView mSubtitleTextView;
private ActionBarMenu menu;
private @ColorInt int mTitleTextColor;
private @ColorInt int mSubtitleTextColor;
public static class ActionBarMenuOnItemClick {
public void onItemClick(int id) {}
public boolean canOpenMenu() {
return true;
}
}
private View actionModeTop;
private ActionBarMenu actionMode;
//private boolean occupyStatusBar = Build.VERSION.SDK_INT >= 21;
private boolean occupyStatusBar = false;
private boolean actionModeVisible;
private boolean addToContainer = true;
private boolean interceptTouches = true;
private int extraHeight;
private AnimatorSet actionModeAnimation;
private boolean allowOverlayTitle;
private CharSequence lastTitle;
private boolean castShadows = true;
protected boolean isSearchFieldVisible;
protected int itemsBackgroundColor;
private boolean isBackOverlayVisible;
public ActionBarMenuOnItemClick actionBarMenuOnItemClick;
public ActionBar(Context context) {
super(context);
initialize(context, null, 0);
}
public ActionBar(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context, attrs, 0);
}
public ActionBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context, attrs, defStyleAttr);
}
public void initialize(Context context, AttributeSet attrs, int defStyleAttr) {
this.setBackgroundColor(Utils.getAttrColor(context, R.attr.colorPrimary));
this.mTitleTextColor = ContextCompat.getColor(context, R.color.md_white);
this.mSubtitleTextColor = ContextCompat.getColor(context, R.color.md_white);
}
public SimpleTextView getTitleTextView() {
return mTitleTextView;
}
public SimpleTextView getSubtitleTextView() {
return mSubtitleTextView;
}
public ImageView getNavigationIconImageView() {
return mNavigationIconImageView;
}
public ActionBar setNavigationIcon(@DrawableRes Drawable resId) {
if (mNavigationIconImageView == null) {
createBackButtonImage();
}
mNavigationIconImageView.setVisibility(resId == null ? GONE : VISIBLE);
mNavigationIconImageView.setImageDrawable(resId);
if (resId instanceof BackDrawable) {
((BackDrawable) resId).setRotation(isActionModeShowed() ? 1 : 0, false);
}
return this;
}
public ActionBar setNavigationIcon(@DrawableRes int icon) {
setNavigationIcon(ContextCompat.getDrawable(getContext(), icon));
return this;
}
private void createBackButtonImage() {
if (mNavigationIconImageView != null) {
return;
}
mNavigationIconImageView = new ImageView(getContext());
mNavigationIconImageView.setScaleType(ImageView.ScaleType.CENTER);
mNavigationIconImageView.setBackgroundResource(Utils.selectableItemBackgroundBorderless(getContext()));
mNavigationIconImageView.setPadding(Utils.dp(getContext(), 1), 0, 0, 0);
addView(mNavigationIconImageView, LayoutHelper.makeFrame(getContext(), 54, 54, Gravity.START | Gravity.TOP));
mNavigationIconImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isSearchFieldVisible) {
closeSearchField();
return;
}
if (actionBarMenuOnItemClick != null) {
actionBarMenuOnItemClick.onItemClick(MENU_ICON);
}
}
});
}
public ActionBar setTitle(@NonNull CharSequence value) {
if (mTitleTextView == null) {
createTitleTextView();
}
if (mTitleTextView != null) {
lastTitle = value;
mTitleTextView.setVisibility(!isSearchFieldVisible ? VISIBLE : INVISIBLE);
mTitleTextView.setText(value);
}
return this;
}
public ActionBar setTitle(@StringRes int stringId) {
setTitle(getContext().getText(stringId));
return this;
}
private void createTitleTextView() {
if (mTitleTextView != null) {
return;
}
mTitleTextView = new SimpleTextView(getContext());
mTitleTextView.setGravity(Gravity.START);
mTitleTextView.setTextColor(mTitleTextColor);
mTitleTextView.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
params.gravity = Gravity.START | Gravity.TOP;
addView(mTitleTextView, 0, params);
}
public ActionBar setSubtitle(@NonNull CharSequence value) {
if (mSubtitleTextView == null) {
createSubtitleTextView();
}
if (mSubtitleTextView != null) {
mSubtitleTextView.setVisibility(!isSearchFieldVisible ? VISIBLE : INVISIBLE);
mSubtitleTextView.setText(value);
}
return this;
}
public ActionBar setSubtitle(@StringRes int stringId) {
setSubtitle(getContext().getText(stringId));
return this;
}
private void createSubtitleTextView() {
if (mSubtitleTextView != null) {
return;
}
mSubtitleTextView = new SimpleTextView(getContext());
mSubtitleTextView.setGravity(Gravity.START);
mSubtitleTextView.setTextColor(mSubtitleTextColor);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
params.gravity = Gravity.START | Gravity.TOP;
addView(mSubtitleTextView, 0, params);
}
@NonNull
public String getTitle() {
return mTitleTextView.getText().toString();
}
@NonNull
public String getSubtitle() {
return mSubtitleTextView.getText().toString();
}
public ActionBarMenu createMenu() {
if (menu != null) {
return menu;
}
menu = new ActionBarMenu(getContext(), this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT
);
params.gravity = Gravity.END;
addView(menu, 0, params);
//addLayout(menu, 0, LayoutHelper.makeFrame(getContext(), LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT));
return menu;
}
public void setActionBarMenuOnItemClick(ActionBarMenuOnItemClick listener) {
actionBarMenuOnItemClick = listener;
}
public int getActionBarHeight() {
if (Utils.isTablet(getContext())) {
return Utils.dp(getContext(), 64);
} else if (Utils.isLandscape(getContext())) {
return Utils.dp(getContext(), 48);
} else {
return Utils.dp(getContext(), 56);
}
}
public int getActionBarHeightPx() {
if (Utils.isTablet(getContext())) {
return 64;
} else if (Utils.isLandscape(getContext())) {
return 48;
} else {
return 56;
}
}
public ActionBar setTitleTextColor(@ColorInt int color) {
this.mTitleTextColor = color;
return this;
}
@ColorInt
public int getTitleTextColor() {
return mTitleTextColor;
}
public ActionBar setSubtitleTextColor(@ColorInt int color) {
this.mSubtitleTextColor = color;
return this;
}
@ColorInt
public int getSubtitleTextColor() {
return mSubtitleTextColor;
}
public void setAddToContainer(boolean value) {
addToContainer = value;
}
public boolean getAddToContainer() {
return addToContainer;
}
public ActionBarMenu createActionMode() {
if (actionMode != null) {
return actionMode;
}
actionMode = new ActionBarMenu(getContext(), this);
actionMode.setBackgroundColor(0xFFFFFFFF);
addView(actionMode, indexOfChild(mNavigationIconImageView));
actionMode.setPadding(0, occupyStatusBar ? Utils.getStatusBarHeight(getContext()) : 0, 0, 0);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionMode.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.gravity = Gravity.END;
actionMode.setLayoutParams(layoutParams);
actionMode.setVisibility(INVISIBLE);
if (occupyStatusBar && actionModeTop == null) {
actionModeTop = new View(getContext());
actionModeTop.setBackgroundColor(0x99000000);
addView(actionModeTop);
layoutParams = (FrameLayout.LayoutParams)actionModeTop.getLayoutParams();
layoutParams.height = Utils.getStatusBarHeight(getContext());
layoutParams.width = LayoutHelper.MATCH_PARENT;
layoutParams.gravity = Gravity.TOP | Gravity.START;
actionModeTop.setLayoutParams(layoutParams);
actionModeTop.setVisibility(INVISIBLE);
}
return actionMode;
}
public void showActionMode() {
if (actionMode == null || actionModeVisible) {
return;
}
actionModeVisible = true;
ArrayList<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(actionMode, "alpha", 0.0F, 1.0F));
if (occupyStatusBar && actionModeTop != null) {
animators.add(ObjectAnimator.ofFloat(actionModeTop, "alpha", 0.0F, 1.0F));
}
if (actionModeAnimation != null) {
actionModeAnimation.cancel();
}
actionModeAnimation = new AnimatorSet();
actionModeAnimation.playTogether(animators);
actionModeAnimation.setDuration(200);
actionModeAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
actionMode.setVisibility(VISIBLE);
if (occupyStatusBar && actionModeTop != null) {
actionModeTop.setVisibility(VISIBLE);
}
}
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (actionModeAnimation != null && actionModeAnimation.equals(animation)) {
actionModeAnimation = null;
if (mTitleTextView != null) {
mTitleTextView.setVisibility(INVISIBLE);
}
if (mSubtitleTextView != null) {
mSubtitleTextView.setVisibility(INVISIBLE);
}
if (menu != null) {
menu.setVisibility(INVISIBLE);
}
}
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
if (actionModeAnimation != null && actionModeAnimation.equals(animation)) {
actionModeAnimation = null;
}
}
});
actionModeAnimation.start();
if (mNavigationIconImageView != null) {
Drawable drawable = mNavigationIconImageView.getDrawable();
if (drawable instanceof BackDrawable) {
((BackDrawable) drawable).setRotation(1, true);
}
mNavigationIconImageView.setBackgroundResource(Utils.selectableItemBackgroundBorderless(getContext()));
}
}
public void hideActionMode() {
if (actionMode == null || !actionModeVisible) {
return;
}
actionModeVisible = false;
ArrayList<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(actionMode, "alpha", 0.0f));
if (occupyStatusBar && actionModeTop != null) {
animators.add(ObjectAnimator.ofFloat(actionModeTop, "alpha", 0.0f));
}
if (actionModeAnimation != null) {
actionModeAnimation.cancel();
}
actionModeAnimation = new AnimatorSet();
actionModeAnimation.playTogether(animators);
actionModeAnimation.setDuration(200);
actionModeAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (actionModeAnimation != null && actionModeAnimation.equals(animation)) {
actionModeAnimation = null;
actionMode.setVisibility(INVISIBLE);
if (occupyStatusBar && actionModeTop != null) {
actionModeTop.setVisibility(INVISIBLE);
}
}
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
if (actionModeAnimation != null && actionModeAnimation.equals(animation)) {
actionModeAnimation = null;
}
}
});
actionModeAnimation.start();
if (mTitleTextView != null) {
mTitleTextView.setVisibility(VISIBLE);
}
if (mSubtitleTextView != null) {
mSubtitleTextView.setVisibility(VISIBLE);
}
if (menu != null) {
menu.setVisibility(VISIBLE);
}
if (mNavigationIconImageView != null) {
Drawable drawable = mNavigationIconImageView.getDrawable();
if (drawable instanceof BackDrawable) {
((BackDrawable) drawable).setRotation(0, true);
}
mNavigationIconImageView.setBackgroundResource(Utils.selectableItemBackgroundBorderless(getContext()));
}
}
public void showActionModeTop() {
if (occupyStatusBar && actionModeTop == null) {
actionModeTop = new View(getContext());
actionModeTop.setBackgroundColor(0x99000000);
addView(actionModeTop);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionModeTop.getLayoutParams();
layoutParams.height = Utils.getStatusBarHeight(getContext());
layoutParams.width = LayoutHelper.MATCH_PARENT;
layoutParams.gravity = Gravity.TOP | Gravity.START;
actionModeTop.setLayoutParams(layoutParams);
}
}
public boolean isActionModeShowed() {
return actionMode != null && actionModeVisible;
}
protected void onSearchFieldVisibilityChanged(boolean visible) {
isSearchFieldVisible = visible;
if (mTitleTextView != null) {
mTitleTextView.setVisibility(visible ? INVISIBLE : VISIBLE);
}
if (mSubtitleTextView != null) {
mSubtitleTextView.setVisibility(visible ? INVISIBLE : VISIBLE);
}
Drawable drawable = mNavigationIconImageView.getDrawable();
if (drawable != null && drawable instanceof MenuDrawable) {
((MenuDrawable) drawable).setRotation(visible ? 1 : 0, true);
}
}
public void setInterceptTouches(boolean value) {
interceptTouches = value;
}
public void setExtraHeight(int value) {
extraHeight = value;
}
public void closeSearchField() {
if (!isSearchFieldVisible || menu == null) {
return;
}
menu.closeSearchField();
}
public void openSearchField(String text) {
if (menu == null || text == null) {
return;
}
menu.openSearchField(!isSearchFieldVisible, text);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int actionBarHeight = getActionBarHeight();
int actionBarHeightSpec = MeasureSpec.makeMeasureSpec(actionBarHeight, MeasureSpec.EXACTLY);
setMeasuredDimension(width, actionBarHeight + (occupyStatusBar ? Utils.getStatusBarHeight(getContext()) : 0) + extraHeight);
int textLeft;
if (mNavigationIconImageView != null && mNavigationIconImageView.getVisibility() != GONE) {
mNavigationIconImageView.measure(MeasureSpec.makeMeasureSpec(Utils.dp(getContext(), 54), MeasureSpec.EXACTLY), actionBarHeightSpec);
textLeft = Utils.dp(getContext(), Utils.isTablet() ? 80 : 72);
} else {
textLeft = Utils.dp(getContext(), Utils.isTablet() ? 26 : 18);
}
if (menu != null && menu.getVisibility() != GONE) {
int menuWidth;
if (isSearchFieldVisible) {
menuWidth = MeasureSpec.makeMeasureSpec(width - Utils.dp(getContext(), Utils.isTablet() ? 74 : 66), MeasureSpec.EXACTLY);
} else {
menuWidth = MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST);
}
menu.measure(menuWidth, actionBarHeightSpec);
}
if (mTitleTextView != null && mTitleTextView.getVisibility() != GONE || mSubtitleTextView != null && mSubtitleTextView.getVisibility() != GONE) {
int availableWidth = width - (menu != null ? menu.getMeasuredWidth() : 0) - Utils.dp(getContext(), 16) - textLeft;
if (mTitleTextView != null && mTitleTextView.getVisibility() != GONE) {
mTitleTextView.setTextSize(!Utils.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 18 : 20);
mTitleTextView.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(Utils.dp(getContext(), 24), MeasureSpec.AT_MOST));
}
if (mSubtitleTextView != null && mSubtitleTextView.getVisibility() != GONE) {
mSubtitleTextView.setTextSize(!Utils.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 14 : 16);
mSubtitleTextView.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(Utils.dp(getContext(), 20), MeasureSpec.AT_MOST));
}
}
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() == GONE || child == mTitleTextView || child == mSubtitleTextView || child == menu || child == mNavigationIconImageView) {
continue;
}
measureChildWithMargins(child, widthMeasureSpec, 0, MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY), 0);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int additionalTop = occupyStatusBar ? Utils.getStatusBarHeight(getContext()) : 0;
int textLeft;
if (mNavigationIconImageView != null && mNavigationIconImageView.getVisibility() != GONE) {
mNavigationIconImageView.layout(0, additionalTop, mNavigationIconImageView.getMeasuredWidth(), additionalTop + mNavigationIconImageView.getMeasuredHeight());
textLeft = Utils.dp(getContext(), Utils.isTablet() ? 80 : 72);
} else {
textLeft = Utils.dp(getContext(), Utils.isTablet() ? 26 : 18);
}
if (menu != null && menu.getVisibility() != GONE) {
int menuLeft = isSearchFieldVisible ? Utils.dp(getContext(), Utils.isTablet() ? 74 : 66) : (right - left) - menu.getMeasuredWidth();
menu.layout(menuLeft, additionalTop, menuLeft + menu.getMeasuredWidth(), additionalTop + menu.getMeasuredHeight());
}
if (mTitleTextView != null && mTitleTextView.getVisibility() != GONE) {
int textTop;
if (mSubtitleTextView != null && mSubtitleTextView.getVisibility() != GONE) {
textTop = (getActionBarHeight() / 2 - mTitleTextView.getTextHeight()) / 2 + Utils.dp(getContext(), !Utils.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 2 : 3);
} else {
textTop = (getActionBarHeight() - mTitleTextView.getTextHeight()) / 2;
}
mTitleTextView.layout(textLeft, additionalTop + textTop, textLeft + mTitleTextView.getMeasuredWidth(), additionalTop + textTop + mTitleTextView.getTextHeight());
}
if (mSubtitleTextView != null && mSubtitleTextView.getVisibility() != GONE) {
int textTop = getActionBarHeight() / 2 + (getActionBarHeight() / 2 - mSubtitleTextView.getTextHeight()) / 2 - Utils.dp(getContext(), !Utils.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 1 : 1);
mSubtitleTextView.layout(textLeft, additionalTop + textTop, textLeft + mSubtitleTextView.getMeasuredWidth(), additionalTop + textTop + mSubtitleTextView.getTextHeight());
}
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() == GONE || child == mTitleTextView || child == mSubtitleTextView || child == menu || child == mNavigationIconImageView) {
continue;
}
LayoutParams lp = (LayoutParams) child.getLayoutParams();
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.START;
}
final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = (right - left - width) / 2 + lp.leftMargin - lp.rightMargin;
break;
case Gravity.END:
childLeft = right - width - lp.rightMargin;
break;
case Gravity.START:
default:
childLeft = lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = lp.topMargin;
break;
case Gravity.CENTER_VERTICAL:
childTop = (bottom - top - height) / 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = (bottom - top) - height - lp.bottomMargin;
break;
default:
childTop = lp.topMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
public void onMenuButtonPressed() {
if (menu != null) {
menu.onMenuButtonPressed();
}
}
protected void onPause() {
if (menu != null) {
menu.hideAllPopupMenus();
}
}
public void setAllowOverlayTitle(boolean value) {
allowOverlayTitle = value;
}
public void setTitleOverlayText(String text) {
if (!allowOverlayTitle) {
return;
}
CharSequence textToSet = text != null ? text : lastTitle;
if (textToSet != null && mTitleTextView == null) {
createTitleTextView();
}
if (mTitleTextView != null) {
mTitleTextView.setVisibility(textToSet != null && !isSearchFieldVisible ? VISIBLE : INVISIBLE);
mTitleTextView.setText(textToSet);
}
}
public boolean isSearchFieldVisible() {
return isSearchFieldVisible;
}
public void setOccupyStatusBar(boolean value) {
occupyStatusBar = value;
if (actionMode != null) {
actionMode.setPadding(0, occupyStatusBar ? Utils.getStatusBarHeight(getContext()) : 0, 0, 0);
}
}
public boolean getOccupyStatusBar() {
return occupyStatusBar;
}
public void setItemsBackgroundColor(int color) {
itemsBackgroundColor = color;
if (mNavigationIconImageView != null) {
mNavigationIconImageView.setBackgroundResource(Utils.selectableItemBackgroundBorderless(getContext()));
}
}
public void setCastShadows(boolean value) {
castShadows = value;
}
public boolean getCastShadows() {
return castShadows;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event) || interceptTouches;
}
@Override
public boolean hasOverlappingRendering() {
return false;
}
public static class BackDrawable extends Drawable {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean reverseAngle = false;
private long lastFrameTime;
private boolean animationInProgress;
private float finalRotation;
private float currentRotation;
private int currentAnimationTime;
private boolean alwaysClose;
private DecelerateInterpolator interpolator = new DecelerateInterpolator();
private Context context;
public BackDrawable(Context context, boolean close) {
super();
this.context = context;
paint.setColor(0xFFFFFFFF);
paint.setStrokeWidth(Utils.dp(context, 2));
alwaysClose = close;
}
public void setRotation(float rotation, boolean animated) {
lastFrameTime = 0;
if (currentRotation == 1) {
reverseAngle = true;
} else if (currentRotation == 0) {
reverseAngle = false;
}
lastFrameTime = 0;
if (animated) {
if (currentRotation < rotation) {
currentAnimationTime = (int) (currentRotation * 300);
} else {
currentAnimationTime = (int) ((1.0f - currentRotation) * 300);
}
lastFrameTime = System.currentTimeMillis();
finalRotation = rotation;
} else {
finalRotation = currentRotation = rotation;
}
invalidateSelf();
}
@Override
public void draw(Canvas canvas) {
if (currentRotation != finalRotation) {
if (lastFrameTime != 0) {
long dt = System.currentTimeMillis() - lastFrameTime;
currentAnimationTime += dt;
if (currentAnimationTime >= 300) {
currentRotation = finalRotation;
} else {
if (currentRotation < finalRotation) {
currentRotation = interpolator.getInterpolation(currentAnimationTime / 300.0f) * finalRotation;
} else {
currentRotation = 1.0f - interpolator.getInterpolation(currentAnimationTime / 300.0f);
}
}
}
lastFrameTime = System.currentTimeMillis();
invalidateSelf();
}
int rD = (int) ((117 - 255) * currentRotation);
int c = Color.rgb(255 + rD, 255 + rD, 255 + rD);
paint.setColor(c);
canvas.save();
canvas.translate(getIntrinsicWidth() / 2, getIntrinsicHeight() / 2);
float rotation = currentRotation;
if (!alwaysClose) {
canvas.rotate(currentRotation * (reverseAngle ? -225 : 135));
} else {
canvas.rotate(135 + currentRotation * (reverseAngle ? -180 : 180));
rotation = 1.0f;
}
canvas.drawLine(-Utils.dp(context, 7) - Utils.dp(context, 1) * rotation, 0, Utils.dp(context, 8), 0, paint);
float startYDiff = -Utils.dp(context, 0.5f);
float endYDiff = Utils.dp(context, 7) + Utils.dp(context, 1) * rotation;
float startXDiff = -Utils.dp(context, 7.0f) + Utils.dp(context, 7.0f) * rotation;
float endXDiff = Utils.dp(context, 0.5f) - Utils.dp(context, 0.5f) * rotation;
canvas.drawLine(startXDiff, -startYDiff, endXDiff, -endYDiff, paint);
canvas.drawLine(startXDiff, startYDiff, endXDiff, endYDiff, paint);
canvas.restore();
}
@Override
public void setAlpha(int alpha) {}
@Override
public void setColorFilter(ColorFilter cf) {}
@Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
@Override
public int getIntrinsicWidth() {
return Utils.dp(context, 24);
}
@Override
public int getIntrinsicHeight() {
return Utils.dp(context, 24);
}
}
public class MenuDrawable extends Drawable {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean reverseAngle = false;
private long lastFrameTime;
private boolean animationInProgress;
private float finalRotation;
private float currentRotation;
private int currentAnimationTime;
private DecelerateInterpolator interpolator = new DecelerateInterpolator();
public MenuDrawable() {
super();
paint.setColor(0xFFFFFFFF);
paint.setStrokeWidth(Utils.dp(getContext(), 2));
}
public void setRotation(float rotation, boolean animated) {
lastFrameTime = 0;
if (currentRotation == 1) {
reverseAngle = true;
} else if (currentRotation == 0) {
reverseAngle = false;
}
lastFrameTime = 0;
if (animated) {
if (currentRotation < rotation) {
currentAnimationTime = (int) (currentRotation * 300);
} else {
currentAnimationTime = (int) ((1.0f - currentRotation) * 300);
}
lastFrameTime = System.currentTimeMillis();
finalRotation = rotation;
} else {
finalRotation = currentRotation = rotation;
}
invalidateSelf();
}
@Override
public void draw(Canvas canvas) {
if (currentRotation != finalRotation) {
if (lastFrameTime != 0) {
long dt = System.currentTimeMillis() - lastFrameTime;
currentAnimationTime += dt;
if (currentAnimationTime >= 300) {
currentRotation = finalRotation;
} else {
if (currentRotation < finalRotation) {
currentRotation = interpolator.getInterpolation(currentAnimationTime / 300.0f) * finalRotation;
} else {
currentRotation = 1.0f - interpolator.getInterpolation(currentAnimationTime / 300.0f);
}
}
}
lastFrameTime = System.currentTimeMillis();
invalidateSelf();
}
canvas.save();
canvas.translate(getIntrinsicWidth() / 2, getIntrinsicHeight() / 2);
canvas.rotate(currentRotation * (reverseAngle ? -180 : 180));
canvas.drawLine(-Utils.dp(getContext(), 9), 0, Utils.dp(getContext(), 9) - Utils.dp(getContext(), 3.0f) * currentRotation, 0, paint);
float endYDiff = Utils.dp(getContext(), 5) * (1 - Math.abs(currentRotation)) - Utils.dp(getContext(), 0.5f) * Math.abs(currentRotation);
float endXDiff = Utils.dp(getContext(), 9) - Utils.dp(getContext(), 2.5f) * Math.abs(currentRotation);
float startYDiff = Utils.dp(getContext(), 5) + Utils.dp(getContext(), 2.0f) * Math.abs(currentRotation);
float startXDiff = -Utils.dp(getContext(), 9) + Utils.dp(getContext(), 7.5f) * Math.abs(currentRotation);
canvas.drawLine(startXDiff, -startYDiff, endXDiff, -endYDiff, paint);
canvas.drawLine(startXDiff, startYDiff, endXDiff, endYDiff, paint);
canvas.restore();
}
@Override
public void setAlpha(int alpha) {}
@Override
public void setColorFilter(ColorFilter cf) {}
@Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
@Override
public int getIntrinsicWidth() {
return Utils.dp(getContext(), 24);
}
@Override
public int getIntrinsicHeight() {
return Utils.dp(getContext(), 24);
}
}
}
|
package org.mini2Dx.ui;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.mini2Dx.core.Mdx;
import org.mini2Dx.core.controller.button.ControllerButton;
import org.mini2Dx.core.game.GameContainer;
import org.mini2Dx.core.graphics.Graphics;
import org.mini2Dx.ui.controller.ControllerUiInput;
import org.mini2Dx.ui.element.Actionable;
import org.mini2Dx.ui.element.Navigatable;
import org.mini2Dx.ui.element.ParentUiElement;
import org.mini2Dx.ui.element.UiElement;
import org.mini2Dx.ui.element.Visibility;
import org.mini2Dx.ui.event.EventTrigger;
import org.mini2Dx.ui.event.params.ControllerEventTriggerParams;
import org.mini2Dx.ui.event.params.EventTriggerParamsPool;
import org.mini2Dx.ui.event.params.KeyboardEventTriggerParams;
import org.mini2Dx.ui.event.params.MouseEventTriggerParams;
import org.mini2Dx.ui.layout.ScreenSize;
import org.mini2Dx.ui.listener.ScreenSizeListener;
import org.mini2Dx.ui.listener.UiContainerListener;
import org.mini2Dx.ui.navigation.UiNavigation;
import org.mini2Dx.ui.render.ActionableRenderNode;
import org.mini2Dx.ui.render.NodeState;
import org.mini2Dx.ui.render.ParentRenderNode;
import org.mini2Dx.ui.render.RenderNode;
import org.mini2Dx.ui.render.TextInputableRenderNode;
import org.mini2Dx.ui.render.UiContainerRenderTree;
import org.mini2Dx.ui.style.UiTheme;
import org.mini2Dx.ui.util.IdAllocator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.math.MathUtils;
/**
* The container for all UI elements. {@link #update(float)},
* {@link #interpolate(float)} and {@link #render(Graphics)} must be called by
* your {@link GameContainer}
*/
public class UiContainer extends ParentUiElement implements InputProcessor {
private static final String LOGGING_TAG = UiContainer.class.getSimpleName();
private static Visibility defaultVisibility = Visibility.HIDDEN;
private final List<ControllerUiInput<?>> controllerInputs = new ArrayList<ControllerUiInput<?>>(1);
private final List<UiContainerListener> listeners = new ArrayList<UiContainerListener>(1);
private final Set<Integer> receivedKeyDowns = new HashSet<Integer>();
private final Set<String> receivedButtonDowns = new HashSet<String>();
private final UiContainerRenderTree renderTree;
private InputSource lastInputSource;
private int width, height;
private int lastMouseX, lastMouseY;
private float scaleX = 1f;
private float scaleY = 1f;
private boolean themeWarningIssued, initialThemeLayoutComplete;
private UiTheme theme;
private int actionKey = Keys.ENTER;
private Navigatable activeNavigation;
private ActionableRenderNode activeAction;
private TextInputableRenderNode activeTextInput;
private boolean keyboardNavigationEnabled = false;
private boolean textInputIgnoredFirstEnter = false;
/**
* Constructor
*
* @param gc
* Your game's {@link GameContainer}
* @param assetManager
* The {@link AssetManager} for the game
*/
public UiContainer(GameContainer gc, AssetManager assetManager) {
super(IdAllocator.getNextId("ui-container-root"));
this.width = gc.getWidth();
this.height = gc.getHeight();
switch (Mdx.os) {
case ANDROID:
case IOS:
lastInputSource = InputSource.TOUCHSCREEN;
break;
case MAC:
case UNIX:
case WINDOWS:
lastInputSource = InputSource.KEYBOARD_MOUSE;
break;
default:
break;
}
renderTree = new UiContainerRenderTree(this, assetManager);
super.renderNode = renderTree;
setVisibility(Visibility.VISIBLE);
}
@Override
protected ParentRenderNode<?, ?> createRenderNode(ParentRenderNode<?, ?> parent) {
return renderTree;
}
/**
* Updates all {@link UiElement}s
*
* @param delta
* The time since the last frame (in seconds)
*/
public void update(float delta) {
if (!isThemeApplied()) {
if (!themeWarningIssued) {
Gdx.app.error(LOGGING_TAG, "No theme applied to UI - cannot update or render UI.");
themeWarningIssued = true;
}
return;
}
notifyPreUpdate(delta);
for (int i = controllerInputs.size() - 1; i >= 0; i
controllerInputs.get(i).update(delta);
}
if (renderTree.isDirty()) {
renderTree.layout();
initialThemeLayoutComplete = true;
}
renderTree.update(delta);
notifyPostUpdate(delta);
}
/**
* Interpolates all {@link UiElement}s
*
* @param alpha
* The interpolation alpha
*/
public void interpolate(float alpha) {
if (!isThemeApplied()) {
return;
}
notifyPreInterpolate(alpha);
renderTree.interpolate(alpha);
notifyPostInterpolate(alpha);
}
/**
* Renders all visible {@link UiElement}s
*
* @param g
* The {@link Graphics} context
*/
public void render(Graphics g) {
if (!isThemeApplied()) {
return;
}
if (!initialThemeLayoutComplete) {
return;
}
notifyPreRender(g);
switch (visibility) {
case HIDDEN:
return;
case NO_RENDER:
return;
default:
float previousScaleX = g.getScaleX();
float previousScaleY = g.getScaleY();
if (scaleX != 1f || scaleY != 1f) {
g.setScale(scaleX, scaleY);
}
renderTree.render(g);
if (scaleX != 1f || scaleY != 1f) {
g.setScale(previousScaleX, previousScaleY);
}
break;
}
notifyPostRender(g);
}
@Override
public void attach(ParentRenderNode<?, ?> parentRenderNode) {
}
@Override
public void detach(ParentRenderNode<?, ?> parentRenderNode) {
}
@Override
public void setVisibility(Visibility visibility) {
this.visibility = visibility;
}
/**
* Adds a {@link ScreenSizeListener} to listen for {@link ScreenSize} change
*
* @param listener
* The {@link ScreenSizeListener} to add
*/
public void addScreenSizeListener(ScreenSizeListener listener) {
renderTree.addScreenSizeListener(listener);
}
/**
* Removes a {@link ScreenSizeListener} from this {@link UiContainer}
*
* @param listener
* The {@link ScreenSizeListener} to remove
*/
public void removeScreenSizeListener(ScreenSizeListener listener) {
renderTree.removeScreenSizeListener(listener);
}
/**
* Returns if a {@link UiTheme} has been applied to thi {@link UiContainer}
*
* @return True if the {@link UiTheme} has been applied
*/
public boolean isThemeApplied() {
return theme != null;
}
/**
* Returns the {@link UiTheme} currently applied to this {@link UiContainer}
*
* @return Null if no {@link UiTheme} has been applied
*/
public UiTheme getTheme() {
return theme;
}
/**
* Sets the current {@link UiTheme} for this {@link UiContainer}
*
* @param theme
* The {@link UiTheme} to apply
*/
public void setTheme(UiTheme theme) {
if (theme == null) {
return;
}
if (this.theme != null && theme.equals(this.theme)) {
return;
}
this.theme = theme;
renderTree.setDirty(true);
initialThemeLayoutComplete = false;
Gdx.app.log(LOGGING_TAG, "Applied theme - " + theme.getId());
}
@Override
public void setStyleId(String styleId) {
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if(keyNavigationInUse()) {
return false;
}
screenX = MathUtils.round(screenX / scaleX);
screenY = MathUtils.round(screenY / scaleY);
lastMouseX = screenX;
lastMouseY = screenY;
if (activeTextInput != null && activeTextInput.mouseDown(screenX, screenY, pointer, button) == null) {
// Release textbox control
activeTextInput = null;
activeAction = null;
switch(Mdx.os) {
case ANDROID:
case IOS:
Gdx.input.setOnscreenKeyboardVisible(false);
break;
default:
break;
}
}
ActionableRenderNode result = renderTree.mouseDown(screenX, screenY, pointer, button);
if (result != null) {
MouseEventTriggerParams params = EventTriggerParamsPool.allocateMouseParams();
params.setMouseX(screenX);
params.setMouseY(screenY);
result.beginAction(EventTrigger.getTriggerForMouseClick(button), params);
EventTriggerParamsPool.release(params);
setActiveAction(result);
return true;
}
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if(keyNavigationInUse()) {
return false;
}
screenX = MathUtils.round(screenX / scaleX);
screenY = MathUtils.round(screenY / scaleY);
lastMouseX = screenX;
lastMouseY = screenY;
if (activeAction == null) {
return false;
}
activeAction.mouseUp(screenX, screenY, pointer, button);
activeAction = null;
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
if(keyNavigationInUse()) {
return false;
}
screenX = MathUtils.round(screenX / scaleX);
screenY = MathUtils.round(screenY / scaleY);
lastMouseX = screenX;
lastMouseY = screenY;
return renderTree.mouseMoved(screenX, screenY);
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
if(keyNavigationInUse()) {
return false;
}
screenX = MathUtils.round(screenX / scaleX);
screenY = MathUtils.round(screenY / scaleY);
lastMouseX = screenX;
lastMouseY = screenY;
return renderTree.mouseMoved(screenX, screenY);
}
@Override
public boolean scrolled(int amount) {
if(keyNavigationInUse()) {
return false;
}
return renderTree.mouseScrolled(lastMouseX, lastMouseY, amount);
}
@Override
public boolean keyTyped(char character) {
if (activeTextInput == null) {
return false;
}
if (activeTextInput.isReceivingInput()) {
activeTextInput.characterReceived(character);
}
return true;
}
@Override
public boolean keyDown(int keycode) {
receivedKeyDowns.add(keycode);
if (activeTextInput != null && activeTextInput.isReceivingInput()) {
return true;
}
if (keycode == actionKey && activeAction != null) {
KeyboardEventTriggerParams params = EventTriggerParamsPool.allocateKeyboardParams();
params.setKey(keycode);
activeAction.beginAction(EventTrigger.KEYBOARD, params);
EventTriggerParamsPool.release(params);
if (activeTextInput != null) {
textInputIgnoredFirstEnter = false;
}
return true;
}
if (handleModalKeyDown(keycode)) {
return true;
}
receivedKeyDowns.remove(keycode);
return false;
}
@Override
public boolean keyUp(int keycode) {
//Key down was sent before this UI Container accepted input
if(!receivedKeyDowns.remove(keycode)) {
return false;
}
if (handleTextInputKeyUp(keycode)) {
return true;
}
if (keycode == actionKey && activeAction != null) {
KeyboardEventTriggerParams params = EventTriggerParamsPool.allocateKeyboardParams();
params.setKey(keycode);
activeAction.endAction(EventTrigger.KEYBOARD, params);
EventTriggerParamsPool.release(params);
switch(Mdx.os) {
case ANDROID:
case IOS:
Gdx.input.setOnscreenKeyboardVisible(false);
break;
default:
break;
}
return true;
}
if (handleModalKeyUp(keycode)) {
return true;
}
return false;
}
public boolean buttonDown(ControllerUiInput<?> controllerUiInput, ControllerButton button) {
if (activeNavigation == null) {
return false;
}
receivedButtonDowns.add(button.getAbsoluteValue());
ActionableRenderNode hotkeyAction = activeNavigation.hotkey(button);
if (hotkeyAction != null) {
ControllerEventTriggerParams params = EventTriggerParamsPool.allocateControllerParams();
params.setControllerButton(button);
hotkeyAction.beginAction(EventTrigger.CONTROLLER, params);
EventTriggerParamsPool.release(params);
} else if (activeAction != null) {
if (button.equals(controllerUiInput.getActionButton())) {
if (activeTextInput != null) {
if(!textInputIgnoredFirstEnter) {
ControllerEventTriggerParams params = EventTriggerParamsPool.allocateControllerParams();
params.setControllerButton(button);
activeAction.beginAction(EventTrigger.CONTROLLER, params);
EventTriggerParamsPool.release(params);
}
} else {
ControllerEventTriggerParams params = EventTriggerParamsPool.allocateControllerParams();
params.setControllerButton(button);
activeAction.beginAction(EventTrigger.CONTROLLER, params);
EventTriggerParamsPool.release(params);
}
}
}
return true;
}
public boolean buttonUp(ControllerUiInput<?> controllerUiInput, ControllerButton button) {
//Button down was sent before this UI Container accepted input
if(!receivedButtonDowns.remove(button.getAbsoluteValue())) {
return false;
}
if (activeNavigation == null) {
return false;
}
ActionableRenderNode hotkeyAction = activeNavigation.hotkey(button);
if (hotkeyAction != null) {
ControllerEventTriggerParams params = EventTriggerParamsPool.allocateControllerParams();
params.setControllerButton(button);
hotkeyAction.endAction(EventTrigger.CONTROLLER, params);
EventTriggerParamsPool.release(params);
} else if (activeAction != null) {
if(activeTextInput != null && !textInputIgnoredFirstEnter) {
textInputIgnoredFirstEnter = true;
return true;
}
if (button.equals(controllerUiInput.getActionButton())) {
ControllerEventTriggerParams params = EventTriggerParamsPool.allocateControllerParams();
params.setControllerButton(button);
activeAction.endAction(EventTrigger.CONTROLLER, params);
EventTriggerParamsPool.release(params);
textInputIgnoredFirstEnter = false;
}
}
return true;
}
private boolean handleModalKeyDown(int keycode) {
if (activeNavigation == null) {
return false;
}
ActionableRenderNode hotkeyAction = activeNavigation.hotkey(keycode);
if (hotkeyAction == null) {
if (keyNavigationInUse()) {
if (activeAction != null) {
activeAction.setState(NodeState.NORMAL);
}
ActionableRenderNode result = activeNavigation.navigate(keycode);
if (result != null) {
result.setState(NodeState.HOVER);
setActiveAction(result);
}
}
} else {
KeyboardEventTriggerParams params = EventTriggerParamsPool.allocateKeyboardParams();
params.setKey(keycode);
hotkeyAction.beginAction(EventTrigger.KEYBOARD, params);
EventTriggerParamsPool.release(params);
}
return true;
}
private boolean handleModalKeyUp(int keycode) {
if (activeNavigation == null) {
return false;
}
ActionableRenderNode hotkeyAction = activeNavigation.hotkey(keycode);
if (hotkeyAction != null) {
KeyboardEventTriggerParams params = EventTriggerParamsPool.allocateKeyboardParams();
params.setKey(keycode);
hotkeyAction.endAction(EventTrigger.KEYBOARD, params);
EventTriggerParamsPool.release(params);
}
return true;
}
private boolean handleTextInputKeyUp(int keycode) {
if (activeTextInput == null) {
return false;
}
if (!activeTextInput.isReceivingInput()) {
return false;
}
switch (keycode) {
case Keys.BACKSPACE:
activeTextInput.backspace();
break;
case Keys.ENTER:
if (!textInputIgnoredFirstEnter) {
textInputIgnoredFirstEnter = true;
return true;
}
if (activeTextInput.enter()) {
activeTextInput = null;
activeAction = null;
switch(Mdx.os) {
case ANDROID:
case IOS:
Gdx.input.setOnscreenKeyboardVisible(false);
break;
default:
break;
}
}
break;
case Keys.RIGHT:
activeTextInput.moveCursorRight();
break;
case Keys.LEFT:
activeTextInput.moveCursorLeft();
break;
}
return true;
}
private void setActiveAction(ActionableRenderNode actionable) {
if (actionable instanceof TextInputableRenderNode) {
activeTextInput = (TextInputableRenderNode) actionable;
switch(Mdx.os) {
case ANDROID:
case IOS:
Gdx.input.setOnscreenKeyboardVisible(true);
break;
default:
break;
}
}
activeAction = actionable;
notifyElementActivated(actionable);
}
/**
* Sets the current {@link Navigatable} for UI navigation
*
* @param activeNavigation
* The current {@link Navigatable} being navigated
*/
public void setActiveNavigation(Navigatable activeNavigation) {
this.activeNavigation = activeNavigation;
if(renderTree == null) {
return;
}
if(!keyNavigationInUse()) {
return;
}
if (activeAction != null) {
activeAction.setState(NodeState.NORMAL);
}
UiNavigation navigation = activeNavigation.getNavigation();
if(navigation == null) {
return;
}
Actionable firstActionable = navigation.resetCursor();
if(firstActionable == null) {
return;
}
RenderNode<?, ?> renderNode = renderTree.getElementById(firstActionable.getId());
if(renderNode == null) {
return;
}
setActiveAction(((ActionableRenderNode) renderNode));
((ActionableRenderNode) renderNode).setState(NodeState.HOVER);
}
/**
* Clears the current {@link Navigatable} being navigated
*/
public void clearActiveNavigation() {
this.activeTextInput = null;
this.activeAction = null;
this.activeNavigation = null;
}
/**
* Returns the width of the {@link UiContainer}
*
* @return The width in pixels
*/
public int getWidth() {
return width;
}
/**
* Returns the height of the {@link UiContainer}
*
* @return The height in pixels
*/
public int getHeight() {
return height;
}
/**
* Sets the width and height of the {@link UiContainer}
*
* @param width
* The width in pixels
* @param height
* The height in pixels
*/
public void set(int width, int height) {
this.width = width;
this.height = height;
renderTree.onResize(width, height);
}
/**
* Returns the configured {@link Graphics} scaling during rendering
* @return 1f by default
*/
public float getScaleX() {
return scaleX;
}
/**
* Returns the configured {@link Graphics} scaling during rendering
* @return 1f by default
*/
public float getScaleY() {
return scaleY;
}
/**
* Sets the {@link Graphics} scaling during rendering. Mouse/touch
* coordinates will be scaled accordingly.
*
* @param scaleX
* Scaling along the X axis
* @param scaleY
* Scaling along the Y axis
*/
public void setScale(float scaleX, float scaleY) {
this.scaleX = scaleX;
this.scaleY = scaleY;
}
/**
* Returns the last {@link InputSource} used on the {@link UiContainer}
*
* @return
*/
public InputSource getLastInputSource() {
return lastInputSource;
}
/**
* Sets the last {@link InputSource} used on the {@link UiContainer}
*
* @param lastInputSource
* The {@link InputSource} last used
*/
public void setLastInputSource(InputSource lastInputSource) {
if (lastInputSource == null) {
return;
}
if (this.lastInputSource.equals(lastInputSource)) {
return;
}
InputSource oldInputSource = this.lastInputSource;
this.lastInputSource = lastInputSource;
notifyInputSourceChange(oldInputSource, lastInputSource);
}
/**
* Adds a {@link ControllerUiInput} instance to this {@link UiContainer}
*
* @param input
* The instance to add
*/
public void addControllerInput(ControllerUiInput<?> input) {
controllerInputs.add(input);
}
/**
* Removes a {@link ControllerUiInput} instance from this
* {@link UiContainer}
*
* @param input
* The instance to remove
*/
public void removeControllerInput(ControllerUiInput<?> input) {
controllerInputs.remove(input);
}
@Override
public void setZIndex(int zIndex) {
}
/**
* Sets the key used for triggering actions (i.e. selecting a menu option)
*
* @param actionKey
* The {@link Keys} value
*/
public void setActionKey(int actionKey) {
this.actionKey = actionKey;
}
private boolean keyNavigationInUse() {
switch (Mdx.os) {
case ANDROID:
case IOS:
return false;
case MAC:
case UNIX:
case UNKNOWN:
case WINDOWS:
default:
return keyboardNavigationEnabled || lastInputSource == InputSource.CONTROLLER;
}
}
/**
* Sets if desktop-based games uses keyboard navigation instead of mouse
* navigation. Note: This does not effect hotkeys
*
* @param keyboardNavigationEnabled True if the desktop-based game should only navigate by keyboard
*/
public void setKeyboardNavigationEnabled(boolean keyboardNavigationEnabled) {
this.keyboardNavigationEnabled = keyboardNavigationEnabled;
}
/**
* Adds a {@link UiContainerListener} to this {@link UiContainer}
* @param listener The {@link UiContainerListener} to be notified of events
*/
public void addListener(UiContainerListener listener) {
listeners.add(listener);
addScreenSizeListener(listener);
}
/**
* Removes a {@link UiContainerListener} from this {@link UiContainer}
* @param listener The {@link UiContainerListener} to stop receiving events
*/
public void removeListener(UiContainerListener listener) {
listeners.remove(listener);
removeScreenSizeListener(listener);
}
private void notifyPreUpdate(float delta) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).preUpdate(this, delta);
}
}
private void notifyPostUpdate(float delta) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).postUpdate(this, delta);
}
}
private void notifyPreInterpolate(float alpha) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).preInterpolate(this, alpha);
}
}
private void notifyPostInterpolate(float alpha) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).postInterpolate(this, alpha);
}
}
private void notifyPreRender(Graphics g) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).preRender(this, g);
}
}
private void notifyPostRender(Graphics g) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).postRender(this, g);
}
}
private void notifyInputSourceChange(InputSource oldSource, InputSource newSource) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).inputSourceChanged(this, oldSource, newSource);
}
}
private void notifyElementActivated(ActionableRenderNode actionable) {
for(int i = listeners.size() - 1; i >= 0; i
listeners.get(i).onElementAction(this, actionable.getElement());
}
}
/**
* Returns the default {@link Visibility} for newly created {@link UiElement} objects
* @return A non-null {@link Visibility} value. {@link Visibility#HIDDEN} by default
*/
public static Visibility getDefaultVisibility() {
return defaultVisibility;
}
/**
* Sets the default {@link Visibility} for newly created {@link UiElement} objects
* @param defaultVisibility The {@link Visibility} to set as default
*/
public static void setDefaultVisibility(Visibility defaultVisibility) {
if(defaultVisibility == null) {
return;
}
UiContainer.defaultVisibility = defaultVisibility;
}
}
|
package hudson.maven;
import hudson.maven.reporters.MavenArtifactArchiver;
import hudson.model.Descriptor;
import hudson.model.Describable;
import hudson.model.Hudson;
import org.apache.commons.jelly.JellyException;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.jelly.JellyClassTearOff;
import java.util.Collection;
/**
* {@link Descriptor} for {@link MavenReporter}.
*
* @author Kohsuke Kawaguchi
*/
public abstract class MavenReporterDescriptor extends Descriptor<MavenReporter> {
protected MavenReporterDescriptor(Class<? extends MavenReporter> clazz) {
super(clazz);
}
/**
* Infers the type of the corresponding {@link Describable} from the outer class.
* This version works when you follow the common convention, where a descriptor
* is written as the static nested class of the describable class.
*
* @since 1.278
*/
protected MavenReporterDescriptor() {
}
/**
* Returns an instance used for automatic {@link MavenReporter} activation.
*
* <p>
* Some {@link MavenReporter}s, such as {@link MavenArtifactArchiver},
* can work just with the configuration in POM and don't need any additional
* Hudson configuration. They also don't need any explicit enabling/disabling
* as they can activate themselves by listening to the callback from the build
* (for example javadoc archiver can do the work in response to the execution
* of the javadoc target.)
*
* <p>
* Those {@link MavenReporter}s should return a valid instance
* from this method. Such instance will then participate into the build
* and receive event callbacks.
*/
public MavenReporter newAutoInstance(MavenModule module) {
return null;
}
/**
* If {@link #hasConfigScreen() the reporter has no configuration screen},
* this method can safely return null, which is the default implementation.
*/
@Deprecated
public MavenReporter newInstance(StaplerRequest req) throws FormException {
return null;
}
/**
* Returns true if this descriptor has <tt>config.jelly</tt>.
*/
public final boolean hasConfigScreen() {
MetaClass c = WebApp.getCurrent().getMetaClass(getClass());
try {
JellyClassTearOff tearOff = c.loadTearOff(JellyClassTearOff.class);
return tearOff.findScript(getConfigPage())!=null;
} catch(JellyException e) {
return false;
}
}
/**
* Lists all the currently registered instances of {@link MavenReporterDescriptor}.
*/
public static Collection<MavenReporterDescriptor> all() {
// use getDescriptorList and not getExtensionList to pick up legacy instances
return Hudson.getInstance().<MavenReporter,MavenReporterDescriptor>getDescriptorList(MavenReporter.class);
}
}
|
package org.jasig.portal.channels;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Map;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.IMultithreadedMimeResponse;
import org.jasig.portal.PortalException;
import org.jasig.portal.UPFileSpec;
import org.jasig.portal.security.IPerson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.portal.services.PersonDirectory;
import org.jasig.portal.utils.DocumentFactory;
import org.jasig.portal.utils.XSLT;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.ContentHandler;
/**
* This channel demonstrates the method of obtaining and displaying
* standard uPortal person attributes.
*
* Implements MultithreadedIMimeResponse in order to support the inline display of jpegPhotos
* Note: for proper operation, one should use an idempotent baseActionURL.
*
* @author Ken Weiner, kweiner@unicon.net
* @author Yuji Shinozaki, ys2n@virginia.edu
* @version $Revision$ $Date$
*/
public class CPersonAttributes extends BaseMultithreadedChannel implements IMultithreadedMimeResponse {
private static final Log log = LogFactory.getLog(CPersonAttributes.class);
private static final String sslLocation = "CPersonAttributes/CPersonAttributes.ssl";
public void renderXML (ContentHandler out, String uid) throws PortalException {
ChannelState channelState = (ChannelState)channelStateMap.get(uid);
ChannelStaticData staticData = channelState.getStaticData();
ChannelRuntimeData runtimeData = channelState.getRuntimeData();
IPerson person = staticData.getPerson();
Document doc = DocumentFactory.getNewDocument();
Element attributesE = doc.createElement("attributes");
Enumeration attribs = person.getAttributeNames();
while ( attribs.hasMoreElements() ) {
// Get the attribute name
String attName = (String) attribs.nextElement();
// Set the attribute
Element attributeE = doc.createElement("attribute");
Element nameE = doc.createElement("name");
nameE.appendChild(doc.createTextNode(attName));
attributeE.appendChild(nameE);
// Get the IPerson attribute value for this eduPerson attribute name
if (person.getAttributeValues(attName) != null) {
Object[] values = person.getAttributeValues(attName);
for (int i = 0; i < values.length; i++) {
if (log.isTraceEnabled())
log.trace("type of value["+i+"] is " + values[i].getClass().getName());
String value = values[i].toString();
Element valueE = doc.createElement("value");
valueE.appendChild(doc.createTextNode(value));
attributeE.appendChild(valueE);
}
}
attributesE.appendChild(attributeE);
}
doc.appendChild(attributesE);
XSLT xslt = XSLT.getTransformer(this, runtimeData.getLocales());
xslt.setXML(doc);
xslt.setStylesheetParameter("baseActionURL",runtimeData.getBaseActionURL());
xslt.setStylesheetParameter("downloadWorkerURL",
runtimeData.getBaseWorkerURL(UPFileSpec.FILE_DOWNLOAD_WORKER,true));
xslt.setXSL(sslLocation, runtimeData.getBrowserInfo());
xslt.setTarget(out);
xslt.transform();
}
// IMimeResponse implementation -- ys2n@virginia.edu
/**
* Returns the MIME type of the content.
*/
public java.lang.String getContentType (String uid) {
// In the future we will need some sort of way of grokking the
// mime-type of the byte-array and returning an appropriate mime-type
// Right now there is no good way of doing that, and we will
// assume that the only thing we will be delivering is a jpegPhoto.
// attribute with a mimetype of image/jpeg
// In the future however, we may need a way to deliver different
// attributes as differenct mimetypes (e.g certs).
String mimetype;
ChannelState channelState = (ChannelState)channelStateMap.get(uid);
ChannelRuntimeData runtimeData = channelState.getRuntimeData();
// runtime parameter "attribute" determines which attribute to return when
// called as an IMimeResponse.
String attrName = runtimeData.getParameter("attribute");
if ("jpegPhoto".equals(attrName)) {
mimetype="image/jpeg";
}
else {
// default -- an appropriate choice?
mimetype="application/octet-stream";
}
return mimetype;
}
/**
* Returns the MIME content in the form of an input stream.
* Returns null if the code needs the OutputStream object
*/
public java.io.InputStream getInputStream (String uid) throws IOException {
ChannelState channelState = (ChannelState)channelStateMap.get(uid);
ChannelStaticData staticData = channelState.getStaticData();
ChannelRuntimeData runtimeData = channelState.getRuntimeData();
String attrName = runtimeData.getParameter("attribute");
IPerson person = staticData.getPerson();
if ( attrName == null ) {
attrName = "";
}
// get the image out of the IPerson as a byte array.
// Note: I am assuming here that the only thing that this
// IMimeResponse will return is a jpegPhoto. Some other
// generalized mechanism will need to be inserted here to
// support other mimetypes and IPerson attributes.
byte[] imgBytes = (byte [])person.getAttribute(attrName);
// need to create a ByteArrayInputStream()
if ( imgBytes == null ) {
imgBytes = new byte[0]; // let's avoid a null pointer
}
java.io.InputStream is = (java.io.InputStream) new java.io.ByteArrayInputStream(imgBytes);
return is;
}
/**
* Pass the OutputStream object to the download code if it needs special handling
* (like outputting a Zip file). Unimplemented.
*/
public void downloadData (OutputStream out, String uid) throws IOException {
}
/**
* Returns the name of the MIME file.
*/
public java.lang.String getName (String uid) {
// As noted above the only attribute we support right now is "image/jpeg" for
// the jpegPhoto attribute.
ChannelState channelState = (ChannelState)channelStateMap.get(uid);
ChannelStaticData staticData = channelState.getStaticData();
ChannelRuntimeData runtimeData = channelState.getRuntimeData();
String payloadName;
if ("jpegPhoto".equals(runtimeData.getParameter("attribute")))
payloadName = "image.jpg";
else
payloadName = "unknown";
return payloadName;
}
/**
* Returns a list of header values that can be set in the HttpResponse.
* Returns null if no headers need to be set.
*/
public Map getHeaders (String uid) {
return null;
}
/**
* Let the channel know that there were problems with the download
* @param e
*/
public void reportDownloadError(Exception e) {
log.error( "CPersonAttributes::reportDownloadError(): " + e.getMessage());
}
}
|
package fitnesse.testrunner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import fitnesse.testsystems.Assertion;
import fitnesse.testsystems.ClassPath;
import fitnesse.testsystems.CompositeExecutionLogListener;
import fitnesse.testsystems.Descriptor;
import fitnesse.testsystems.ExceptionResult;
import fitnesse.testsystems.ExecutionLogListener;
import fitnesse.testsystems.TestPage;
import fitnesse.testsystems.TestResult;
import fitnesse.testsystems.TestSummary;
import fitnesse.testsystems.TestSystem;
import fitnesse.testsystems.TestSystemFactory;
import fitnesse.testsystems.TestSystemListener;
import util.FileUtil;
public class MultipleTestsRunner implements Stoppable {
private static final Logger LOG = Logger.getLogger(MultipleTestsRunner.class.getName());
private final CompositeFormatter formatters;
private final PagesByTestSystem pagesByTestSystem;
private final TestSystemFactory testSystemFactory;
private final CompositeExecutionLogListener executionLogListener;
private volatile boolean isStopped = false;
private boolean runInProcess;
private boolean enableRemoteDebug;
private TestSystem testSystem;
private volatile int testsInProgressCount;
public MultipleTestsRunner(final PagesByTestSystem pagesByTestSystem,
final TestSystemFactory testSystemFactory) {
this.pagesByTestSystem = pagesByTestSystem;
this.testSystemFactory = testSystemFactory;
this.formatters = new CompositeFormatter();
this.executionLogListener = new CompositeExecutionLogListener();
}
public void setRunInProcess(boolean runInProcess) {
this.runInProcess = runInProcess;
}
public void setEnableRemoteDebug(boolean enableRemoteDebug) {
this.enableRemoteDebug = enableRemoteDebug;
}
public void addTestSystemListener(TestSystemListener listener) {
this.formatters.addTestSystemListener(listener);
}
public void executeTestPages() throws IOException, InterruptedException {
try {
internalExecuteTestPages();
} finally {
allTestingComplete();
}
}
private void allTestingComplete() {
FileUtil.close(formatters);
}
private void internalExecuteTestPages() throws IOException, InterruptedException {
announceTotalTestsToRun(pagesByTestSystem);
for (WikiPageIdentity identity : pagesByTestSystem.identities()) {
startTestSystemAndExecutePages(identity, pagesByTestSystem.testPagesForIdentity(identity));
}
}
private void startTestSystemAndExecutePages(WikiPageIdentity identity, List<TestPage> testSystemPages) throws IOException, InterruptedException {
TestSystem testSystem = null;
try {
if (!isStopped) {
testSystem = startTestSystem(identity, testSystemPages);
}
if (testSystem != null && testSystem.isSuccessfullyStarted()) {
executeTestSystemPages(testSystemPages, testSystem);
waitForTestSystemToSendResults();
}
} finally {
if (!isStopped && testSystem != null) {
try {
testSystem.bye();
} catch (Exception e) {
executionLogListener.exceptionOccurred(e);
}
}
}
}
private TestSystem startTestSystem(final WikiPageIdentity identity, final List<TestPage> testPages) throws IOException {
Descriptor descriptor = new Descriptor() {
private ClassPath classPath;
@Override
public String getTestSystem() {
String testSystemName = getVariable(WikiPageIdentity.TEST_SYSTEM);
if (testSystemName == null)
return "fit";
return testSystemName;
}
@Override
public String getTestSystemType() {
return getTestSystem().split(":")[0];
}
@Override
public ClassPath getClassPath() {
if (classPath == null) {
List<ClassPath> paths = new ArrayList<ClassPath>();
for (TestPage testPage: testPages) {
paths.add(testPage.getClassPath());
}
classPath = new ClassPath(paths);
}
return classPath;
}
@Override
public boolean runInProcess() {
return runInProcess;
}
@Override
public boolean isDebug() {
return enableRemoteDebug;
}
@Override
public String getVariable(String name) {
return identity.getVariable(name);
}
@Override
public ExecutionLogListener getExecutionLogListener() {
return executionLogListener;
}
};
InternalTestSystemListener internalTestSystemListener = new InternalTestSystemListener();
try {
testSystem = testSystemFactory.create(descriptor);
testSystem.addTestSystemListener(internalTestSystemListener);
testSystem.start();
} catch (Exception e) {
formatters.unableToStartTestSystem(descriptor.getTestSystem(), e);
return null;
}
return testSystem;
}
private void executeTestSystemPages(List<TestPage> pagesInTestSystem, TestSystem testSystem) throws IOException, InterruptedException {
for (TestPage testPage : pagesInTestSystem) {
testsInProgressCount++;
testSystem.runTests(testPage);
}
}
private void waitForTestSystemToSendResults() throws InterruptedException {
// TODO: use testSystemStopped event to wait for tests to end.
while (testsInProgressCount > 0 && isNotStopped())
Thread.sleep(50);
}
void announceTotalTestsToRun(PagesByTestSystem pagesByTestSystem) {
formatters.announceNumberTestsToRun(pagesByTestSystem.totalTestsToRun());
}
public void addExecutionLogListener(ExecutionLogListener listener) {
executionLogListener.addExecutionLogListener(listener);
}
private class InternalTestSystemListener implements TestSystemListener {
@Override
public void testSystemStarted(TestSystem testSystem) throws IOException {
formatters.testSystemStarted(testSystem);
}
@Override
public void testOutputChunk(String output) throws IOException {
formatters.testOutputChunk(output);
}
@Override
public void testStarted(TestPage testPage) throws IOException {
formatters.testStarted(testPage);
}
@Override
public void testComplete(TestPage testPage, TestSummary testSummary) throws IOException {
formatters.testComplete(testPage, testSummary);
testsInProgressCount
}
@Override
public void testSystemStopped(TestSystem testSystem, Throwable cause) {
formatters.testSystemStopped(testSystem, cause);
if (cause != null) {
executionLogListener.exceptionOccurred(cause);
stop();
}
}
@Override
public void testAssertionVerified(Assertion assertion, TestResult testResult) {
formatters.testAssertionVerified(assertion, testResult);
}
@Override
public void testExceptionOccurred(Assertion assertion, ExceptionResult exceptionResult) {
formatters.testExceptionOccurred(assertion, exceptionResult);
}
}
private boolean isNotStopped() {
return !isStopped;
}
@Override
public void stop() {
boolean wasNotStopped = isNotStopped();
isStopped = true;
if (wasNotStopped && testSystem != null) {
try {
testSystem.kill();
} catch (IOException e) {
LOG.log(Level.WARNING, "Unable to stop test systems", e);
}
}
}
}
|
package com.github.dreamhead.moco;
import com.google.common.io.ByteStreams;
import com.google.common.io.Resources;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.hamcrest.Matcher;
import org.hamcrest.core.SubstringMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import static com.github.dreamhead.moco.HttpProtocolVersion.VERSION_0_9;
import static com.github.dreamhead.moco.HttpProtocolVersion.VERSION_1_0;
import static com.github.dreamhead.moco.HttpProtocolVersion.VERSION_1_1;
import static com.github.dreamhead.moco.Moco.and;
import static com.github.dreamhead.moco.Moco.by;
import static com.github.dreamhead.moco.Moco.context;
import static com.github.dreamhead.moco.Moco.eq;
import static com.github.dreamhead.moco.Moco.failover;
import static com.github.dreamhead.moco.Moco.file;
import static com.github.dreamhead.moco.Moco.from;
import static com.github.dreamhead.moco.Moco.header;
import static com.github.dreamhead.moco.Moco.httpServer;
import static com.github.dreamhead.moco.Moco.json;
import static com.github.dreamhead.moco.Moco.log;
import static com.github.dreamhead.moco.Moco.match;
import static com.github.dreamhead.moco.Moco.method;
import static com.github.dreamhead.moco.Moco.pathResource;
import static com.github.dreamhead.moco.Moco.playback;
import static com.github.dreamhead.moco.Moco.proxy;
import static com.github.dreamhead.moco.Moco.query;
import static com.github.dreamhead.moco.Moco.seq;
import static com.github.dreamhead.moco.Moco.status;
import static com.github.dreamhead.moco.Moco.template;
import static com.github.dreamhead.moco.Moco.text;
import static com.github.dreamhead.moco.Moco.uri;
import static com.github.dreamhead.moco.Moco.version;
import static com.github.dreamhead.moco.Moco.with;
import static com.github.dreamhead.moco.MocoRequestHit.once;
import static com.github.dreamhead.moco.MocoRequestHit.requestHit;
import static com.github.dreamhead.moco.Runner.running;
import static com.github.dreamhead.moco.helper.RemoteTestUtils.port;
import static com.github.dreamhead.moco.helper.RemoteTestUtils.remoteUrl;
import static com.github.dreamhead.moco.helper.RemoteTestUtils.root;
import static com.google.common.collect.ImmutableMultimap.of;
import static com.google.common.io.Files.asCharSource;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
public class MocoProxyTest extends AbstractMocoHttpTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
// @Test
// public void should_fetch_remote_url() throws Exception {
// running(server, new Runnable() {
// @Override
// public void run() throws IOException {
// assertThat(helper.getForStatus(root()), is(200));
@Test
public void should_proxy_with_request_method() throws Exception {
server.get(by(uri("/target"))).response("get_proxy");
server.post(and(by(uri("/target")), by("proxy"))).response("post_proxy");
server.request(and(by(uri("/target")), by(method("put")), by("proxy"))).response("put_proxy");
server.request(and(by(uri("/target")), by(method("delete")))).response("delete_proxy");
server.request(and(by(uri("/target")), by(method("head")))).response(status(200));
server.request(and(by(uri("/target")), by(method("options")))).response("options_proxy");
server.request(and(by(uri("/target")), by(method("trace")))).response("trace_proxy");
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target")));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy")), is("get_proxy"));
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("post_proxy"));
Request putRequest = Request.Put(remoteUrl("/proxy")).bodyString("proxy", ContentType.DEFAULT_TEXT);
assertThat(helper.executeAsString(putRequest), is("put_proxy"));
Request deleteRequest = Request.Delete(remoteUrl("/proxy"));
assertThat(helper.executeAsString(deleteRequest), is("delete_proxy"));
Request headRequest = Request.Head(remoteUrl("/proxy"));
StatusLine headStatusLine = helper.execute(headRequest).getStatusLine();
assertThat(headStatusLine.getStatusCode(), is(200));
Request optionsRequest = Request.Options(remoteUrl("/proxy"));
assertThat(helper.executeAsString(optionsRequest), is("options_proxy"));
Request traceRequest = Request.Trace(remoteUrl("/proxy"));
assertThat(helper.executeAsString(traceRequest), is("trace_proxy"));
});
}
@Test
public void should_proxy_with_request_header() throws Exception {
server.request(and(by(uri("/target")), eq(header("foo"), "foo"))).response("foo_proxy");
server.request(and(by(uri("/target")), eq(header("bar"), "bar"))).response("bar_proxy");
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target")));
running(server, () -> assertThat(helper.getWithHeader(remoteUrl("/proxy"), of("foo", "foo")), is("foo_proxy")));
}
@Test
public void should_proxy_with_request_query_parameters() throws Exception {
server.request(and(by(uri("/target")), eq(query("foo"), "foo"))).response("foo_proxy");
server.request(and(by(uri("/target")), eq(query("bar"), "bar"))).response("bar_proxy");
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target")));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy?foo=foo")), is("foo_proxy"));
assertThat(helper.get(remoteUrl("/proxy?bar=bar")), is("bar_proxy"));
});
}
@Test
public void should_proxy_with_response_headers() throws Exception {
server.request(and(by(uri("/target")), eq(header("foo"), "foo"))).response(header("foo", "foo_header"));
server.request(and(by(uri("/target")), eq(header("bar"), "bar"))).response(header("bar", "bar_header"));
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target")));
running(server, () -> {
Request request = Request.Get(remoteUrl("/proxy")).addHeader("foo", "foo");
String fooHeader = helper.execute(request).getFirstHeader("foo").getValue();
assertThat(fooHeader, is("foo_header"));
});
}
@Test
public void should_proxy_with_request_version() throws Exception {
server.request(and(by(uri("/target")), by(version(VERSION_1_0)))).response("1.0");
server.request(and(by(uri("/target")), by(version(VERSION_1_1)))).response("1.1");
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target")));
running(server, () -> {
assertThat(helper.getWithVersion(remoteUrl("/proxy"), HttpVersion.HTTP_1_0), is("1.0"));
assertThat(helper.getWithVersion(remoteUrl("/proxy"), HttpVersion.HTTP_1_1), is("1.1"));
});
}
@Test
public void should_proxy_with_response_version() throws Exception {
server.request(and(by(uri("/target")), by(version(VERSION_1_0)))).response(version(VERSION_1_0));
server.request(and(by(uri("/target")), by(version(VERSION_1_1)))).response(version(VERSION_1_1));
server.request(and(by(uri("/target")), by(version(VERSION_0_9)))).response(version(VERSION_1_0));
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target")));
running(server, () -> {
HttpResponse response10 = helper.execute(Request.Get(remoteUrl("/proxy"))
.version(HttpVersion.HTTP_1_0));
assertThat(response10.getProtocolVersion().toString(), is(HttpVersion.HTTP_1_0.toString()));
HttpResponse response11 = helper.execute(Request.Get(remoteUrl("/proxy"))
.version(HttpVersion.HTTP_1_1));
assertThat(response11.getProtocolVersion().toString(), is(HttpVersion.HTTP_1_1.toString()));
HttpResponse response09 = helper.execute(Request.Get(remoteUrl("/proxy"))
.version(HttpVersion.HTTP_0_9));
assertThat(response09.getProtocolVersion().toString(), is(HttpVersion.HTTP_1_0.toString()));
});
}
@Test
public void should_failover_with_response_content() throws Exception {
server.post(and(by(uri("/target")), by("proxy"))).response("proxy");
final File tempFile = tempFolder.newFile();
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target"), failover(tempFile.getAbsolutePath())));
running(server, () -> {
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("proxy"));
assertThat(asCharSource(tempFile, Charset.defaultCharset()).read(), containsString("proxy"));
});
}
@Test
public void should_failover_with_many_response_content() throws Exception {
server.get(by(uri("/target"))).response("get_proxy");
server.post(and(by(uri("/target")), by("proxy"))).response("post_proxy");
final File tempFile = tempFolder.newFile();
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target"), failover(tempFile.getAbsolutePath())));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy")), is("get_proxy"));
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("post_proxy"));
String failoverContent = asCharSource(tempFile, Charset.defaultCharset()).read();
assertThat(failoverContent, containsString("get_proxy"));
assertThat(failoverContent, containsString("post_proxy"));
});
}
@Test
public void should_failover_with_same_response_once() throws Exception {
server = httpServer(port());
server.post(and(by(uri("/target")), by("proxy"))).response("0XCAFEBABE");
final File tempFile = tempFolder.newFile();
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target"), failover(tempFile.getAbsolutePath())));
running(server, () -> {
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("0XCAFEBABE"));
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("0XCAFEBABE"));
assertThat(asCharSource(tempFile, Charset.defaultCharset()).read(), countString("/proxy", 1));
});
}
private Matcher<String> countString(final String substring, final int targetCount) {
return new SubstringMatcher("counting", false, substring) {
@Override
protected boolean evalSubstringOf(final String string) {
int count = 0;
int current = 0;
while (current < string.length()) {
int index = string.indexOf(substring, current);
if (index > 0) {
count++;
current = index + substring.length();
} else {
break;
}
}
return count == targetCount;
}
};
}
@Test
public void should_failover_for_unreachable_remote_server() throws Exception {
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target"), failover("src/test/resources/failover.response")));
running(server, () -> assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("proxy")));
}
@Test
public void should_failover_for_specified_status() throws Exception {
server.request(by(uri("/target"))).response(seq(status(500), status(400)));
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target"), failover("src/test/resources/failover.response", 500, 400)));
running(server, () -> {
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("proxy"));
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("proxy"));
});
}
@Test
public void should_failover_for_specified_status_with_resource_proxy() throws Exception {
server.request(by(uri("/target"))).response(seq(status(500), status(400)));
server.request(by(uri("/proxy"))).response(proxy(text(remoteUrl("/target")), failover("src/test/resources/failover.response", 500, 400)));
running(server, () -> {
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("proxy"));
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("proxy"));
});
}
@Test
public void should_failover_for_unreachable_remote_server_with_many_content() throws Exception {
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target"), failover("src/test/resources/many_content_failover.response")));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy")), is("get_proxy"));
assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("post_proxy"));
});
}
// @Test
// public void should_be_able_to_connect_to_external_website_successfully() throws Exception {
// running(server, new Runnable() {
// @Override
// public void run() throws IOException {
// assertThat(helper.getForStatus(root()), is(200));
@Test
public void should_proxy_a_batch_of_urls() throws Exception {
server.get(by(uri("/target/1"))).response("target_1");
server.get(by(uri("/target/2"))).response("target_2");
server.get(match(uri("/proxy/.*"))).response(proxy(from("/proxy").to(remoteUrl("/target"))));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy/1")), is("target_1"));
assertThat(helper.get(remoteUrl("/proxy/2")), is("target_2"));
});
}
@Test
public void should_proxy_a_batch_of_urls_with_failover() throws Exception {
server.request(match(uri("/proxy/.*"))).response(proxy(from("/proxy").to(remoteUrl("/target")), failover("src/test/resources/failover.response")));
running(server, () -> assertThat(helper.postContent(remoteUrl("/proxy/1"), "proxy"), is("proxy")));
}
@Test
public void should_failover_for_batch_api_with_specified_status() throws Exception {
server.request(by(uri("/target"))).response(seq(status(500), status(400)));
server.request(match(uri("/proxy/.*"))).response(proxy(from("/proxy").to(remoteUrl("/target")), failover("src/test/resources/failover.response", 500, 400)));
running(server, () -> {
assertThat(helper.postContent(remoteUrl("/proxy/1"), "proxy"), is("proxy"));
assertThat(helper.postContent(remoteUrl("/proxy/2"), "proxy"), is("proxy"));
});
}
@Test
public void should_batch_proxy_from_server() throws Exception {
server.get(by(uri("/target/1"))).response("target_1");
server.get(by(uri("/target/2"))).response("target_2");
server.proxy(from("/proxy").to(remoteUrl("/target")));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy/1")), is("target_1"));
assertThat(helper.get(remoteUrl("/proxy/2")), is("target_2"));
});
}
@Test(expected = HttpResponseException.class)
public void should_not_proxy_url_for_unmatching_url_for_batch_proxy_from_server() throws Exception {
server.proxy(from("/proxy").to(remoteUrl("/target")));
running(server, () -> helper.get(remoteUrl("/proxy1/1")));
}
@Test
public void should_batch_proxy_from_server_with_context_server() throws Exception {
server = httpServer(port(), context("/proxy"));
server.get(by(uri("/target/1"))).response("target_1");
server.get(by(uri("/target/2"))).response("target_2");
server.proxy(from("/proxy").to(remoteUrl("/proxy/target")));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy/proxy/1")), is("target_1"));
assertThat(helper.get(remoteUrl("/proxy/proxy/2")), is("target_2"));
});
}
@Test
public void should_proxy_a_batch_of_urls_with_failover_from_server() throws Exception {
server.proxy(from("/proxy").to(remoteUrl("/target")), failover("src/test/resources/failover.response"));
running(server, () -> assertThat(helper.postContent(remoteUrl("/proxy/1"), "proxy"), is("proxy")));
}
@Test
public void should_proxy_with_playback() throws Exception {
server.request(by(uri("/target"))).response("proxy");
final File file = tempFolder.newFile();
server.request(by(uri("/proxy_playback"))).response(proxy(remoteUrl("/target"), playback(file.getAbsolutePath())));
running(server, () -> assertThat(helper.get(remoteUrl("/proxy_playback")), is("proxy")));
}
@Test
public void should_proxy_with_playback_to_access_remote_only_once() throws Exception {
RequestHit hit = requestHit();
server = httpServer(port(), hit);
server.request(by(uri("/target"))).response("proxy");
final File file = tempFolder.newFile();
server.request(by(uri("/proxy_playback"))).response(proxy(remoteUrl("/target"), playback(file.getAbsolutePath())));
running(server, () -> {
assertThat(helper.get(remoteUrl("/proxy_playback")), is("proxy"));
System.out.println("First request");
assertThat(helper.get(remoteUrl("/proxy_playback")), is("proxy"));
System.out.println("Second request");
});
hit.verify(by(uri("/target")), once());
}
@Test
public void should_ignore_some_header_from_remote_server() throws Exception {
server.request(by(uri("/target"))).response(with("proxy"), header("Date", "2014-5-1"), header("Server", "moco"));
server.request(by(uri("/proxy"))).response(proxy(remoteUrl("/target")));
running(server, () -> {
HttpResponse response = helper.execute(Request.Get(remoteUrl("/proxy")));
assertThat(response.getFirstHeader("Date"), nullValue());
assertThat(response.getFirstHeader("Server"), nullValue());
});
}
// @Test
// public void should_work_well_for_chunk_response() throws Exception {
// final File file = tempFolder.newFile();
// HttpServer server = httpServer(12306, context("/"));
// server.get(match(uri("/repos/.*")))
// running(server, new Runnable() {
// @Override
// public void run() throws Exception {
// assertThat(result.isEmpty(), is(false));
@Test
public void should_work_with_file_resource_url() throws Exception {
server.get(by(uri("/target"))).response("get_proxy");
server.request(by(uri("/proxy"))).response(proxy(file("src/test/resources/remote_url.resource")));
running(server, () -> assertThat(helper.get(remoteUrl("/proxy")), is("get_proxy")));
}
@Test
public void should_work_with_template() throws Exception {
server.get(by(uri("/target"))).response("get_proxy");
server.request(by(uri("/proxy"))).response(proxy(template("http://localhost:12306/${var}", "var", "target")));
running(server, () -> assertThat(helper.get(remoteUrl("/proxy")), is("get_proxy")));
}
@Test
public void should_forward_gbk_request() throws Exception {
server = httpServer(port(), log());
final Charset gbk = Charset.forName("GBK");
server.request(and(by(uri("/proxy")), by(json(pathResource("gbk.json", gbk))))).response("response");
server.response(proxy(remoteUrl("/proxy")));
running(server, () -> {
URL resource = Resources.getResource("gbk.json");
byte[] bytes = ByteStreams.toByteArray(resource.openStream());
String result = helper.postBytes(root(), bytes, gbk);
assertThat(result, is("response"));
});
}
}
|
package io.polestar.data.sensors;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public abstract class MergeAction
{
private String mName;
private String mFormat;
/** add sample of value at time aTime **/
public abstract void update(Object aValue, long aTime);
/** return value for period ending at aTime **/
public abstract Object getValue(long aTime);
private void init(String aName, String aFormat)
{ mName=aName;
mFormat=aFormat;
}
public String getName()
{ return mName;
}
public String getFormat()
{ return mFormat;
}
public enum Type
{ /* basic */
SAMPLE, COUNT,
/* numeric functions */
AVERAGE, MAX, MIN, DIFF, POSITIVE_DIFF, SUM, RUNNING_TOTAL, ROTATION_360_AVERAGE,
/* boolean functions */
BOOLEAN_CHANGE, BOOLEAN_RISING_EDGE_COUNT, BOOLEAN_FALLING_EDGE_COUNT,
/* map functions */
AVERAGE_MAP
}
public static MergeAction getMergeAction(String aName, String aFormat, Type aType)
{
MergeAction result;
switch(aType)
{
case SAMPLE:
result=new SampleAction();
break;
case COUNT:
result=new CountAction();
break;
case AVERAGE:
result=new AverageAction();
break;
case MAX:
result=new MaxAction();
break;
case MIN:
result=new MinAction();
break;
case DIFF:
result=new DiffAction();
break;
case POSITIVE_DIFF:
result=new PositiveDiffAction();
break;
case RUNNING_TOTAL:
result=new RunningTotalAction();
break;
case SUM:
result=new SumAction();
break;
case BOOLEAN_RISING_EDGE_COUNT:
result=new BooleanRisingEdgeAction();
break;
case BOOLEAN_FALLING_EDGE_COUNT:
result=new BooleanFallingEdgeAction();
break;
case BOOLEAN_CHANGE:
result=new BooleanChangeAction();
break;
case ROTATION_360_AVERAGE:
result=new Rot360AvgAction();
break;
case AVERAGE_MAP:
result=new AverageMapAction();
break;
default:
throw new IllegalArgumentException(aType+" not implemented");
}
result.init(aName,aFormat);
return result;
}
/** take first value or null **/
private static class SampleAction extends MergeAction
{ private Object mValue;
private Object mLast;
private boolean mDataPoint;
public void update(Object aValue, long aTime)
{ if (!mDataPoint && aValue!=null)
{ mValue=aValue;
}
mLast=aValue;
mDataPoint=true;
}
public Object getValue(long aTime)
{ Object result;
if (mDataPoint)
{ result=mValue;
}
else
{ result=mLast;
}
mDataPoint=false;
return result;
}
}
/** count number of records in period **/
private static class CountAction extends MergeAction
{ private int mCount;
public void update(Object aValue, long aTime)
{ mCount++;
}
public Object getValue(long aTime)
{ int result=mCount;
mCount=0;
return result;
}
}
private static class DiffAction extends MergeAction
{ private double mValue;
private double mLastValue;
public void update(Object aValue, long aTime)
{
if (aValue instanceof Number)
{ mValue=((Number)aValue).doubleValue();
}
}
public Object getValue(long aTime)
{ double result=mValue-mLastValue;
mLastValue=mValue;
return result;
}
}
private static class PositiveDiffAction extends MergeAction
{ private double mValue;
private double mLastValue;
public void update(Object aValue, long aTime)
{
if (aValue instanceof Number)
{ mValue=((Number)aValue).doubleValue();
}
}
public Object getValue(long aTime)
{ double result=mValue-mLastValue;
mLastValue=mValue;
return result>=0.0?result:0.0;
}
}
private static class SumAction extends MergeAction
{ private double mValue;
public void update(Object aValue, long aTime)
{ if (aValue!=null)
{ double v=Double.parseDouble(aValue.toString());
mValue+=v;
}
}
public Object getValue(long aTime)
{ double result=mValue;
mValue=0.0;
return result;
}
}
private static class RunningTotalAction extends MergeAction
{ private double mTotal;
public void update(Object aValue, long aTime)
{
if (aValue instanceof Number)
{ mTotal+=((Number)aValue).doubleValue();
}
System.out.println("total="+mTotal);
}
public Object getValue(long aTime)
{ return mTotal;
}
}
private static class AverageMapAction extends MergeAction
{ Map<String,Double> mValue=new LinkedHashMap();
Map<String,Integer> mCount=new HashMap();
public void update(Object aValue, long aTime)
{
if (aValue!=null)
{ Map<String,Object> value=(Map)aValue;
for (Map.Entry<String,Object> entry : value.entrySet())
{ String key=entry.getKey();
double v2=Double.parseDouble(entry.getValue().toString());
Double existingValue=mValue.get(key);
if (existingValue==null)
{ mCount.put(key, Integer.valueOf(1));
mValue.put(key,v2);
}
else
{ mValue.put(key,v2+existingValue);
mCount.put(key, Integer.valueOf(1+mCount.get(key)));
}
}
}
}
public Object getValue(long aTime)
{
for (Map.Entry<String,Double> entry : mValue.entrySet())
{ String key=entry.getKey();
Double existingValue=mValue.get(key);
Integer count=mCount.get(key);
mValue.put(key,existingValue/(double)count);
}
Object result=mValue;
mValue=new LinkedHashMap();
mCount.clear();
return result;
}
}
private static class AverageAction extends MergeAction
{ private Double mLastValue;
private double mTotal;
private long mLastTime;
private long mPeriodStart;
public void update(Object aValue, long aTime)
{
innerUpdate(aTime);
if (aValue instanceof Number)
{ double v=((Number)aValue).doubleValue();
mLastValue=v;
}
else if (aValue instanceof Boolean)
{ mLastValue=Boolean.TRUE.equals(aValue)?1.0:0.0;
}
else
{ mLastValue=null;
}
mLastTime=aTime;
}
private void innerUpdate(long aTime)
{ if (mLastValue!=null)
{ double duration=aTime-mLastTime;
mTotal+=mLastValue*duration;
}
}
public Object getValue(long aTime)
{
innerUpdate(aTime);
double duration=aTime-mPeriodStart;
double result=mTotal/duration;
mTotal=0.0;
mPeriodStart=aTime;
mLastTime=aTime;
return result;
}
}
private static class MaxAction extends MergeAction
{ private Double mMax;
private Double mLastGood=Double.NaN;
public void update(Object aValue, long aTime)
{ if (aValue instanceof Number)
{ double v=((Number)aValue).doubleValue();
if (mMax==null || mMax<v)
{ mMax=v;
}
mLastGood=v;
}
}
public Object getValue(long aTime)
{ Object result;
if (mMax!=null)
{ result=mMax;
}
else
{ result=mLastGood;
}
mMax=null;
return result;
}
}
private static class MinAction extends MergeAction
{ private Double mMin;
private Double mLastGood=Double.NaN;
public void update(Object aValue, long aTime)
{ if (aValue instanceof Number)
{ double v=((Number)aValue).doubleValue();
if (mMin==null || mMin>v)
{ mMin=v;
}
mLastGood=v;
}
}
public Object getValue(long aTime)
{ Object result;
if (mMin!=null)
{ result=mMin;
}
else
{ result=mLastGood;
}
mMin=null;
return result;
}
}
private static class BooleanChangeAction extends MergeAction
{ private boolean mHadFalse;
private boolean mHadTrue;
private boolean mLast;
private boolean mLastReal;
public void update(Object aValue, long aTime)
{ boolean v=(Boolean)aValue;
if (v)
{ mHadTrue=true;
}
else
{ mHadFalse=true;
}
mLastReal=v;
}
public Object getValue(long aTime)
{ boolean result;
if (mHadFalse && !mHadTrue)
{ result=false;
//mLastReal=false;
}
else if (mHadTrue && !mHadFalse)
{ result=true;
//mLastReal=true;
}
else if (mHadTrue && mHadFalse)
{ result=!mLast;
}
else
{ result=mLastReal;
}
mLast=result;
mHadFalse=false;
mHadTrue=false;
return result;
}
}
private static class BooleanRisingEdgeAction extends MergeAction
{
private Boolean mLast;
private int mCount;
public void update(Object aValue, long aTime)
{
if (Boolean.TRUE.equals(aValue) && !aValue.equals(mLast)) mCount++;
if (aValue instanceof Boolean) mLast=(Boolean)aValue;
}
public Object getValue(long aTime)
{ int result=mCount;
mCount=0;
return result;
}
}
private static class BooleanFallingEdgeAction extends MergeAction
{
private Boolean mLast;
private int mCount;
public void update(Object aValue, long aTime)
{
if (Boolean.FALSE.equals(aValue) && !aValue.equals(mLast)) mCount++;
if (aValue instanceof Boolean) mLast=(Boolean)aValue;
}
public Object getValue(long aTime)
{ int result=mCount;
mCount=0;
return result;
}
}
private static class Rot360AvgAction extends MergeAction
{ private double mValue=-1;
public void update(Object aValue,long aTime)
{ if (aValue!=null)
{ double v=Double.parseDouble(aValue.toString());
if (mValue==-1)
{ mValue=v;
}
else
{ double diff=v-mValue;
double nv;
if (diff>180)
{ nv=v-360;
}
else if (diff<-180)
{ nv=v+360;
}
else
{ nv=v;
}
mValue=mValue*0.75+nv*0.25;
}
}
}
public Object getValue(long aTime)
{ return mValue;
}
}
}
|
package wge3.game.engine.ai.tasks;
import java.util.ArrayList;
import java.util.List;
import wge3.game.entity.creatures.Creature;
import static wge3.game.engine.utilities.pathfinding.PathFinder.findPath;
import wge3.game.entity.Tile;
import static wge3.game.engine.utilities.Math.angle;
public final class MoveTask extends AITask {
private Creature executor;
private TurnTask turnTask;
private List<Tile> path;
private int position;
public MoveTask(Creature executor, Tile dest) {
this.executor = executor;
if (dest.isAnOKMoveDestinationFor(executor)) {
path = new ArrayList<Tile>(1);
path.add(dest);
} else {
path = findPath(executor.getTile(), dest);
if (path == null) return;
}
position = 0;
float angle = angle(executor.getX(), executor.getY(), path.get(position).getMiddleX(), path.get(position).getMiddleY());
turnTask = new TurnTask(executor, angle);
}
@Override
public boolean isFinished() {
return path == null || (executor.getTile().equals(getDestination()) && executor.isInCenterOfATile());
}
@Override
public void execute() {
if (!turnTask.isFinished()) {
turnTask.execute();
return;
}
if (executor.getTile().equals(path.get(position)) && executor.isInCenterOfATile()) {
position++;
float angle = angle(executor.getX(), executor.getY(), path.get(position).getMiddleX(), path.get(position).getMiddleY());
turnTask = new TurnTask(executor, angle);
} else {
executor.goForward();
}
}
public Tile getDestination() {
return path == null ? null : path.get(path.size()-1);
}
public void setDestination(Tile dest) {
if (path != null) path.set(path.size()-1, dest);
}
}
|
/* P0013
*
* Merge Sorted Array
* Given two sorted integer arrays A and B, merge B into A as one sorted array.
*
* Notes:
* 1) Allow to use an auxilary array to store the restul? (O(M+N) space)
* 2) What if the space complexity is O(1) (without additional storage)?
*/
public class P0013 {
public static void merge(int[] a, int m, int[] b, int n) {
// a.length = m + n
// b.length = n
int len = a.length;
int i = m - 1, j = n - 1;
for (int k = len - 1; k >= 0; k
if (i >= 0 && j < 0)
a[k] = a[i
else if (i < 0 && j >= 0)
a[k] = b[j
else {
if (a[i] > b[j]) {
a[k] = a[i
}
else {
a[k] = b[j
}
}
}
}
public static void print(int[] a, int len) {
for (int i = 0; i < len; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public static void main(String args[]) {
int m = 5, n = 5;
int[] tmp = {2, 5, 6, 9, 10};
int[] a = new int[m + n];
for (int i = 0; i < m; i++)
a[i] = tmp[i];
int[] b = {1, 7, 8, 11, 15};
P0013.merge(a, m, b, n);
P0013.print(a, m + n);
}
}
|
import javafx.beans.binding.DoubleBinding;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
public class NameSurferGraph extends Pane implements NameSurferConstants {
private static final int LABEL_PADDING = 2;
public NameSurferGraph() {
super();
setWhiteBackground();
drawVerticalGridLines();
drawHorizontalGridLines();
drawDecadeLabels();
}
private void setWhiteBackground() {
this.setStyle("-fx-background-color: white");
}
private void drawVerticalGridLines() {
for (int i = 0; i < NDECADES; i++) {
drawVerticalLine(i);
}
}
private void drawVerticalLine(int decadeIndex) {
Line line = new Line();
line.startXProperty().bind(getDecadeStartX(decadeIndex));
line.endXProperty().bind(line.startXProperty());
line.setStartY(0);
line.endYProperty().bind(heightProperty());
this.getChildren().add(line);
}
private void drawHorizontalGridLines() {
drawTopLine();
drawBottomLine();
}
private void drawTopLine() {
Line line = new Line();
line.setStartX(0);
line.endXProperty().bind(widthProperty());
line.setStartY(GRAPH_MARGIN_SIZE);
line.setEndY(GRAPH_MARGIN_SIZE);
this.getChildren().add(line);
}
private void drawBottomLine() {
Line line = new Line();
line.setStartX(0);
line.endXProperty().bind(widthProperty());
line.startYProperty().bind(getBottomMarginY());
line.endYProperty().bind(line.startYProperty());
this.getChildren().add(line);
}
private void drawDecadeLabels() {
for (int i = 0; i < NDECADES; i++) {
drawDecadeLabel(i);
}
}
private void drawDecadeLabel(int decadeIndex) {
Label label = new Label(Integer.toString(START_DECADE + decadeIndex * 10));
label.layoutXProperty().bind(getDecadeStartX(decadeIndex).add(LABEL_PADDING));
label.layoutYProperty().bind(getBottomMarginY().add(LABEL_PADDING));
this.getChildren().add(label);
}
public void addEntry(NameSurferEntry entry) {
for (int i = 0; i < NDECADES - 1; i++) {
drawDecadeGraphLine(i, entry.getRank(i), entry.getRank(i + 1));
}
}
private void drawDecadeGraphLine(int decadeIndex, int startRank, int endRank) {
Line line = new Line();
if (startRank == 0) {
startRank = MAX_RANK;
}
if (endRank == 0) {
endRank = MAX_RANK;
}
line.startXProperty().bind(getDecadeStartX(decadeIndex));
line.endXProperty().bind(getDecadeStartX(decadeIndex + 1));
line.startYProperty().bind(getRankY(startRank));
line.endYProperty().bind(getRankY(endRank));
this.getChildren().add(line);
}
private DoubleBinding getDecadeStartX(int decadeIndex) {
return widthProperty().divide(NDECADES).multiply(decadeIndex);
}
private DoubleBinding getBottomMarginY() {
return heightProperty().subtract(GRAPH_MARGIN_SIZE);
}
private DoubleBinding getRankY(int rank) {
return heightProperty().subtract(GRAPH_MARGIN_SIZE * 2)
.divide(MAX_RANK)
.multiply(rank)
.add(GRAPH_MARGIN_SIZE);
}
}
// public class NameSurferGraph extends GCanvas
// implements NameSurferConstants, ComponentListener {
// /**
// * Creates a new NameSurferGraph object that displays the data.
// */
// public NameSurferGraph() {
// addComponentListener(this);
// // You fill in the rest //
// /**
// * Clears the list of name surfer entries stored inside this class.
// */
// public void clear() {
// // You fill this in //
// /* Method: addEntry(entry) */
// /**
// * Adds a new NameSurferEntry to the list of entries on the display.
// * Note that this method does not actually draw the graph, but
// * simply stores the entry; the graph is drawn by calling update.
// */
// public void addEntry(NameSurferEntry entry) {
// // You fill this in //
// /**
// * Updates the display image by deleting all the graphical objects
// * from the canvas and then reassembling the display according to
// * the list of entries. Your application must call update after
// * calling either clear or addEntry; update is also called whenever
// * the size of the canvas changes.
// */
// public void update() {
// // You fill this in //
// /* Implementation of the ComponentListener interface */
// public void componentHidden(ComponentEvent e) { }
// public void componentMoved(ComponentEvent e) { }
// public void componentResized(ComponentEvent e) { update(); }
// public void componentShown(ComponentEvent e) { }
|
package org.voltdb.iv2;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.TreeMap;
import org.voltcore.messaging.TransactionInfoBaseMessage;
import org.voltcore.messaging.VoltMessage;
import org.voltdb.ClientResponseImpl;
import org.voltdb.StoredProcedureInvocation;
import org.voltdb.VoltTable;
import org.voltdb.messaging.CompleteTransactionMessage;
import org.voltdb.messaging.FragmentTaskMessage;
import org.voltdb.messaging.InitiateResponseMessage;
import org.voltdb.messaging.Iv2EndOfLogMessage;
import org.voltdb.messaging.Iv2InitiateTaskMessage;
import org.voltdb.messaging.MultiPartitionParticipantMessage;
/**
* Orders work for command log replay - where fragment tasks can show up before
* or after the partition-wise sentinels that record the correct location of a
* multi-partition work in the partition's transaction sequence.
*
* Offer a message to the replay sequencer. If the sequencer rejects this
* message, it is already correctly sequenced. Callers must check the return
* code of <code>offer</code>. If offering makes other messages available, they
* must be retrieved by calling poll() until it returns null.
*
* End of log handling: If the local partition reaches end of log first, all MPs
* blocked waiting for sentinels will be made safe, future MP fragments will
* also be safe automatically. If the MPI reaches end of log first, and there is
* an outstanding sentinel in the sequencer, then all SPs blocked after this
* sentinel will be made safe (can be polled). There cannot be any fragments in
* the replay sequencer when the MPI EOL arrives, because the MPI will only send
* EOLs when it has finished all previous MP work. NOTE: Once MPI end of log
* message is received, NONE of the SPs polled from the sequencer can be
* executed, the poller must make sure that a failure response is returned
* appropriately instead. However, SPs rejected by offer() can always be
* executed.
*
* NOTE: messages are sequenced according to the transactionId passed in to the
* offer() method. This transaction id may differ from the value stored in the
* ReplayEntry.m_firstFragment in the case of DR fragment tasks. The
* ReplaySequencer MUST do all txnId comparisons on the value passed to offer
* (which becomes a key in m_replayEntries tree map).
*/
public class ReplaySequencer
{
// place holder that associates sentinel, first fragment and
// work that follows in the transaction sequence.
private class ReplayEntry {
Long m_sentinalTxnId = null;
FragmentTaskMessage m_firstFragment = null;
private Deque<VoltMessage> m_blockedMessages = new ArrayDeque<VoltMessage>();
private boolean m_servedFragment = false;
boolean isReady()
{
if (m_mpiEOLReached) {
// no more MP fragments will arrive
return true;
} else if (m_eolReached) {
// End of log, no more sentinels, release first fragment
return m_firstFragment != null;
} else {
return m_sentinalTxnId != null && m_firstFragment != null;
}
}
boolean hasSentinel()
{
return m_sentinalTxnId != null;
}
void addBlockedMessage(VoltMessage m)
{
m_blockedMessages.addLast(m);
}
VoltMessage poll()
{
if (isReady()) {
if(!m_servedFragment && m_firstFragment != null) {
m_servedFragment = true;
return m_firstFragment;
}
else {
return m_blockedMessages.poll();
}
}
else {
return null;
}
}
boolean isEmpty() {
return isReady() && m_servedFragment && m_blockedMessages.isEmpty();
}
}
// queued entries hashed by transaction id.
TreeMap<Long, ReplayEntry> m_replayEntries = new TreeMap<Long, ReplayEntry>();
// lastPolledFragmentTxnId tracks released MP transactions; new fragments
// for released transactions do not need further sequencing.
long m_lastPolledFragmentTxnId = Long.MIN_VALUE;
// lastSeenTxnId tracks the last seen txnId for this partition
long m_lastSeenTxnId = Long.MIN_VALUE;
// has reached end of log for this partition, release any MP Txns for
// replay if this is true.
boolean m_eolReached = false;
// has reached end of log for the MPI, no more MP fragments will come,
// release all txns.
boolean m_mpiEOLReached = false;
public boolean isMPIEOLReached()
{
return m_mpiEOLReached;
}
/**
* Dedupe initiate task messages. Check if the initiate task message is seen before.
*
* @param inTxnId The txnId of the message
* @param in The initiate task message
* @return A client response to return if it's a duplicate, otherwise null.
*/
public InitiateResponseMessage dedupe(long inTxnId, TransactionInfoBaseMessage in)
{
if (in instanceof Iv2InitiateTaskMessage) {
final Iv2InitiateTaskMessage init = (Iv2InitiateTaskMessage) in;
final StoredProcedureInvocation invocation = init.getStoredProcedureInvocation();
final String procName = invocation.getProcName();
/*
* Ning - @LoadSinglepartTable and @LoadMultipartTable always have the same txnId
* which is the txnId of the snapshot.
*/
if (!(procName.equalsIgnoreCase("@LoadSinglepartitionTable") ||
procName.equalsIgnoreCase("@LoadMultipartitionTable")) &&
inTxnId <= m_lastSeenTxnId) {
// already sequenced
final InitiateResponseMessage resp = new InitiateResponseMessage(init);
resp.setResults(new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
new VoltTable[0],
ClientResponseImpl.DUPE_TRANSACTION));
return resp;
}
}
return null;
}
/**
* Update the last seen txnId for this partition if it's an initiate task message.
*
* @param inTxnId
* @param in
*/
public void updateLastSeenTxnId(long inTxnId, TransactionInfoBaseMessage in)
{
if (in instanceof Iv2InitiateTaskMessage && inTxnId > m_lastSeenTxnId) {
m_lastSeenTxnId = inTxnId;
}
}
/**
* Update the last polled txnId for this partition if it's a fragment task message.
* @param inTxnId
* @param in
*/
public void updateLastPolledTxnId(long inTxnId, TransactionInfoBaseMessage in)
{
if (in instanceof FragmentTaskMessage) {
m_lastPolledFragmentTxnId = inTxnId;
}
}
// Return the next correctly sequenced message or null if none exists.
public VoltMessage poll()
{
if (m_replayEntries.isEmpty()) {
return null;
}
/*
* If the MPI has sent EOL message to this partition, leave the
* unfinished MP entry there so that future SPs will be offered to the
* backlog and they will not get executed.
*/
if (!m_mpiEOLReached && m_replayEntries.firstEntry().getValue().isEmpty()) {
m_replayEntries.pollFirstEntry();
}
if (m_replayEntries.isEmpty()) {
return null;
}
VoltMessage m = m_replayEntries.firstEntry().getValue().poll();
updateLastPolledTxnId(m_replayEntries.firstEntry().getKey(), (TransactionInfoBaseMessage) m);
return m;
}
// Offer a new message. Return false if the offered message can be run immediately.
public boolean offer(long inTxnId, TransactionInfoBaseMessage in)
{
ReplayEntry found = m_replayEntries.get(inTxnId);
if (in instanceof Iv2EndOfLogMessage) {
if (((Iv2EndOfLogMessage) in).isMP()) {
m_mpiEOLReached = true;
} else {
m_eolReached = true;
}
return true;
}
/*
* End-of-log reached. Only FragmentTaskMessage and
* CompleteTransactionMessage can arrive at this partition once EOL is
* reached.
*
* If the txn is found, meaning that found is not null, then this might
* be the first fragment, it needs to get through in order to free any
* txns queued behind it.
*
* If the txn is not found, then there will be no matching sentinel to
* come later, and there will be no SP txns after this MP, so release
* the first fragment immediately.
*/
if (m_eolReached && found == null) {
return false;
}
if (in instanceof MultiPartitionParticipantMessage) {
/*
* DR sends multiple @LoadMultipartitionTable proc calls with the
* same txnId, which is the snapshot txnId. For each partition,
* there is a sentinel paired with the @LoadMultipartitionTable
* call. Dedupe the sentinels the same way as we dedupe fragments,
* so that there won't be sentinels end up in the sequencer where
* matching fragments are deduped.
*/
if (inTxnId <= m_lastPolledFragmentTxnId) {
return true;
}
// Incoming sentinel.
// MultiPartitionParticipantMessage mppm = (MultiPartitionParticipantMessage)in;
if (m_mpiEOLReached) {
/*
* MPI sent end of log. No more fragments or complete transaction
* messages will arrive. Ignore all sentinels.
*/
}
else if (found == null) {
ReplayEntry newEntry = new ReplayEntry();
newEntry.m_sentinalTxnId = inTxnId;
m_replayEntries.put(inTxnId, newEntry);
}
else {
found.m_sentinalTxnId = inTxnId;
assert(found.isReady());
}
}
else if (in instanceof FragmentTaskMessage) {
// already sequenced
if (inTxnId <= m_lastPolledFragmentTxnId) {
return false;
}
FragmentTaskMessage ftm = (FragmentTaskMessage)in;
if (found == null) {
ReplayEntry newEntry = new ReplayEntry();
newEntry.m_firstFragment = ftm;
m_replayEntries.put(inTxnId, newEntry);
}
else if (found.m_firstFragment == null) {
found.m_firstFragment = ftm;
assert(found.isReady());
}
else {
found.addBlockedMessage(ftm);
}
}
else if (in instanceof CompleteTransactionMessage) {
// already sequenced
if (inTxnId <= m_lastPolledFragmentTxnId) {
return false;
}
if (found != null && found.m_firstFragment != null) {
found.addBlockedMessage(in);
}
else {
// Always expect to see the fragment first, but there are places in the protocol
// where CompleteTransactionMessages may arrive for transactions that this site hasn't
// done/won't do, e.g. txn restart, so just tell the caller that we can't do
// anything with it and hope the right thing happens.
return false;
}
}
else {
if (dedupe(inTxnId, in) != null) {
// Ignore an already seen txn
return true;
}
updateLastSeenTxnId(inTxnId, in);
if (m_replayEntries.isEmpty() || !m_replayEntries.lastEntry().getValue().hasSentinel()) {
// not-blocked work; rejected and not queued.
return false;
}
else {
// blocked work queues with the newest replayEntry
m_replayEntries.lastEntry().getValue().addBlockedMessage(in);
}
}
return true;
}
}
|
package gov.doe.kbase.scripts;
import gov.doe.kbase.scripts.util.ProcessHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.googlecode.jsonschema2pojo.DefaultGenerationConfig;
import com.googlecode.jsonschema2pojo.Jackson1Annotator;
import com.googlecode.jsonschema2pojo.SchemaGenerator;
import com.googlecode.jsonschema2pojo.SchemaMapper;
import com.googlecode.jsonschema2pojo.SchemaStore;
import com.googlecode.jsonschema2pojo.rules.Rule;
import com.googlecode.jsonschema2pojo.rules.RuleFactory;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
public class JavaTypeGenerator {
private static final char[] propWordDelim = {'_', '-'};
private static final String utilPackage = "gov.doe.kbase";
public static void main(String[] args) throws Exception {
Args parsedArgs = new Args();
CmdLineParser parser = new CmdLineParser(parsedArgs);
parser.setUsageWidth(85);
try {
parser.parseArgument(args);
} catch( CmdLineException e ) {
String message = e.getMessage();
showUsage(parser, message);
return;
}
File inputFile = parsedArgs.specFile;
File tempDir = parsedArgs.tempDir == null ? inputFile.getAbsoluteFile().getParentFile() : new File(parsedArgs.tempDir);
boolean deleteTempDir = false;
if (!tempDir.exists()) {
tempDir.mkdir();
deleteTempDir = true;
}
File srcOutDir = null;
String packageParent = parsedArgs.packageParent;
File libDir = null;
if (parsedArgs.outputDir == null) {
if (parsedArgs.srcDir == null) {
showUsage(parser, "Either -o or -s parameter should be defined");
return;
}
srcOutDir = new File(parsedArgs.srcDir);
libDir = parsedArgs.libDir == null ? null : new File(parsedArgs.libDir);
} else {
srcOutDir = new File(parsedArgs.outputDir, "src");
libDir = new File(parsedArgs.outputDir, "lib");
}
boolean createServer = parsedArgs.createServerSide;
processSpec(inputFile, tempDir, srcOutDir, packageParent, createServer, libDir);
if (deleteTempDir)
tempDir.delete();
}
private static void showUsage(CmdLineParser parser, String message) {
System.err.println(message);
System.err.println("Usage: <program> [options...] <spec-file>");
parser.printUsage(System.err);
}
public static JavaData processSpec(File specFile, File tempDir, File srcOutDir, String packageParent, boolean createServer, File libOutDir) throws Exception {
return processJson(transformSpecToJson(specFile, tempDir), new File(tempDir, "json-schemas"), srcOutDir, packageParent, createServer, libOutDir);
}
public static File transformSpecToJson(File specFile, File tempDir) throws Exception {
File bashFile = new File(tempDir, "comp_server.sh");
File serverOutDir = new File(tempDir, "server_out");
serverOutDir.mkdir();
File specDir = specFile.getAbsoluteFile().getParentFile();
File retFile = new File(tempDir, "jsync_parsing_file.json");
File outFile = new File(tempDir, "comp.out");
File errFile = new File(tempDir, "comp.err");
List<String> lines = new ArrayList<String>(Arrays.asList("#!/bin/bash"));
checkEnvVar("KB_TOP", lines, "/kb/deployment");
checkEnvVar("KB_RUNTIME", lines, "/kb/runtime");
checkEnvVar("PATH", lines, "/kb/runtime/bin", "/kb/deployment/bin");
checkEnvVar("PERL5LIB", lines, "/kb/deployment/lib");
lines.add("perl /kb/deployment/plbin/compile_typespec.pl --path \"" + specDir.getAbsolutePath() + "\"" +
" --jsync " + retFile.getName() + " \"" + specFile.getAbsolutePath() + "\" " +
serverOutDir.getName() + " >" + outFile.getName() + " 2>" + errFile.getName()
);
Utils.writeFileLines(lines, bashFile);
ProcessHelper.cmd("bash", bashFile.getCanonicalPath()).exec(tempDir);
File jsyncFile = new File(serverOutDir, retFile.getName());
if (jsyncFile.exists()) {
Utils.writeFileLines(Utils.readFileLines(jsyncFile), retFile);
} else {
List<String> errLines = Utils.readFileLines(errFile);
if (errLines.size() > 1 || (errLines.size() == 1 && errLines.get(0).trim().length() > 0)) {
for (String errLine : errLines)
System.err.println(errLine);
}
}
bashFile.delete();
Utils.deleteRecursively(serverOutDir);
outFile.delete();
errFile.delete();
if (!retFile.exists()) {
throw new IllegalStateException("Wrong process state, jsync file wasn't created");
}
return retFile;
}
private static void checkEnvVar(String varName, List<String> shellLines, String... partPath) {
String value = System.getenv(varName);
Set<String> paths = new HashSet<String>();
if (value != null) {
String[] parts = value.split(":");
for (String part : parts)
if (part.trim().length() > 0)
paths.add(part.trim());
}
StringBuilder newValue = new StringBuilder();
for (String path : partPath)
if (!paths.contains(path))
newValue.append(path).append(":");
if (newValue.length() > 0)
shellLines.add("export " + varName + "=" + newValue.append("$").append(varName));
}
public static JavaData processJson(File jsonParsingFile, File jsonSchemaOutDir, File srcOutDir, String packageParent, boolean createServer, File libOutDir) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.INDENT_OUTPUT, true);
Map<?,?> map = mapper.readValue(jsonParsingFile, Map.class);
JSyncProcessor subst = new JSyncProcessor(map);
List<KbService> srvList = KbService.loadFromMap(map, subst);
JavaData data = prepareDataStructures(srvList);
jsonParsingFile.delete();
outputData(data, jsonSchemaOutDir, srcOutDir, packageParent, createServer, libOutDir);
return data;
}
private static JavaData prepareDataStructures(List<KbService> services) {
Set<JavaType> nonPrimitiveTypes = new TreeSet<JavaType>();
JavaData data = new JavaData();
for (KbService service: services) {
for (KbModule module : service.getModules()) {
List<JavaFunc> funcs = new ArrayList<JavaFunc>();
Set<Integer> tupleTypes = data.getTupleTypes();
for (KbModuleComp comp : module.getModuleComponents()) {
if (comp instanceof KbFuncdef) {
String moduleName = module.getModuleName();
KbFuncdef func = (KbFuncdef)comp;
String funcJavaName = Utils.inCamelCase(func.getName());
List<JavaFuncParam> params = new ArrayList<JavaFuncParam>();
for (KbParameter param : func.getParameters()) {
JavaType type = findBasic(param.getType(), module.getModuleName(), nonPrimitiveTypes, tupleTypes);
params.add(new JavaFuncParam(param, Utils.inCamelCase(param.getName()), type));
}
List<JavaFuncParam> returns = new ArrayList<JavaFuncParam>();
for (KbParameter param : func.getReturnType()) {
JavaType type = findBasic(param.getType(), module.getModuleName(), nonPrimitiveTypes, tupleTypes);
returns.add(new JavaFuncParam(param, param.getName() == null ? null : Utils.inCamelCase(param.getName()), type));
}
JavaType retMultiType = null;
if (returns.size() > 1) {
List<KbType> subTypes = new ArrayList<KbType>();
for (JavaFuncParam retPar : returns)
subTypes.add(retPar.getOriginal().getType());
KbTuple tuple = new KbTuple(subTypes);
retMultiType = new JavaType(null, tuple, moduleName, new ArrayList<KbTypedef>());
for (JavaFuncParam retPar : returns)
retMultiType.addInternalType(retPar.getType());
tupleTypes.add(returns.size());
}
funcs.add(new JavaFunc(moduleName, func, funcJavaName, params, returns, retMultiType));
} else {
findBasic((KbTypedef)comp, module.getModuleName(), nonPrimitiveTypes, tupleTypes);
}
}
data.addModule(module, funcs);
}
}
data.setTypes(nonPrimitiveTypes);
return data;
}
private static void outputData(JavaData data, File jsonOutDir, File srcOutDir, String packageParent, boolean createServers, File libOutDir) throws Exception {
if (!srcOutDir.exists())
srcOutDir.mkdirs();
generatePojos(data, jsonOutDir, srcOutDir, packageParent);
generateTupleClasses(data,srcOutDir, packageParent);
generateClientClass(data, srcOutDir, packageParent);
if (createServers)
generateServerClass(data, srcOutDir, packageParent);
checkUtilityClasses(srcOutDir, createServers);
checkLibs(libOutDir, createServers);
}
private static void generatePojos(JavaData data, File jsonOutDir,
File srcOutDir, String packageParent) throws Exception {
for (JavaType type : data.getTypes()) {
Set<Integer> tupleTypes = data.getTupleTypes();
File dir = new File(jsonOutDir, type.getModuleName());
if (!dir.exists())
dir.mkdirs();
File jsonFile = new File(dir, type.getJavaClassName() + ".json");
writeJsonSchema(jsonFile, packageParent, type, tupleTypes);
}
JCodeModel codeModel = new JCodeModel();
DefaultGenerationConfig cfg = new DefaultGenerationConfig() {
@Override
public char[] getPropertyWordDelimiters() {
return propWordDelim;
}
@Override
public boolean isIncludeHashcodeAndEquals() {
return false;
}
@Override
public boolean isIncludeToString() {
return false;
}
@Override
public boolean isIncludeJsr303Annotations() {
return false;
}
@Override
public boolean isGenerateBuilders() {
return true;
}
};
SchemaStore ss = new SchemaStore();
RuleFactory rf = new RuleFactory(cfg, new Jackson1Annotator(), ss) {
@Override
public Rule<JPackage, JType> getObjectRule() {
return new JsonSchemaToPojoCustomObjectRule(this);
}
};
SchemaGenerator sg = new SchemaGenerator();
SchemaMapper sm = new SchemaMapper(rf, sg);
for (JavaType type : data.getTypes()) {
File jsonFile = new File(new File(jsonOutDir, type.getModuleName()), type.getJavaClassName() + ".json");
URL source = jsonFile.toURI().toURL();
sm.generate(codeModel, type.getJavaClassName(), "", source);
}
codeModel.build(srcOutDir);
Utils.deleteRecursively(jsonOutDir);
}
private static void generateTupleClasses(JavaData data, File srcOutDir, String packageParent) throws Exception {
Set<Integer> tupleTypes = data.getTupleTypes();
if (tupleTypes.size() > 0) {
File utilDir = new File(srcOutDir.getAbsolutePath() + "/" + utilPackage.replace('.', '/'));
if (!utilDir.exists())
utilDir.mkdirs();
for (int tupleType : tupleTypes) {
if (tupleType < 1)
throw new IllegalStateException("Wrong tuple type: " + tupleType);
File tupleFile = new File(utilDir, "Tuple" + tupleType + ".java");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tupleType; i++) {
if (sb.length() > 0)
sb.append(", ");
sb.append('T').append(i+1);
}
List<String> classLines = new ArrayList<String>(Arrays.asList(
"package " + utilPackage + ";",
"",
"import java.util.HashMap;",
"import java.util.Map;",
"import org.codehaus.jackson.annotate.JsonAnyGetter;",
"import org.codehaus.jackson.annotate.JsonAnySetter;",
"",
"public class Tuple" + tupleType + " <" + sb + "> {"
));
for (int i = 0; i < tupleType; i++) {
classLines.add(" private T" + (i + 1) + " e" + (i + 1) + ";");
}
classLines.add(" private Map<String, Object> additionalProperties = new HashMap<String, Object>();");
for (int i = 0; i < tupleType; i++) {
classLines.addAll(Arrays.asList(
"",
" public T" + (i + 1) + " getE" + (i + 1) + "() {",
" return e" + (i + 1) + ";",
" }",
"",
" public void setE" + (i + 1) + "(T" + (i + 1) + " e" + (i + 1) + ") {",
" this.e" + (i + 1) + " = e" + (i + 1) + ";",
" }",
"",
" public Tuple" + tupleType + "<" + sb + "> withE" + (i + 1) + "(T" + (i + 1) + " e" + (i + 1) + ") {",
" this.e" + (i + 1) + " = e" + (i + 1) + ";",
" return this;",
" }"
));
}
classLines.addAll(Arrays.asList(
"",
" @JsonAnyGetter",
" public Map<String, Object> getAdditionalProperties() {",
" return this.additionalProperties;",
" }",
"",
" @JsonAnySetter",
" public void setAdditionalProperties(String name, Object value) {",
" this.additionalProperties.put(name, value);",
" }",
"}"
));
Utils.writeFileLines(classLines, tupleFile);
}
}
}
private static File getParentSourceDir(File srcOutDir, String packageParent) {
File parentDir = new File(srcOutDir.getAbsolutePath() + "/" + packageParent.replace('.', '/'));
if (!parentDir.exists())
parentDir.mkdirs();
return parentDir;
}
private static void generateClientClass(JavaData data, File srcOutDir, String packageParent) throws Exception {
File parentDir = getParentSourceDir(srcOutDir, packageParent);
for (JavaModule module : data.getModules()) {
File moduleDir = new File(parentDir, module.getModuleName());
if (!moduleDir.exists())
moduleDir.mkdir();
JavaImportHolder model = new JavaImportHolder(packageParent + "." + module.getModuleName());
String clientClassName = Utils.capitalize(module.getModuleName()) + "Client";
File classFile = new File(moduleDir, clientClassName + ".java");
String callerClass = model.ref(utilPackage + ".JsonClientCaller");
boolean anyAuth = false;
for (JavaFunc func : module.getFuncs()) {
if (func.isAuthRequired()) {
anyAuth = true;
break;
}
}
List<String> classLines = new ArrayList<String>(Arrays.asList(
"public class " + clientClassName + " {",
" private " + callerClass + " caller;",
"",
" public " + clientClassName + "(String url) throws " + model.ref("java.net.MalformedURLException") + " {",
" caller = new " + callerClass + "(url);",
" }",
""
));
if (anyAuth) {
classLines.addAll(Arrays.asList(
" public " + clientClassName + "(String url, String token) throws " + model.ref("java.net.MalformedURLException") + " {",
" caller = new " + callerClass + "(url, token);",
" }",
"",
" public " + clientClassName + "(String url, String user, String password) throws " + model.ref("java.net.MalformedURLException") + " {",
" caller = new " + callerClass + "(url, user, password);",
" }",
""
));
}
for (JavaFunc func : module.getFuncs()) {
JavaType retType = null;
if (func.getRetMultyType() == null) {
if (func.getReturns().size() > 0) {
retType = func.getReturns().get(0).getType();
}
} else {
retType = func.getRetMultyType();
}
StringBuilder funcParams = new StringBuilder();
for (JavaFuncParam param : func.getParams()) {
if (funcParams.length() > 0)
funcParams.append(", ");
funcParams.append(getJType(param.getType(), packageParent, model)).append(" ").append(param.getJavaName());
}
String retTypeName = retType == null ? "void" : getJType(retType, packageParent, model);
String listClass = model.ref("java.util.List");
String arrayListClass = model.ref("java.util.ArrayList");
classLines.add("");
classLines.add(" public " + retTypeName + " " + func.getJavaName() + "(" + funcParams + ") throws Exception {");
classLines.add(" " + listClass + "<Object> args = new " + arrayListClass + "<Object>();");
for (JavaFuncParam param : func.getParams()) {
classLines.add(" args.add(" + param.getJavaName() + ");");
}
String typeReferenceClass = model.ref("org.codehaus.jackson.type.TypeReference");
boolean authRequired = func.isAuthRequired();
boolean needRet = retType != null;
if (func.getRetMultyType() == null) {
if (retType == null) {
String trFull = typeReferenceClass + "<Object>";
classLines.addAll(Arrays.asList(
" " + trFull + " retType = new " + trFull + "() {};",
" caller.jsonrpcCall(\"" + module.getOriginal().getModuleName() + "." + func.getOriginal().getName() + "\", args, retType, " + needRet + ", " + authRequired + ");",
" }"
));
} else {
String trFull = typeReferenceClass + "<" + listClass + "<" + retTypeName + ">>";
classLines.addAll(Arrays.asList(
" " + trFull + " retType = new " + trFull + "() {};",
" " + listClass + "<" + retTypeName + "> res = caller.jsonrpcCall(\"" + module.getOriginal().getModuleName() + "." + func.getOriginal().getName() + "\", args, retType, " + needRet + ", " + authRequired + ");",
" return res.get(0);",
" }"
));
}
} else {
String trFull = typeReferenceClass + "<" + retTypeName + ">";
classLines.addAll(Arrays.asList(
" " + trFull + " retType = new " + trFull + "() {};",
" " + retTypeName + " res = caller.jsonrpcCall(\"" + module.getOriginal().getModuleName() + "." + func.getOriginal().getName() + "\", args, retType, " + needRet + ", " + authRequired + ");",
" return res;",
" }"
));
}
}
classLines.add("}");
List<String> headerLines = new ArrayList<String>(Arrays.asList(
"package " + packageParent + "." + module.getModuleName() + ";",
""
));
headerLines.addAll(model.generateImports());
headerLines.add("");
classLines.addAll(0, headerLines);
Utils.writeFileLines(classLines, classFile);
}
}
private static String backupExtension() {
String ret = ".bak-";
Calendar now = Calendar.getInstance();
ret += now.get(Calendar.YEAR) + "-";
ret += String.format("%02d", now.get(Calendar.MONTH) + 1) + "-";
ret += String.format("%02d", now.get(Calendar.DAY_OF_MONTH)) + "-";
ret += String.format("%02d", now.get(Calendar.HOUR)) + "-";
ret += String.format("%02d", now.get(Calendar.MINUTE)) + "-";
ret += String.format("%02d", now.get(Calendar.SECOND));
return ret;
}
private static final String HEADER = "HEADER";
private static final String CLSHEADER = "CLASS_HEADER";
private static final String CONSTRUCTOR = "CONSTRUCTOR";
private static final String METHOD = "METHOD_";
private static final Pattern PAT_HEADER = Pattern.compile(
".*//BEGIN_HEADER\n(.*)//END_HEADER.*", Pattern.DOTALL);
private static final Pattern PAT_CLASS_HEADER = Pattern.compile(
".*//BEGIN_CLASS_HEADER\n(.*) //END_CLASS_HEADER.*", Pattern.DOTALL);
private static final Pattern PAT_CONSTRUCTOR = Pattern.compile(
".*//BEGIN_CONSTRUCTOR\n(.*) //END_CONSTRUCTOR.*", Pattern.DOTALL);
private static void checkMatch(HashMap<String, String> code, Pattern matcher,
String oldserver, String codekey, String errortype, boolean exceptOnFail)
throws ParseException {
Matcher m = matcher.matcher(oldserver);
if (!m.matches()) {
if (exceptOnFail) {
throw new ParseException("Missing " + errortype +
" in original file", 0);
} else {
return;
}
}
code.put(codekey, m.group(1));
}
private static HashMap<String, String> parsePrevCode(File classFile, List<JavaFunc> funcs)
throws IOException, ParseException {
HashMap<String, String> code = new HashMap<String, String>();
if (!classFile.exists()) {
return code;
}
File backup = new File(classFile.getAbsoluteFile() + backupExtension());
FileUtils.copyFile(classFile, backup);
String oldserver = IOUtils.toString(new FileReader(classFile));
checkMatch(code, PAT_HEADER, oldserver, HEADER, "header", true);
checkMatch(code, PAT_CLASS_HEADER, oldserver, CLSHEADER, "class header", true);
checkMatch(code, PAT_CONSTRUCTOR, oldserver, CONSTRUCTOR, "constructor", true);
for (JavaFunc func: funcs) {
String name = func.getOriginal().getName();
Pattern p = Pattern.compile(MessageFormat.format(
".*//BEGIN {0}\n(.*) //END {0}.*", name), Pattern.DOTALL);
checkMatch(code, p, oldserver, METHOD + name, "method " + name, false);
}
return code;
}
private static List<String> splitCodeLines(String code) {
LinkedList<String> l = new LinkedList<String>();
if (code.length() == 0) { //returns empty string otherwise
return l;
}
return Arrays.asList(code.split("\n"));
}
private static void generateServerClass(JavaData data, File srcOutDir, String packageParent) throws Exception {
File parentDir = getParentSourceDir(srcOutDir, packageParent);
for (JavaModule module : data.getModules()) {
File moduleDir = new File(parentDir, module.getModuleName());
if (!moduleDir.exists())
moduleDir.mkdir();
JavaImportHolder model = new JavaImportHolder(packageParent + "." + module.getModuleName());
String serverClassName = Utils.capitalize(module.getModuleName()) + "Server";
File classFile = new File(moduleDir, serverClassName + ".java");
HashMap<String, String> originalCode = parsePrevCode(classFile, module.getFuncs());
List<String> classLines = new ArrayList<String>(Arrays.asList(
"public class " + serverClassName + " extends " + model.ref(utilPackage + ".JsonServerServlet") + " {",
" private static final long serialVersionUID = 1L;",
"",
" public static void main(String[] args) throws Exception {",
" if (args.length != 1) {",
" System.out.println(\"Usage: <program> <server_port>\");",
" return;",
" }",
" new " + serverClassName + "().startupServer(Integer.parseInt(args[0]));",
" }",
""
));
classLines.add(" //BEGIN_CLASS_HEADER");
List<String> classHeader = splitCodeLines(originalCode.get(CLSHEADER));
classLines.addAll(classHeader);
classLines.add(" //END_CLASS_HEADER");
classLines.add("");
classLines.add(" public " + serverClassName + "() throws Exception {");
classLines.add(" //BEGIN_CONSTRUCTOR");
List<String> constructor = splitCodeLines(originalCode.get(CONSTRUCTOR));
classLines.addAll(constructor);
classLines.addAll(Arrays.asList(
" //END_CONSTRUCTOR",
" }"
));
for (JavaFunc func : module.getFuncs()) {
JavaType retType = null;
if (func.getRetMultyType() == null) {
if (func.getReturns().size() > 0) {
retType = func.getReturns().get(0).getType();
}
} else {
retType = func.getRetMultyType();
}
StringBuilder funcParams = new StringBuilder();
for (JavaFuncParam param : func.getParams()) {
if (funcParams.length() > 0)
funcParams.append(", ");
funcParams.append(getJType(param.getType(), packageParent, model)).append(" ").append(param.getJavaName());
}
String retTypeName = retType == null ? "void" : getJType(retType, packageParent, model);
classLines.add("");
classLines.add(" @" + model.ref(utilPackage + ".JsonServerMethod") + "(rpc = \"" + module.getOriginal().getModuleName() + "." + func.getOriginal().getName() + "\"" +
(func.getRetMultyType() == null ? "" : ", tuple = true") + ")");
classLines.add(" public " + retTypeName + " " + func.getJavaName() + "(" + funcParams + ") throws Exception {");
List<String> funcLines = new LinkedList<String>();
String name = func.getOriginal().getName();
if (originalCode.containsKey(METHOD + name)) {
funcLines.addAll(splitCodeLines(originalCode.get(METHOD + name)));
}
funcLines.add(0, " //BEGIN " + name);
funcLines.add(" //END " + name);
if (func.getRetMultyType() == null) {
if (retType == null) {
classLines.addAll(funcLines);
classLines.add(" }");
} else {
classLines.add(" " + retTypeName + " ret = null;");
classLines.addAll(funcLines);
classLines.addAll(Arrays.asList(
" return ret;",
" }"
));
}
} else {
for (int retPos = 0; retPos < func.getReturns().size(); retPos++) {
String retInnerType = getJType(func.getReturns().get(retPos).getType(), packageParent, model);
classLines.add(" " + retInnerType + " ret" + (retPos + 1) + " = null;");
}
classLines.addAll(funcLines);
classLines.add(" " + retTypeName + " ret = new " + retTypeName + "();");
for (int retPos = 0; retPos < func.getReturns().size(); retPos++) {
classLines.add(" ret.setE" + (retPos + 1) + "(ret" + (retPos + 1) + ");");
}
classLines.add(" return ret;");
classLines.add(" }");
}
}
classLines.add("}");
List<String> headerLines = new ArrayList<String>(Arrays.asList(
"package " + packageParent + "." + module.getModuleName() + ";",
""
));
headerLines.addAll(model.generateImports());
headerLines.add("");
headerLines.add("//BEGIN_HEADER");
List<String> customheader = splitCodeLines(originalCode.get(HEADER));
headerLines.addAll(customheader);
headerLines.add("//END_HEADER");
headerLines.add("");
classLines.addAll(0, headerLines);
Utils.writeFileLines(classLines, classFile);
}
}
private static void checkUtilityClasses(File srcOutDir, boolean createServers) throws Exception {
checkUtilityClass(srcOutDir, "JsonClientCaller");
checkUtilityClass(srcOutDir, "JacksonTupleModule");
checkUtilityClass(srcOutDir, "UObject");
if (createServers) {
checkUtilityClass(srcOutDir, "JsonServerMethod");
checkUtilityClass(srcOutDir, "JsonServerServlet");
}
}
private static void checkUtilityClass(File srcOutDir, String className) throws Exception {
File dir = new File(srcOutDir.getAbsolutePath() + "/" + utilPackage.replace('.', '/'));
if (!dir.exists())
dir.mkdirs();
File dstClassFile = new File(dir, className + ".java");
if (dstClassFile.exists())
return;
Utils.writeFileLines(Utils.readStreamLines(JavaTypeGenerator.class.getResourceAsStream(
className + ".java.properties")), dstClassFile);
}
private static void checkLibs(File libOutDir, boolean createServers) throws Exception {
if (libOutDir == null)
return;
if (!libOutDir.exists())
libOutDir.mkdirs();
checkLib(libOutDir, "jackson-all-1.9.11");
if (createServers) {
checkLib(libOutDir, "servlet-api-2.5");
checkLib(libOutDir, "jetty-all-7.0.0");
}
}
private static void checkLib(File libDir, String libName) throws Exception {
String libFileName = libName + ".jar";
InputStream is = JavaTypeGenerator.class.getResourceAsStream(libFileName + ".properties");
OutputStream os = new FileOutputStream(new File(libDir, libFileName));
Utils.copyStreams(is, os);
}
private static void writeJsonSchema(File jsonFile, String packageParent, JavaType type,
Set<Integer> tupleTypes) throws Exception {
LinkedHashMap<String, Object> tree = new LinkedHashMap<String, Object>();
tree.put("$schema", "http://json-schema.org/draft-04/schema
tree.put("id", type.getModuleName() + "." + type.getJavaClassName());
tree.put("description", type.getComment());
tree.put("type", "object");
tree.put("javaType", packageParent + "." + type.getModuleName() + "." + type.getJavaClassName());
if (type.getMainType() instanceof KbMapping) {
JavaType firstInternal = type.getInternalTypes().get(0);
if (!firstInternal.getJavaClassName().equals("String"))
throw new IllegalStateException("Type [" + firstInternal.getOriginalTypeName() + "] " +
"can not be used as map key type");
JavaType subType = type.getInternalTypes().get(1);
LinkedHashMap<String, Object> typeTree = createJsonRefTypeTree(type.getModuleName(), subType,
null, false, packageParent, tupleTypes);
tree.put("additionalProperties", typeTree);
throw new IllegalStateException();
} else {
LinkedHashMap<String, Object> props = new LinkedHashMap<String, Object>();
for (int itemPos = 0; itemPos < type.getInternalTypes().size(); itemPos++) {
JavaType iType = type.getInternalTypes().get(itemPos);
String field = type.getInternalFields().get(itemPos);
props.put(field, createJsonRefTypeTree(type.getModuleName(), iType,
type.getInternalComment(itemPos), false, packageParent, tupleTypes));
}
tree.put("properties", props);
tree.put("additionalProperties", true);
}
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.INDENT_OUTPUT, true);
mapper.writeValue(jsonFile, tree);
}
private static LinkedHashMap<String, Object> createJsonRefTypeTree(String module, JavaType type, String comment,
boolean insideTypeParam, String packageParent, Set<Integer> tupleTypes) {
LinkedHashMap<String, Object> typeTree = new LinkedHashMap<String, Object>();
if (comment != null && comment.trim().length() > 0)
typeTree.put("description", comment);
if (type.needClassGeneration()) {
if (insideTypeParam) {
typeTree.put("type", "object");
typeTree.put("javaType", packageParent + "." + type.getModuleName() + "." + type.getJavaClassName());
} else {
String modulePrefix = type.getModuleName().equals(module) ? "" : ("../" + type.getModuleName() + "/");
typeTree.put("$ref", modulePrefix + type.getJavaClassName() + ".json");
}
} else if (type.getMainType() instanceof KbScalar) {
if (insideTypeParam) {
typeTree.put("type", "object");
typeTree.put("javaType", ((KbScalar)type.getMainType()).getJavaStyleName());
} else {
typeTree.put("type", ((KbScalar)type.getMainType()).getJsonStyleName());
}
} else if (type.getMainType() instanceof KbList) {
LinkedHashMap<String, Object> subType = createJsonRefTypeTree(module, type.getInternalTypes().get(0), null,
insideTypeParam, packageParent, tupleTypes);
if (insideTypeParam) {
typeTree.put("type", "object");
typeTree.put("javaType", "java.util.List");
typeTree.put("javaTypeParams", subType);
} else {
typeTree.put("type", "array");
typeTree.put("items", subType);
}
} else if (type.getMainType() instanceof KbMapping) {
typeTree.put("type", "object");
typeTree.put("javaType", "java.util.Map");
List<LinkedHashMap<String, Object>> subList = new ArrayList<LinkedHashMap<String, Object>>();
for (JavaType iType : type.getInternalTypes())
subList.add(createJsonRefTypeTree(module, iType, null, true, packageParent, tupleTypes));
typeTree.put("javaTypeParams", subList);
} else if (type.getMainType() instanceof KbTuple) {
typeTree.put("type", "object");
int tupleType = type.getInternalTypes().size();
if (tupleType < 1)
throw new IllegalStateException("Wrong count of tuple parameters: " + tupleType);
typeTree.put("javaType", utilPackage + ".Tuple" + tupleType);
tupleTypes.add(tupleType);
List<LinkedHashMap<String, Object>> subList = new ArrayList<LinkedHashMap<String, Object>>();
for (JavaType iType : type.getInternalTypes())
subList.add(createJsonRefTypeTree(module, iType, null, true, packageParent, tupleTypes));
typeTree.put("javaTypeParams", subList);
} else if (type.getMainType() instanceof KbUnspecifiedObject) {
typeTree.put("type", "object");
typeTree.put("javaType", "java.lang.Object");
} else {
throw new IllegalStateException("Unknown type: " + type.getMainType().getClass().getName());
}
return typeTree;
}
private static JavaType findBasic(KbType type, String moduleName, Set<JavaType> nonPrimitiveTypes, Set<Integer> tupleTypes) {
JavaType ret = findBasic(null, type, moduleName, null, new ArrayList<KbTypedef>(), nonPrimitiveTypes, tupleTypes);
return ret;
}
private static JavaType findBasic(String typeName, KbType type, String defaultModuleName, String typeModuleName,
List<KbTypedef> aliases, Set<JavaType> nonPrimitiveTypes, Set<Integer> tupleTypes) {
if (type instanceof KbBasicType) {
JavaType ret = new JavaType(typeName, (KbBasicType)type,
typeModuleName == null ? defaultModuleName : typeModuleName, aliases);
if (!(type instanceof KbScalar || type instanceof KbUnspecifiedObject))
if (type instanceof KbStruct) {
for (KbStructItem item : ((KbStruct)type).getItems()) {
ret.addInternalType(findBasic(null, item.getItemType(), defaultModuleName, null,
new ArrayList<KbTypedef>(), nonPrimitiveTypes, tupleTypes));
ret.addInternalField(item.getName(), "");
}
} else if (type instanceof KbList) {
ret.addInternalType(findBasic(null, ((KbList)type).getElementType(), defaultModuleName, null,
new ArrayList<KbTypedef>(), nonPrimitiveTypes, tupleTypes));
} else if (type instanceof KbMapping) {
ret.addInternalType(findBasic(null, ((KbMapping)type).getKeyType(), defaultModuleName, null,
new ArrayList<KbTypedef>(), nonPrimitiveTypes, tupleTypes));
ret.addInternalType(findBasic(null, ((KbMapping)type).getValueType(), defaultModuleName, null,
new ArrayList<KbTypedef>(), nonPrimitiveTypes, tupleTypes));
} else if (type instanceof KbTuple) {
tupleTypes.add(((KbTuple)type).getElementTypes().size());
for (KbType iType : ((KbTuple)type).getElementTypes())
ret.addInternalType(findBasic(null, iType, defaultModuleName, null,
new ArrayList<KbTypedef>(), nonPrimitiveTypes, tupleTypes));
} else {
throw new IllegalStateException("Unknown basic type: " + type.getClass().getSimpleName());
}
if (ret.needClassGeneration())
nonPrimitiveTypes.add(ret);
return ret;
} else {
KbTypedef typeRef = (KbTypedef)type;
aliases.add(typeRef);
return findBasic(typeRef.getName(), typeRef.getAliasType(), defaultModuleName, typeRef.getModule(),
aliases, nonPrimitiveTypes, tupleTypes);
}
}
private static String getJType(JavaType type, String packageParent, JavaImportHolder codeModel) throws Exception {
KbBasicType kbt = type.getMainType();
if (type.needClassGeneration()) {
return codeModel.ref(getPackagePrefix(packageParent, type) + type.getJavaClassName());
} else if (kbt instanceof KbScalar) {
return codeModel.ref(((KbScalar)kbt).getFullJavaStyleName());
} else if (kbt instanceof KbList) {
return codeModel.ref("java.util.List") + "<" + getJType(type.getInternalTypes().get(0), packageParent, codeModel) + ">";
} else if (kbt instanceof KbMapping) {
return codeModel.ref("java.util.Map")+ "<" + getJType(type.getInternalTypes().get(0), packageParent, codeModel) + "," +
getJType(type.getInternalTypes().get(1), packageParent, codeModel) + ">";
} else if (kbt instanceof KbTuple) {
int paramCount = type.getInternalTypes().size();
StringBuilder narrowParams = new StringBuilder();
for (JavaType iType : type.getInternalTypes()) {
if (narrowParams.length() > 0)
narrowParams.append(", ");
narrowParams.append(getJType(iType, packageParent, codeModel));
}
return codeModel.ref(utilPackage + "." + "Tuple" + paramCount) + "<" + narrowParams + ">";
} else if (kbt instanceof KbUnspecifiedObject) {
return codeModel.ref("java.lang.Object");
} else {
throw new IllegalStateException("Unknown data type: " + kbt.getClass().getName());
}
}
private static String getPackagePrefix(String packageParent, JavaType type) {
return packageParent + "." + type.getModuleName() + ".";
}
public static class Args {
@Option(name="-o",usage="Output folder (src and lib subfolders will be created), use -s and possibly -l instead of -o for more detailed settings", metaVar="<out-dir>")
String outputDir;
@Option(name="-s",usage="Source output folder (exclusive with -o)", metaVar="<src-dir>")
String srcDir;
@Option(name="-l",usage="Library output folder (exclusive with -o, not required when using -s)", metaVar="<lib-dir>")
String libDir;
@Option(name="-p",usage="Java package parent (module subpackages are created in this package), default value is gov.doe.kbase", metaVar="<package>")
String packageParent = "gov.doe.kbase";
@Option(name="-t", usage="Temporary folder, default value is parent folder of <spec-file>", metaVar="<tmp-dir>")
String tempDir;
@Option(name="-S", usage="Defines whether or not java code for server side should be created, default value is false", metaVar="<boolean>")
boolean createServerSide = false;
@Argument(metaVar="<spec-file>",required=true,usage="File *.spec for compilation into java classes")
File specFile;
}
}
|
package gov.nih.nci.calab.dto.workflow;
import gov.nih.nci.calab.domain.InputFile;
import gov.nih.nci.calab.domain.OutputFile;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.Date;
/**
* @author zengje
*
*/
public class FileBean {
private String id = "";
private String path = "";
private String filename = "";
private String createDateStr = "";
private String fileSubmitter = "";
private String fileMaskStatus = "";
private Date createdDate;
private String shortFilename = "";
private String inoutType = "";
public FileBean() {
super();
// TODO Auto-generated constructor stub
}
// used in WorkflowResultBean
public FileBean(String id, String path, String fileSubmissionDate,
String fileSubmitter, String fileMaskStatus, String inoutType) {
this.id = id;
this.path = path;
this.createDateStr = fileSubmissionDate;
this.fileSubmitter = fileSubmitter;
this.filename = getFileName(path);
this.fileMaskStatus = (fileMaskStatus.length() == 0 && filename
.length() > 0) ? CalabConstants.ACTIVE_STATUS : fileMaskStatus;
this.inoutType = inoutType;
}
public FileBean(String id, String path) {
super();
// TODO Auto-generated constructor stub
this.id = id;
this.path = path;
this.filename = getFileName(path);
}
public FileBean(InputFile infile) {
this.id = StringUtils.convertToString(infile.getId());
this.path = infile.getPath();
this.fileSubmitter = infile.getCreatedBy();
this.filename = getFileName(path);
this.shortFilename=infile.getFilename();
this.fileMaskStatus = (fileMaskStatus.length() == 0 && filename
.length() > 0) ? CalabConstants.ACTIVE_STATUS : fileMaskStatus;
this.inoutType = CalabConstants.INPUT;
}
public FileBean(OutputFile outfile) {
this.id = StringUtils.convertToString(outfile.getId());
this.path = outfile.getPath();
this.fileSubmitter = outfile.getCreatedBy();
this.fileMaskStatus = (fileMaskStatus.length() == 0 && filename
.length() > 0) ? CalabConstants.ACTIVE_STATUS : fileMaskStatus;
this.filename = getFileName(path);
this.shortFilename=outfile.getFilename();
this.inoutType = CalabConstants.OUTPUT;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
this.filename = getFileName(path);
}
public String getFilename() {
return filename;
}
// public void setFilename(String filename) {
// this.filename = filename;
private String getFileName(String path) {
String[] tokens = path.split("/");
return tokens[tokens.length - 1];
}
public String getFileMaskStatus() {
return fileMaskStatus;
}
public void setFileMaskStatus(String fileMaskStatus) {
this.fileMaskStatus = (fileMaskStatus.length() == 0 && getFilename()
.length() > 0) ? CalabConstants.ACTIVE_STATUS : fileMaskStatus;
}
public String getCreateDateStr() {
return createDateStr;
}
public void setCreateDateStr(String fileSubmissionDate) {
this.createDateStr = fileSubmissionDate;
}
public String getFileSubmitter() {
return fileSubmitter;
}
public void setFileSubmitter(String fileSubmitter) {
this.fileSubmitter = fileSubmitter;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getShortFilename() {
return shortFilename;
}
public void setShortFilename(String shortFileName) {
this.shortFilename = shortFileName;
}
public String getInoutType() {
return inoutType;
}
public void setInoutType(String inoutType) {
this.inoutType = inoutType;
}
}
|
package org.yuanheng.cookcc.ant;
import java.io.File;
import java.util.ArrayList;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.util.JavaEnvUtils;
/**
* @author Heng Yuan
* @version $Id$
*/
public class Task extends org.apache.tools.ant.Task
{
public static class Option
{
private String m_name;
private String m_value;
public void setName (String name)
{
m_name = name;
}
public void setValue (String value)
{
m_value = value;
}
}
private String m_lexerTable;
private String m_parserTable;
private boolean m_debug;
private boolean m_analysis;
private boolean m_defaultReduce;
private String m_lang;
private File m_destDir = null;
private File m_srcDir = null;
private ArrayList<Option> m_options = new ArrayList<Option> ();
private ArrayList<String> m_aptFiles = new ArrayList<String> ();
private ArrayList<String> m_xccFiles = new ArrayList<String> ();
public void setSrcDir (File srcDir)
{
if (!srcDir.exists () || !srcDir.isDirectory ())
throw new IllegalArgumentException ("Invalid destination directory.");
m_srcDir = srcDir;
}
public void setDestDir (File destDir)
{
if (!destDir.exists () || !destDir.isDirectory ())
throw new IllegalArgumentException ("Invalid destination directory.");
m_destDir = destDir;
}
public void setLexerTable (String table)
{
if (!"ecs".equals (table) &&
!"full".equals (table) &&
!"compressed".equals (table))
throw new IllegalArgumentException ("Unknown lexer table: " + table);
m_lexerTable = table;
}
public void setParserTable (String table)
{
if (!"ecs".equals (table) &&
!"compressed".equals (table))
throw new IllegalArgumentException ("Unknown parser table: " + table);
m_parserTable = table;
}
public void setLang (String lang)
{
m_lang = lang;
}
public void setDebug (boolean debug)
{
m_debug = debug;
}
public void setAnalysis (boolean analysis)
{
m_analysis = analysis;
}
public void setDefaultReduce (boolean defaultReduce)
{
m_defaultReduce = defaultReduce;
}
public void setSrc (String files)
{
String[] fileNames = files.split (" ");
for (String fileName : fileNames)
{
if (fileName == null || fileName.length () == 0)
continue;
if (fileName.endsWith (".java"))
m_aptFiles.add (fileName);
else
m_xccFiles.add (fileName);
}
}
public void addConfiguredOption (Option option)
{
m_options.add (option);
}
public void execute ()
{
if (m_xccFiles.size () > 0)
executeCookCC (m_xccFiles.toArray (new String[m_xccFiles.size ()]));
if (m_aptFiles.size () > 0)
executeApt (m_aptFiles.toArray (new String[m_aptFiles.size ()]));
}
protected void executeCookCC (String[] files)
{
Commandline cmd = new Commandline ();
cmd.setExecutable (JavaEnvUtils.getJdkExecutable ("java"));
cmd.createArgument ().setValue ("-cp");
cmd.createArgument ().setValue (getCookCCPath ());
cmd.createArgument ().setValue ("org.yuanheng.cookcc.Main");
if (m_analysis)
cmd.createArgument ().setValue ("-analysis");
if (m_debug)
cmd.createArgument ().setValue ("-debug");
if (m_defaultReduce)
cmd.createArgument ().setValue ("-defaultreduce");
if (m_lexerTable != null)
{
cmd.createArgument ().setValue ("-lexertable");
cmd.createArgument ().setValue (m_lexerTable);
}
if (m_parserTable != null)
{
cmd.createArgument ().setValue ("-parsertable");
cmd.createArgument ().setValue (m_parserTable);
}
if (m_lang != null)
{
cmd.createArgument ().setValue ("-lang");
cmd.createArgument ().setValue (m_lang);
}
for (Option option : m_options)
{
if (option.m_name == null || option.m_name.length () == 0)
continue;
cmd.createArgument ().setValue (option.m_name);
if (option.m_value == null)
continue;
cmd.createArgument ().setValue (option.m_value);
}
for (String file : files)
{
Commandline newCmd = (Commandline)cmd.clone ();
newCmd.createArgument ().setValue (file);
if (executeCmd (newCmd))
throw new RuntimeException ("Error executing CookCC");
}
}
protected String getCookCCPath ()
{
ClassLoader cl = Task.class.getClassLoader ();
if (cl instanceof AntClassLoader)
{
return ((AntClassLoader)cl).getClasspath ();
}
throw new RuntimeException ("Unable to determine the runtime path of CookCC.");
}
protected void executeApt (String[] classes)
{
Commandline cmd = new Commandline ();
cmd.setExecutable (JavaEnvUtils.getJdkExecutable ("apt"));
if (m_srcDir == null)
throw new IllegalArgumentException ("Source directory is not specified.");
cmd.createArgument ().setValue ("-cp");
cmd.createArgument ().setValue (getCookCCPath () + File.pathSeparatorChar + m_srcDir.getPath ());
cmd.createArgument ().setValue ("-s");
cmd.createArgument ().setValue (m_srcDir.getPath ());
if (m_analysis)
cmd.createArgument ().setValue ("-Aanalysis");
if (m_debug)
cmd.createArgument ().setValue ("-Adebug");
if (m_defaultReduce)
cmd.createArgument ().setValue ("-Adefaultreduce");
if (m_lexerTable != null)
cmd.createArgument ().setValue ("-Alexertable=" + m_lexerTable);
if (m_parserTable != null)
cmd.createArgument ().setValue ("-Aparsertable=" + m_parserTable);
if (m_lang != null)
cmd.createArgument ().setValue ("-Alang=" + m_lang);
if (m_lang == null || "java".equals (m_lang))
{
if (m_destDir == null)
m_destDir = m_srcDir;
cmd.createArgument ().setValue ("-Ad=" + m_destDir.getPath ());
}
for (Option option : m_options)
{
if (option.m_name == null || option.m_name.length () == 0)
continue;
String arg = option.m_name;
if (arg.startsWith ("-"))
arg = arg.substring (1);
arg = "-A" + arg;
if (option.m_value != null)
arg = arg + '=' + option.m_value;
cmd.createArgument ().setValue (arg);
}
for (String className : classes)
{
File file = new File (m_srcDir, className);
cmd.createArgument ().setValue (file.getPath ());
}
if (executeCmd (cmd))
throw new RuntimeException ("Error executing CookCC using APT");
}
protected boolean executeCmd (Commandline cmd)
{
try
{
System.out.println (cmd.toString ());
Execute exe = new Execute ();
exe.setCommandline (cmd.getCommandline ());
exe.execute ();
if (exe.getExitValue () == 0)
return false;
}
catch (Exception ex)
{
}
return true;
}
}
|
package de.pifpafpuf.kavi;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Comparator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import de.pifpafpuf.kavi.offmeta.GroupMetaKey;
import de.pifpafpuf.kavi.offmeta.GroupMsgValue;
import de.pifpafpuf.kavi.offmeta.MsgValue;
import de.pifpafpuf.kavi.offmeta.OffsetMetaKey;
import de.pifpafpuf.kavi.offmeta.OffsetMsgValue;
import de.pifpafpuf.web.html.EmptyElem;
import de.pifpafpuf.web.html.Html;
import de.pifpafpuf.web.html.HtmlPage;
import de.pifpafpuf.web.urlparam.IntegerCodec;
import de.pifpafpuf.web.urlparam.StringCodec;
import de.pifpafpuf.web.urlparam.UrlParamCodec;
public class ShowTopicContent extends AllServletsParent {
public static final String URL = "/topic";
public static final UrlParamCodec<String> pTopic =
new UrlParamCodec<>("topic", StringCodec.INSTANCE);
public static final UrlParamCodec<Integer> pOffset =
new UrlParamCodec<>("offset", IntegerCodec.INSTANCE);
public static final UrlParamCodec<Integer> pRefreshSecs =
new UrlParamCodec<>("refreshsecs",
new IntegerCodec(3, Integer.MAX_VALUE));
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
HtmlPage page = initPage("show topic content");
int refreshSecs = pRefreshSecs.fromFirst(req, -1);
if (refreshSecs>0) {
EmptyElem meta = new EmptyElem("meta");
meta.setAttr("http-equiv", "refresh");
meta.setAttr("content", Integer.toString(refreshSecs));
page.addHeadElem(meta);
}
String topicName = pTopic.fromFirst(req, "");
int offset = pOffset.fromFirst(req, -5);
QueueWatcher qw = KafkaViewerServer.getQueueWatcher();
List<ConsumerRecord<Object, byte[]>> recs =
qw.readRecords(topicName, offset);
page.addContent(renderRefreshButton(refreshSecs, topicName, offset));
page.addContent(renderHeader(topicName));
page.addContent(renderTable(recs));
sendPage(resp, page);
}
private Html renderHeader(String topic) {
return new Html("h1")
.addText("Latest keys from topic:")
.addText(topic);
}
private Html renderRefreshButton(int refreshSecs, String topic, int offset) {
final int newRefresh = 10;
StringBuilder sb = new StringBuilder(200);
sb.append(ShowTopicContent.URL).append('?');
pTopic.appendToUrl(sb, topic);
pOffset.appendToUrl(sb, offset);
Html a = new Html("a");
if (refreshSecs<0) {
pRefreshSecs.appendToUrl(sb, newRefresh);
a.setAttr("href", sb.toString());
a.addText("start refresh every "+newRefresh+" seconds");
} else {
a.setAttr("href", sb.toString());
a.addText("stop auto-refresh");
}
return a;
}
private Html renderTable(List<ConsumerRecord<Object, byte[]>> recs) {
Html table = new Html("table").setAttr("class", "records withdata");
Html thead = table.add("thead");
recs.sort(RecSorter.INSTANCE);
Html tr = new Html("tr").setAttr("class", "recordrow recordrowhead");
tr.add("th").addText("created (UTC)");
tr.add("th").addText("parti\u00adtion");
tr.add("th").addText("offset");
tr.add("th").addText("key");
tr.add("th").addText("value");
thead.add(tr);
Html tbody = table.add("tbody");
for (ConsumerRecord<Object, byte[]> rec : recs) {
String created = "unknown"; //dateFormat(rec.timestamp());
tr = new Html("tr").setAttr("class", "recordrow");
tr.add("td").addText(created);
tr.add("td").addText(Long.toString(rec.partition()));
tr.add("td").addText(Long.toString(rec.offset()));
tr.add("td").addText(rec.key().toString());
tr.add("td").addText(convert(rec));
tbody.add(tr);
}
return table;
}
private String convert(ConsumerRecord<Object, byte[]> rec) {
Object key = rec.key();
if (key instanceof GroupMetaKey) {
MsgValue mv =GroupMsgValue.decode(rec.value());
return mv==null ? "(null)" : mv.toString();
}
if (key instanceof OffsetMetaKey) {
MsgValue mv = OffsetMsgValue.decode(rec.value());
return mv==null ? "(null)" : mv.toString();
}
if (rec.value()==null) {
return "(null message)";
}
try(ByteArrayInputStream bin = new ByteArrayInputStream(rec.value());
ObjectInputStream oin = new ObjectInputStream(bin);
) {
return oin.readObject().toString();
} catch (IOException | ClassNotFoundException e) {
return e.getClass().getName()+": "+e.getMessage();
}
}
private enum RecSorter implements Comparator<ConsumerRecord<?, ?>> {
INSTANCE;
@Override
public int compare(ConsumerRecord<?,?> o1, ConsumerRecord<?,?> o2) {
//TODO: with 0.10 we will be able to sort by timestamp
// if (o1.timestamp() < o2.timestamp()) {
// return -1;
// if (o1.timestamp() > o2.timestamp()) {
// return 1;
if (o1.partition() < o2.partition()) {
return -1;
}
if (o1.partition() > o2.partition()) {
return 1;
}
if (o1.offset() < o2.offset()) {
return -1;
}
if (o1.offset() > o2.offset()) {
return 1;
}
return 0;
}
}
}
|
package net.sf.picard.sam;
import net.sf.picard.PicardException;
import net.sf.picard.metrics.MetricBase;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.reference.ReferenceSequence;
import net.sf.picard.reference.ReferenceSequenceFile;
import net.sf.picard.reference.ReferenceSequenceFileWalker;
import net.sf.picard.util.*;
import net.sf.samtools.*;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import net.sf.samtools.SAMValidationError.Type;
import net.sf.samtools.util.*;
import java.io.*;
import java.util.*;
/**
* Validates SAM files as follows:
* <ul>
* <li>checks sam file header for sequence dictionary</li>
* <li>checks sam file header for read groups</li>
* <li>for each sam record
* <ul>
* <li>reports error detected by SAMRecord.isValid()</li>
* <li>validates NM (nucleotide differences) exists and matches reality</li>
* <li>validates mate fields agree with data in the mate record</li>
* </ul>
* </li>
* </ul>
*
* @author Doug Voet
* @see SAMRecord#isValid()
*/
public class SamFileValidator {
private Histogram<Type> errorsByType = new Histogram<Type>();
private final PrintWriter out;
private PairEndInfoMap pairEndInfoByName;
private ReferenceSequenceFileWalker refFileWalker = null;
private boolean verbose = false;
private int maxVerboseOutput = 100;
private SAMSortOrderChecker orderChecker;
private Set<Type> errorsToIgnore = EnumSet.noneOf(Type.class);
private boolean ignoreWarnings = false;
private boolean bisulfiteSequenced = false;
private boolean validateIndex = false;
private boolean sequenceDictionaryEmptyAndNoWarningEmitted = false;
private final int maxTempFiles;
private final static Log log = Log.getInstance(SamFileValidator.class);
public SamFileValidator(final PrintWriter out, final int maxTempFiles) {
this.out = out;
this.maxTempFiles = maxTempFiles;
}
/**
* Sets one or more error types that should not be reported on.
*/
public void setErrorsToIgnore(final Collection<Type> types) {
if (!types.isEmpty()) {
this.errorsToIgnore = EnumSet.copyOf(types);
}
}
public void setIgnoreWarnings(final boolean ignoreWarnings) {
this.ignoreWarnings = ignoreWarnings;
}
/**
* Outputs validation summary report to out.
*
* @param samReader records to validate
* @param reference if null, NM tag validation is skipped
* @return boolean true if there are no validation errors, otherwise false
*/
public boolean validateSamFileSummary(final SAMFileReader samReader, final ReferenceSequenceFile reference) {
init(reference, samReader.getFileHeader());
validateSamFile(samReader, out);
boolean result = errorsByType.isEmpty();
if (errorsByType.getCount() > 0) {
// Convert to a histogram with String IDs so that WARNING: or ERROR: can be prepended to the error type.
final Histogram<String> errorsAndWarningsByType = new Histogram<String>("Error Type", "Count");
for (final Histogram<SAMValidationError.Type>.Bin bin : errorsByType.values()) {
errorsAndWarningsByType.increment(bin.getId().getHistogramString(), bin.getValue());
}
final MetricsFile<ValidationMetrics, String> metricsFile = new MetricsFile<ValidationMetrics, String>();
errorsByType.setBinLabel("Error Type");
errorsByType.setValueLabel("Count");
metricsFile.setHistogram(errorsAndWarningsByType);
metricsFile.write(out);
}
cleanup();
return result;
}
/**
* Outputs validation error details to out.
*
* @param samReader records to validate
* @param reference if null, NM tag validation is skipped
* processing will stop after this threshold has been reached
* @return boolean true if there are no validation errors, otherwise false
*/
public boolean validateSamFileVerbose(final SAMFileReader samReader, final ReferenceSequenceFile reference) {
init(reference, samReader.getFileHeader());
try {
validateSamFile(samReader, out);
} catch (MaxOutputExceededException e) {
out.println("Maximum output of [" + maxVerboseOutput + "] errors reached.");
}
boolean result = errorsByType.isEmpty();
cleanup();
return result;
}
public void validateBamFileTermination(final File inputFile) {
BufferedInputStream inputStream = null;
try {
inputStream = IOUtil.toBufferedStream(new FileInputStream(inputFile));
if (!BlockCompressedInputStream.isValidFile(inputStream)) {
return;
}
final BlockCompressedInputStream.FileTermination terminationState =
BlockCompressedInputStream.checkTermination(inputFile);
if (terminationState.equals(BlockCompressedInputStream.FileTermination.DEFECTIVE)) {
addError(new SAMValidationError(Type.TRUNCATED_FILE, "BAM file has defective last gzip block",
inputFile.getPath()));
} else if (terminationState.equals(BlockCompressedInputStream.FileTermination.HAS_HEALTHY_LAST_BLOCK)) {
addError(new SAMValidationError(Type.BAM_FILE_MISSING_TERMINATOR_BLOCK,
"Older BAM file -- does not have terminator block",
inputFile.getPath()));
}
} catch (IOException e) {
throw new PicardException("IOException", e);
} finally {
if (inputStream != null) {
CloserUtil.close(inputStream);
}
}
}
private void validateSamFile(final SAMFileReader samReader, final PrintWriter out) {
try {
samReader.setValidationStringency(ValidationStringency.SILENT);
validateHeader(samReader.getFileHeader());
orderChecker = new SAMSortOrderChecker(samReader.getFileHeader().getSortOrder());
validateSamRecordsAndQualityFormat(samReader, samReader.getFileHeader());
validateUnmatchedPairs();
if (validateIndex) {
try {
BamIndexValidator.exhaustivelyTestIndex(samReader);
} catch (Exception e) {
addError(new SAMValidationError(Type.INVALID_INDEX_FILE_POINTER, e.getMessage(), null));
}
}
if (errorsByType.isEmpty()) {
out.println("No errors found");
}
} finally {
out.flush();
}
}
/**
* Report on reads marked as paired, for which the mate was not found.
*/
private void validateUnmatchedPairs() {
final InMemoryPairEndInfoMap inMemoryPairMap;
if (pairEndInfoByName instanceof CoordinateSortedPairEndInfoMap) {
// For the coordinate-sorted map, need to detect mate pairs in which the mateReferenceIndex on one end
// does not match the readReference index on the other end, so the pairs weren't united and validated.
inMemoryPairMap = new InMemoryPairEndInfoMap();
CloseableIterator<Map.Entry<String, PairEndInfo>> it = ((CoordinateSortedPairEndInfoMap) pairEndInfoByName).iterator();
while (it.hasNext()) {
Map.Entry<String, PairEndInfo> entry = it.next();
PairEndInfo pei = inMemoryPairMap.remove(entry.getValue().readReferenceIndex, entry.getKey());
if (pei != null) {
// Found a mismatch btw read.mateReferenceIndex and mate.readReferenceIndex
List<SAMValidationError> errors = pei.validateMates(entry.getValue(), entry.getKey());
for (final SAMValidationError error : errors) {
addError(error);
}
} else {
// Mate not found.
inMemoryPairMap.put(entry.getValue().mateReferenceIndex, entry.getKey(), entry.getValue());
}
}
it.close();
} else {
inMemoryPairMap = (InMemoryPairEndInfoMap) pairEndInfoByName;
}
// At this point, everything in InMemoryMap is a read marked as a pair, for which a mate was not found.
for (final Map.Entry<String, PairEndInfo> entry : inMemoryPairMap) {
addError(new SAMValidationError(Type.MATE_NOT_FOUND, "Mate not found for paired read", entry.getKey()));
}
}
/**
* SAM record and quality format validations are combined into a single method because validation must be completed
* in only a single pass of the SamRecords (because a SamReader's iterator() method may not return the same
* records on a subsequent call).
*/
private void validateSamRecordsAndQualityFormat(final Iterable<SAMRecord> samRecords, final SAMFileHeader header) {
SAMRecordIterator iter = (SAMRecordIterator) samRecords.iterator();
final ProgressLogger progress = new ProgressLogger(log, 10000000, "Validated Read");
final QualityEncodingDetector qualityDetector = new QualityEncodingDetector();
try {
while (iter.hasNext()) {
final SAMRecord record = iter.next();
qualityDetector.add(record);
final long recordNumber = progress.getCount() + 1;
final Collection<SAMValidationError> errors = record.isValid();
if (errors != null) {
for (final SAMValidationError error : errors) {
error.setRecordNumber(recordNumber);
addError(error);
}
}
validateMateFields(record, recordNumber);
validateSortOrder(record, recordNumber);
validateReadGroup(record, header);
final boolean cigarIsValid = validateCigar(record, recordNumber);
if (cigarIsValid) {
validateNmTag(record, recordNumber);
}
validateSecondaryBaseCalls(record, recordNumber);
validateTags(record, recordNumber);
if (sequenceDictionaryEmptyAndNoWarningEmitted && !record.getReadUnmappedFlag()) {
addError(new SAMValidationError(Type.MISSING_SEQUENCE_DICTIONARY, "Sequence dictionary is empty", null));
sequenceDictionaryEmptyAndNoWarningEmitted = false;
}
progress.record(record);
}
try {
if (progress.getCount() > 0) { // Avoid exception being thrown as a result of no qualities being read
final FastqQualityFormat format = qualityDetector.generateBestGuess(QualityEncodingDetector.FileContext.SAM);
if (format != FastqQualityFormat.Standard) {
addError(new SAMValidationError(Type.INVALID_QUALITY_FORMAT, String.format("Detected %s quality score encoding, but expected %s.", format, FastqQualityFormat.Standard), null));
}
}
} catch (PicardException e) {
addError(new SAMValidationError(Type.INVALID_QUALITY_FORMAT, e.getMessage(), null));
}
} catch (SAMFormatException e) {
// increment record number because the iterator behind the SAMFileReader
// reads one record ahead so we will get this failure one record ahead
final String msg = "SAMFormatException on record " + progress.getCount() + 1;
out.println(msg);
throw new PicardException(msg, e);
} catch (FileTruncatedException e) {
addError(new SAMValidationError(Type.TRUNCATED_FILE, "File is truncated", null));
} finally {
iter.close();
}
}
private void validateReadGroup(final SAMRecord record, final SAMFileHeader header) {
SAMReadGroupRecord rg = record.getReadGroup();
if (rg == null) {
addError(new SAMValidationError(Type.RECORD_MISSING_READ_GROUP,
"A record is missing a read group", record.getReadName()));
} else if (!header.getReadGroups().contains(rg)) {
addError(new SAMValidationError(Type.READ_GROUP_NOT_FOUND,
"A record has a read group not found in the header: ",
record.getReadName() + ", " + rg.getReadGroupId()));
}
}
/**
* Report error if a tag value is a Long.
*/
private void validateTags(final SAMRecord record, final long recordNumber) {
for (final SAMRecord.SAMTagAndValue tagAndValue : record.getAttributes()) {
if (tagAndValue.value instanceof Long) {
addError(new SAMValidationError(Type.TAG_VALUE_TOO_LARGE,
"Numeric value too large for tag " + tagAndValue.tag,
record.getReadName(), recordNumber));
}
}
}
private void validateSecondaryBaseCalls(final SAMRecord record, final long recordNumber) {
final String e2 = (String) record.getAttribute(SAMTag.E2.name());
if (e2 != null) {
if (e2.length() != record.getReadLength()) {
addError(new SAMValidationError(Type.MISMATCH_READ_LENGTH_AND_E2_LENGTH,
String.format("E2 tag length (%d) != read length (%d)", e2.length(), record.getReadLength()),
record.getReadName(), recordNumber));
}
final byte[] bases = record.getReadBases();
final byte[] secondaryBases = StringUtil.stringToBytes(e2);
for (int i = 0; i < Math.min(bases.length, secondaryBases.length); ++i) {
if (SequenceUtil.isNoCall(bases[i]) || SequenceUtil.isNoCall(secondaryBases[i])) {
continue;
}
if (SequenceUtil.basesEqual(bases[i], secondaryBases[i])) {
addError(new SAMValidationError(Type.E2_BASE_EQUALS_PRIMARY_BASE,
String.format("Secondary base call (%c) == primary base call (%c)",
(char) secondaryBases[i], (char) bases[i]),
record.getReadName(), recordNumber));
break;
}
}
}
final String u2 = (String) record.getAttribute(SAMTag.U2.name());
if (u2 != null && u2.length() != record.getReadLength()) {
addError(new SAMValidationError(Type.MISMATCH_READ_LENGTH_AND_U2_LENGTH,
String.format("U2 tag length (%d) != read length (%d)", u2.length(), record.getReadLength()),
record.getReadName(), recordNumber));
}
}
private boolean validateCigar(final SAMRecord record, final long recordNumber) {
if (record.getReadUnmappedFlag()) {
return true;
}
final ValidationStringency savedStringency = record.getValidationStringency();
record.setValidationStringency(ValidationStringency.LENIENT);
final List<SAMValidationError> errors = record.validateCigar(recordNumber);
record.setValidationStringency(savedStringency);
if (errors == null) {
return true;
}
boolean valid = true;
for (final SAMValidationError error : errors) {
addError(error);
valid = false;
}
return valid;
}
private void validateSortOrder(final SAMRecord record, final long recordNumber) {
final SAMRecord prev = orderChecker.getPreviousRecord();
if (!orderChecker.isSorted(record)) {
addError(new SAMValidationError(
Type.RECORD_OUT_OF_ORDER,
String.format(
"The record is out of [%s] order, prior read name [%s], prior coodinates [%d:%d]",
record.getHeader().getSortOrder().name(),
prev.getReadName(),
prev.getReferenceIndex(),
prev.getAlignmentStart()),
record.getReadName(),
recordNumber));
}
}
private void init(final ReferenceSequenceFile reference, final SAMFileHeader header) {
if (header.getSortOrder() == SAMFileHeader.SortOrder.coordinate) {
this.pairEndInfoByName = new CoordinateSortedPairEndInfoMap();
} else {
this.pairEndInfoByName = new InMemoryPairEndInfoMap();
}
if (reference != null) {
this.refFileWalker = new ReferenceSequenceFileWalker(reference);
}
}
private void cleanup() {
this.errorsByType = null;
this.pairEndInfoByName = null;
this.refFileWalker = null;
}
private void validateNmTag(final SAMRecord record, final long recordNumber) {
if (!record.getReadUnmappedFlag()) {
final Integer tagNucleotideDiffs = record.getIntegerAttribute(ReservedTagConstants.NM);
if (tagNucleotideDiffs == null) {
addError(new SAMValidationError(
Type.MISSING_TAG_NM,
"NM tag (nucleotide differences) is missing",
record.getReadName(),
recordNumber));
} else if (refFileWalker != null) {
final ReferenceSequence refSequence = refFileWalker.get(record.getReferenceIndex());
final int actualNucleotideDiffs = SequenceUtil.calculateSamNmTag(record, refSequence.getBases(),
0, isBisulfiteSequenced());
if (!tagNucleotideDiffs.equals(actualNucleotideDiffs)) {
addError(new SAMValidationError(
Type.INVALID_TAG_NM,
"NM tag (nucleotide differences) in file [" + tagNucleotideDiffs +
"] does not match reality [" + actualNucleotideDiffs + "]",
record.getReadName(),
recordNumber));
}
}
}
}
private void validateMateFields(final SAMRecord record, final long recordNumber) {
if (!record.getReadPairedFlag() || record.getNotPrimaryAlignmentFlag()) {
return;
}
final PairEndInfo pairEndInfo = pairEndInfoByName.remove(record.getReferenceIndex(), record.getReadName());
if (pairEndInfo == null) {
pairEndInfoByName.put(record.getMateReferenceIndex(), record.getReadName(), new PairEndInfo(record, recordNumber));
} else {
final List<SAMValidationError> errors =
pairEndInfo.validateMates(new PairEndInfo(record, recordNumber), record.getReadName());
for (final SAMValidationError error : errors) {
addError(error);
}
}
}
private void validateHeader(final SAMFileHeader fileHeader) {
for (final SAMValidationError error : fileHeader.getValidationErrors()) {
addError(error);
}
if (fileHeader.getVersion() == null) {
addError(new SAMValidationError(Type.MISSING_VERSION_NUMBER, "Header has no version number", null));
} else if (!SAMFileHeader.ACCEPTABLE_VERSIONS.contains(fileHeader.getVersion())) {
addError(new SAMValidationError(Type.INVALID_VERSION_NUMBER, "Header version: " +
fileHeader.getVersion() + " does not match any of the acceptable versions: " +
StringUtil.join(", ", SAMFileHeader.ACCEPTABLE_VERSIONS.toArray(new String[0])),
null));
}
if (fileHeader.getSequenceDictionary().isEmpty()) {
sequenceDictionaryEmptyAndNoWarningEmitted = true;
}
if (fileHeader.getReadGroups().isEmpty()) {
addError(new SAMValidationError(Type.MISSING_READ_GROUP, "Read groups is empty", null));
}
List<SAMProgramRecord> pgs = fileHeader.getProgramRecords();
for (int i = 0; i < pgs.size() - 1; i++) {
for (int j = i + 1; j < pgs.size(); j++) {
if (pgs.get(i).getProgramGroupId().equals(pgs.get(j).getProgramGroupId())) {
addError(new SAMValidationError(Type.DUPLICATE_PROGRAM_GROUP_ID, "Duplicate " +
"program group id: " + pgs.get(i).getProgramGroupId(), null));
}
}
}
List<SAMReadGroupRecord> rgs = fileHeader.getReadGroups();
for (int i = 0; i < rgs.size() - 1; i++) {
for (int j = i + 1; j < rgs.size(); j++) {
if (rgs.get(i).getReadGroupId().equals(rgs.get(j).getReadGroupId())) {
addError(new SAMValidationError(Type.DUPLICATE_READ_GROUP_ID, "Duplicate " +
"read group id: " + rgs.get(i).getReadGroupId(), null));
}
}
}
}
private void addError(final SAMValidationError error) {
// Just ignore an error if it's of a type we're not interested in
if (this.errorsToIgnore.contains(error.getType())) return;
if (this.ignoreWarnings && error.getType().severity == SAMValidationError.Severity.WARNING) return;
this.errorsByType.increment(error.getType());
if (verbose) {
out.println(error);
out.flush();
if (this.errorsByType.getCount() >= maxVerboseOutput) {
throw new MaxOutputExceededException();
}
}
}
/**
* Control verbosity
*
* @param verbose True in order to emit a message per error or warning.
* @param maxVerboseOutput If verbose, emit no more than this many messages. Ignored if !verbose.
*/
public void setVerbose(final boolean verbose, final int maxVerboseOutput) {
this.verbose = verbose;
this.maxVerboseOutput = maxVerboseOutput;
}
public boolean isBisulfiteSequenced() {
return bisulfiteSequenced;
}
public void setBisulfiteSequenced(boolean bisulfiteSequenced) {
this.bisulfiteSequenced = bisulfiteSequenced;
}
public SamFileValidator setValidateIndex(boolean validateIndex) {
// The SAMFileReader must also have IndexCaching enabled to have the index validated,
// samReader.enableIndexCaching(true);
this.validateIndex = validateIndex;
return this;
}
public static class ValidationMetrics extends MetricBase {
}
/**
* This class is used so we don't have to store the entire SAMRecord in memory while we wait
* to find a record's mate and also to store the record number.
*/
private static class PairEndInfo {
private final int readAlignmentStart;
private final int readReferenceIndex;
private final boolean readNegStrandFlag;
private final boolean readUnmappedFlag;
private final int mateAlignmentStart;
private final int mateReferenceIndex;
private final boolean mateNegStrandFlag;
private final boolean mateUnmappedFlag;
private final boolean firstOfPairFlag;
private final long recordNumber;
public PairEndInfo(final SAMRecord record, final long recordNumber) {
this.recordNumber = recordNumber;
this.readAlignmentStart = record.getAlignmentStart();
this.readNegStrandFlag = record.getReadNegativeStrandFlag();
this.readReferenceIndex = record.getReferenceIndex();
this.readUnmappedFlag = record.getReadUnmappedFlag();
this.mateAlignmentStart = record.getMateAlignmentStart();
this.mateNegStrandFlag = record.getMateNegativeStrandFlag();
this.mateReferenceIndex = record.getMateReferenceIndex();
this.mateUnmappedFlag = record.getMateUnmappedFlag();
this.firstOfPairFlag = record.getFirstOfPairFlag();
}
private PairEndInfo(int readAlignmentStart, int readReferenceIndex, boolean readNegStrandFlag, boolean readUnmappedFlag,
int mateAlignmentStart, int mateReferenceIndex, boolean mateNegStrandFlag, boolean mateUnmappedFlag,
boolean firstOfPairFlag, long recordNumber) {
this.readAlignmentStart = readAlignmentStart;
this.readReferenceIndex = readReferenceIndex;
this.readNegStrandFlag = readNegStrandFlag;
this.readUnmappedFlag = readUnmappedFlag;
this.mateAlignmentStart = mateAlignmentStart;
this.mateReferenceIndex = mateReferenceIndex;
this.mateNegStrandFlag = mateNegStrandFlag;
this.mateUnmappedFlag = mateUnmappedFlag;
this.firstOfPairFlag = firstOfPairFlag;
this.recordNumber = recordNumber;
}
public List<SAMValidationError> validateMates(final PairEndInfo mate, final String readName) {
final List<SAMValidationError> errors = new ArrayList<SAMValidationError>();
validateMateFields(this, mate, readName, errors);
validateMateFields(mate, this, readName, errors);
// Validations that should not be repeated on both ends
if (this.firstOfPairFlag == mate.firstOfPairFlag) {
final String whichEnd = this.firstOfPairFlag ? "first" : "second";
errors.add(new SAMValidationError(
Type.MATES_ARE_SAME_END,
"Both mates are marked as " + whichEnd + " of pair",
readName,
this.recordNumber
));
}
return errors;
}
private void validateMateFields(final PairEndInfo end1, final PairEndInfo end2, final String readName, final List<SAMValidationError> errors) {
if (end1.mateAlignmentStart != end2.readAlignmentStart) {
errors.add(new SAMValidationError(
Type.MISMATCH_MATE_ALIGNMENT_START,
"Mate alignment does not match alignment start of mate",
readName,
end1.recordNumber));
}
if (end1.mateNegStrandFlag != end2.readNegStrandFlag) {
errors.add(new SAMValidationError(
Type.MISMATCH_FLAG_MATE_NEG_STRAND,
"Mate negative strand flag does not match read negative strand flag of mate",
readName,
end1.recordNumber));
}
if (end1.mateReferenceIndex != end2.readReferenceIndex) {
errors.add(new SAMValidationError(
Type.MISMATCH_MATE_REF_INDEX,
"Mate reference index (MRNM) does not match reference index of mate",
readName,
end1.recordNumber));
}
if (end1.mateUnmappedFlag != end2.readUnmappedFlag) {
errors.add(new SAMValidationError(
Type.MISMATCH_FLAG_MATE_UNMAPPED,
"Mate unmapped flag does not match read unmapped flag of mate",
readName,
end1.recordNumber));
}
}
}
/**
* Thrown in addError indicating that maxVerboseOutput has been exceeded and processing should stop
*/
private static class MaxOutputExceededException extends PicardException {
MaxOutputExceededException() {
super("maxVerboseOutput exceeded.");
}
}
interface PairEndInfoMap extends Iterable<Map.Entry<String, PairEndInfo>> {
void put(int mateReferenceIndex, String key, PairEndInfo value);
PairEndInfo remove(int mateReferenceIndex, String key);
CloseableIterator<Map.Entry<String, PairEndInfo>> iterator();
}
private class CoordinateSortedPairEndInfoMap implements PairEndInfoMap {
private final CoordinateSortedPairInfoMap<String, PairEndInfo> onDiskMap =
new CoordinateSortedPairInfoMap<String, PairEndInfo>(maxTempFiles, new Codec());
public void put(int mateReferenceIndex, String key, PairEndInfo value) {
onDiskMap.put(mateReferenceIndex, key, value);
}
public PairEndInfo remove(int mateReferenceIndex, String key) {
return onDiskMap.remove(mateReferenceIndex, key);
}
public CloseableIterator<Map.Entry<String, PairEndInfo>> iterator() {
return onDiskMap.iterator();
}
private class Codec implements CoordinateSortedPairInfoMap.Codec<String, PairEndInfo> {
private DataInputStream in;
private DataOutputStream out;
public void setOutputStream(final OutputStream os) {
this.out = new DataOutputStream(os);
}
public void setInputStream(final InputStream is) {
this.in = new DataInputStream(is);
}
public void encode(String key, PairEndInfo record) {
try {
out.writeUTF(key);
out.writeInt(record.readAlignmentStart);
out.writeInt(record.readReferenceIndex);
out.writeBoolean(record.readNegStrandFlag);
out.writeBoolean(record.readUnmappedFlag);
out.writeInt(record.mateAlignmentStart);
out.writeInt(record.mateReferenceIndex);
out.writeBoolean(record.mateNegStrandFlag);
out.writeBoolean(record.mateUnmappedFlag);
out.writeBoolean(record.firstOfPairFlag);
out.writeLong(record.recordNumber);
} catch (IOException e) {
throw new PicardException("Error spilling PairInfo to disk", e);
}
}
public Map.Entry<String, PairEndInfo> decode() {
try {
final String key = in.readUTF();
final int readAlignmentStart = in.readInt();
final int readReferenceIndex = in.readInt();
final boolean readNegStrandFlag = in.readBoolean();
final boolean readUnmappedFlag = in.readBoolean();
final int mateAlignmentStart = in.readInt();
final int mateReferenceIndex = in.readInt();
final boolean mateNegStrandFlag = in.readBoolean();
final boolean mateUnmappedFlag = in.readBoolean();
final boolean firstOfPairFlag = in.readBoolean();
final long recordNumber = in.readLong();
final PairEndInfo rec = new PairEndInfo(readAlignmentStart, readReferenceIndex, readNegStrandFlag,
readUnmappedFlag, mateAlignmentStart, mateReferenceIndex, mateNegStrandFlag, mateUnmappedFlag,
firstOfPairFlag, recordNumber);
return new AbstractMap.SimpleEntry(key, rec);
} catch (IOException e) {
throw new PicardException("Error reading PairInfo from disk", e);
}
}
}
}
private static class InMemoryPairEndInfoMap implements PairEndInfoMap {
private final Map<String, PairEndInfo> map = new HashMap<String, PairEndInfo>();
public void put(int mateReferenceIndex, String key, PairEndInfo value) {
if (mateReferenceIndex != value.mateReferenceIndex)
throw new IllegalArgumentException("mateReferenceIndex does not agree with PairEndInfo");
map.put(key, value);
}
public PairEndInfo remove(int mateReferenceIndex, String key) {
return map.remove(key);
}
public CloseableIterator<Map.Entry<String, PairEndInfo>> iterator() {
final Iterator<Map.Entry<String, PairEndInfo>> it = map.entrySet().iterator();
return new CloseableIterator<Map.Entry<String, PairEndInfo>>() {
public void close() {
// do nothing
}
public boolean hasNext() {
return it.hasNext();
}
public Map.Entry<String, PairEndInfo> next() {
return it.next();
}
public void remove() {
it.remove();
}
};
}
}
}
|
/*
* The main class which opens up several shells and gives the user the possibility
* to access all different forms of visualization.
*
* @author Mario Antn
*/
package org.deidentifier.arx.kap;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.DataType;
import org.deidentifier.arx.aggregates.StatisticsSummary;
import org.deidentifier.arx.aggregates.StatisticsSummary.ScaleOfMeasure;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.swtchart.Chart;
import org.swtchart.IAxis;
import org.swtchart.IBarSeries;
import org.swtchart.ISeries.SeriesType;
import org.swtchart.ISeriesLabel;
public class KAPDisplay {
private Button choice1;
private Button choice2;
private Button choice3;
private Button next;
private Label attLabel1;
private Label attLabel2;
private Label scaleLabel1;
private Label scaleLabel2;
private Label modeLabel1;
private Label modeLabel2;
private Label medianLabel1;
private Label medianLabel2;
private Label maxLabel1;
private Label maxLabel2;
private Label minLabel1;
private Label minLabel2;
private Label meanLabel1;
private Label meanLabel2;
private Label rangeLabel1;
private Label rangeLabel2;
private Label kurtosisLabel1;
private Label kurtosisLabel2;
private Label samVarLabel1;
private Label samVarLabel2;
private Label popVarLabel1;
private Label popVarLabel2;
private Label stdDevLabel1;
private Label stdDevLabel2;
private Label geoMeanLabel1;
private Label geoMeanLabel2;
private Chart chart;
private StatisticsSummary<?> statSum;
private String attribute;
private DataType<?> attType;
private boolean barSeriesClicked = false;
private boolean boxPlotClicked = false;
private boolean textClicked = false;
private boolean string = false;
private boolean orderedString = false;
private boolean integer = false;
private boolean decimal = false;
private boolean date = false;
private double[] barSeriesDouble;
/*
* The method opening the shells and providing buttons to access different
* visualization methods.
*
* @param dataHandle
*/
public void displayData(final DataHandle dataHandle) {
// Establishing "String" as the default starting attribute.
string = true;
attribute = "String";
statSum = dataHandle.getStatistics().getSummaryStatistics(true)
.get(attribute);
attType = dataHandle.getDefinition().getDataType(attribute);
final Display display = new Display();
final Shell mainShell = new Shell(display);
final Shell textShell = new Shell(display);
final Shell barSeriesShell = new Shell(display);
chart = new Chart(barSeriesShell, SWT.NONE);
chart.setLayout(new FillLayout());
mainShell.setSize(400, 200);
mainShell.setText("Displaying the data of attribute " + attribute);
textShell.setSize(550, 400);
textShell.setText("Text shell");
barSeriesShell.setSize(800, 600);
barSeriesShell.setText("Bar series shell");
barSeriesShell.setLayout(new FillLayout());
// creating all the needed text labels
attLabel1 = new Label(textShell, SWT.LEFT);
attLabel2 = new Label(textShell, SWT.LEFT);
scaleLabel1 = new Label(textShell, SWT.LEFT);
scaleLabel2 = new Label(textShell, SWT.LEFT);
modeLabel1 = new Label(textShell, SWT.LEFT);
modeLabel2 = new Label(textShell, SWT.LEFT);
medianLabel1 = new Label(textShell, SWT.LEFT);
medianLabel2 = new Label(textShell, SWT.LEFT);
maxLabel1 = new Label(textShell, SWT.LEFT);
maxLabel2 = new Label(textShell, SWT.LEFT);
minLabel1 = new Label(textShell, SWT.LEFT);
minLabel2 = new Label(textShell, SWT.LEFT);
meanLabel1 = new Label(textShell, SWT.LEFT);
meanLabel2 = new Label(textShell, SWT.LEFT);
rangeLabel1 = new Label(textShell, SWT.LEFT);
rangeLabel2 = new Label(textShell, SWT.LEFT);
kurtosisLabel1 = new Label(textShell, SWT.LEFT);
kurtosisLabel2 = new Label(textShell, SWT.LEFT);
samVarLabel1 = new Label(textShell, SWT.LEFT);
samVarLabel2 = new Label(textShell, SWT.LEFT);
popVarLabel1 = new Label(textShell, SWT.LEFT);
popVarLabel2 = new Label(textShell, SWT.LEFT);
stdDevLabel1 = new Label(textShell, SWT.LEFT);
stdDevLabel2 = new Label(textShell, SWT.LEFT);
geoMeanLabel1 = new Label(textShell, SWT.LEFT);
geoMeanLabel2 = new Label(textShell, SWT.LEFT);
choice2 = new Button(mainShell, SWT.PUSH);
choice2.setText("Display a Box-Plot");
choice2.setBounds(160, 10, 120, 30);
choice2.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
/*
* The booleans "boxPlotClicked", "barSeriesClicked" and
* "textClicked" exist to ensure that every visualization method
* can only be selected once per attribute. They are set to
* "false" by default, and switch to "true" once the button has
* been pushed.
*
* After changing attributes with the "next" button, the
* booleans are set to "false" again.
*/
if (!boxPlotClicked) {
final BoxPlotJFreeChart boxPlot = new BoxPlotJFreeChart();
boxPlot.displayBoxPlot(dataHandle, attribute, attType,
statSum);
boxPlotClicked = true;
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
choice2.setVisible(false);
choice3 = new Button(mainShell, SWT.PUSH);
choice3.setText("Display values as Bar Series");
choice3.setBounds(10, 40, 150, 30);
choice3.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!barSeriesClicked) {
chart.dispose();
chart = barSeries(chart, barSeriesShell, statSum,
attribute, attType);
barSeriesShell.setLayout(new FillLayout());
barSeriesClicked = true;
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
choice3.setVisible(false);
choice1 = new Button(mainShell, SWT.PUSH);
choice1.setText("Display values as text");
choice1.setBounds(10, 10, 150, 30);
choice1.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!textClicked) {
attributeText(textShell, statSum, attribute, attType);
textClicked = true;
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
next = new Button(mainShell, SWT.PUSH);
next.setText("Next Attribute");
next.setBounds(160, 40, 120, 30);
next.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
/*
* upon pushing the "next" Button, the shell is given the next
* attribute in the sample database, and the booleans are set
* accordingly.
*
* Moreover, the DataType of the attribute and the
* StatisticsSummary are updated.
*/
if (string) {
attribute = "OrderedString";
statSum = dataHandle.getStatistics()
.getSummaryStatistics(true).get(attribute);
attType = dataHandle.getDefinition().getDataType(attribute);
mainShell.setText("Displaying the data of attribute "
+ attribute);
string = false;
orderedString = true;
} else if (orderedString) {
attribute = "integer";
statSum = dataHandle.getStatistics()
.getSummaryStatistics(true).get(attribute);
attType = dataHandle.getDefinition().getDataType(attribute);
mainShell.setText("Displaying the data of attribute "
+ attribute);
orderedString = false;
integer = true;
choice2.setVisible(true);
choice3.setVisible(true);
} else if (integer) {
attribute = "decimal";
statSum = dataHandle.getStatistics()
.getSummaryStatistics(true).get(attribute);
attType = dataHandle.getDefinition().getDataType(attribute);
mainShell.setText("Displaying the data of attribute "
+ attribute);
integer = false;
decimal = true;
} else if (decimal) {
attribute = "date";
statSum = dataHandle.getStatistics()
.getSummaryStatistics(true).get(attribute);
attType = dataHandle.getDefinition().getDataType(attribute);
mainShell.setText("Displaying the data of attribute "
+ attribute);
decimal = false;
date = true;
} else if (date) {
attribute = "String";
statSum = dataHandle.getStatistics()
.getSummaryStatistics(true).get(attribute);
attType = dataHandle.getDefinition().getDataType(attribute);
mainShell.setText("Displaying the data of attribute "
+ attribute);
date = false;
string = true;
choice2.setVisible(false);
choice3.setVisible(false);
}
boxPlotClicked = false;
barSeriesClicked = false;
textClicked = false;
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
mainShell.open();
textShell.open();
barSeriesShell.open();
while (!mainShell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/*
* Method to display values as text.
*
* @param textShell
*
* @param statSum
*
* @param attribute
*
* @param attType
*/
public void attributeText(Shell textShell, StatisticsSummary<?> statSum,
String attribute, DataType<?> attType) {
// All labels are set to invisible at the start of the method, as not
// every attribute displays all labels.
attLabel1.setVisible(false);
attLabel2.setVisible(false);
scaleLabel1.setVisible(false);
scaleLabel2.setVisible(false);
modeLabel1.setVisible(false);
modeLabel2.setVisible(false);
medianLabel1.setVisible(false);
medianLabel2.setVisible(false);
maxLabel1.setVisible(false);
maxLabel2.setVisible(false);
minLabel1.setVisible(false);
minLabel2.setVisible(false);
meanLabel1.setVisible(false);
meanLabel2.setVisible(false);
rangeLabel1.setVisible(false);
rangeLabel2.setVisible(false);
kurtosisLabel1.setVisible(false);
kurtosisLabel2.setVisible(false);
samVarLabel1.setVisible(false);
samVarLabel2.setVisible(false);
popVarLabel1.setVisible(false);
popVarLabel2.setVisible(false);
stdDevLabel1.setVisible(false);
stdDevLabel2.setVisible(false);
geoMeanLabel1.setVisible(false);
geoMeanLabel2.setVisible(false);
attLabel1.setBounds(10, 10, 160, 20);
attLabel2.setBounds(170, 10, 160, 20);
attLabel1.setText("Attribute:");
attLabel2.setText(attribute);
attLabel1.setVisible(true);
attLabel2.setVisible(true);
scaleLabel1.setBounds(10, 30, 160, 20);
scaleLabel2.setBounds(170, 30, 160, 20);
scaleLabel1.setText("Scale Of Measure");
scaleLabel2.setText(statSum.getScale().toString());
scaleLabel1.setVisible(true);
scaleLabel2.setVisible(true);
modeLabel1.setText("Mode:");
modeLabel2.setText(statSum.getModeAsString());
modeLabel1.setBounds(10, 50, 160, 20);
modeLabel2.setBounds(170, 50, 160, 20);
modeLabel1.setVisible(true);
modeLabel2.setVisible(true);
/*
* Depending on the Scale of the attribute, different amounts of labels
* will be displayed. This is why the Scale of measure is looked at in
* order to determine the needed labels.
*/
if (statSum.getScale() != ScaleOfMeasure.NOMINAL) {
medianLabel1.setText("Median:");
medianLabel2.setText(statSum.getMedianAsString());
medianLabel1.setBounds(10, 70, 160, 20);
medianLabel2.setBounds(170, 70, 160, 20);
medianLabel1.setVisible(true);
medianLabel2.setVisible(true);
maxLabel1.setText("Maximum:");
maxLabel2.setText(statSum.getMaxAsString());
maxLabel1.setBounds(10, 90, 160, 20);
maxLabel2.setBounds(170, 90, 160, 20);
maxLabel1.setVisible(true);
maxLabel2.setVisible(true);
minLabel1.setText("Minimum:");
minLabel2.setText(statSum.getMinAsString());
minLabel1.setBounds(10, 110, 160, 20);
minLabel2.setBounds(170, 110, 160, 20);
minLabel1.setVisible(true);
minLabel2.setVisible(true);
}
if (statSum.getScale() == ScaleOfMeasure.INTERVAL
|| statSum.getScale() == ScaleOfMeasure.RATIO) {
meanLabel1.setText("Arithmetic mean:");
meanLabel2.setText(statSum.getArithmeticMeanAsString());
meanLabel1.setBounds(10, 130, 160, 20);
meanLabel2.setBounds(170, 130, 160, 20);
meanLabel1.setVisible(true);
meanLabel2.setVisible(true);
rangeLabel1.setText("range:");
rangeLabel2.setText(statSum.getRangeAsString());
rangeLabel1.setBounds(10, 150, 160, 20);
rangeLabel2.setBounds(170, 150, 160, 20);
rangeLabel1.setVisible(true);
rangeLabel2.setVisible(true);
kurtosisLabel1.setText("kurtosis:");
kurtosisLabel2.setText(statSum.getKurtosisAsString());
kurtosisLabel1.setBounds(10, 170, 160, 20);
kurtosisLabel2.setBounds(170, 170, 160, 20);
kurtosisLabel1.setVisible(true);
kurtosisLabel2.setVisible(true);
samVarLabel1.setText("sample variance:");
samVarLabel2.setText(statSum.getSampleVarianceAsString());
samVarLabel1.setBounds(10, 190, 160, 20);
samVarLabel2.setBounds(170, 190, 500, 20);
samVarLabel1.setVisible(true);
samVarLabel2.setVisible(true);
popVarLabel1.setText("population variance:");
popVarLabel2.setText(statSum.getPopulationVarianceAsString());
popVarLabel1.setBounds(10, 210, 160, 20);
popVarLabel2.setBounds(170, 210, 500, 20);
popVarLabel1.setVisible(true);
popVarLabel2.setVisible(true);
stdDevLabel1.setText("standard deviance:");
stdDevLabel2.setText(statSum.getStdDevAsString());
stdDevLabel1.setBounds(10, 230, 160, 20);
stdDevLabel2.setBounds(170, 230, 200, 20);
stdDevLabel1.setVisible(true);
stdDevLabel2.setVisible(true);
}
if (statSum.getScale() == ScaleOfMeasure.RATIO) {
geoMeanLabel1.setText("geometric mean:");
geoMeanLabel2.setText(statSum.getGeometricMeanAsString());
geoMeanLabel1.setBounds(10, 250, 160, 20);
geoMeanLabel2.setBounds(170, 250, 160, 20);
geoMeanLabel1.setVisible(true);
geoMeanLabel2.setVisible(true);
}
}
/*
* Method to display the Mode, Median, Minimum and Maximum of an attribute
* as bar series.
*
* @param barShell
*
* @param statSum
*
* @param attribute
*
* @param dataType
*
* @return
*/
public Chart barSeries(Chart chart, Shell barShell,
StatisticsSummary<?> statSum, String attribute, DataType<?> dataType) {
chart = new Chart(barShell, SWT.NONE);
chart.getAxisSet().getXAxis(0).getTitle().setVisible(false);
chart.getAxisSet().getYAxis(0).getTitle().setVisible(false);
chart.getTitle().setText(
"Displaying the Mode, Median, Minimum and Maximum of the attribute "
+ attribute);
// The method has to check for the DataType of the attribute, as "date"
// needs different parsing commands.
if (dataType != DataType.DATE) {
barSeriesDouble = new double[] {
Double.parseDouble(statSum.getModeAsString()),
Double.parseDouble(statSum.getMedianAsString()),
Double.parseDouble(statSum.getMinAsString()),
Double.parseDouble(statSum.getMaxAsString()) };
} else {
barSeriesDouble = new double[] {
stringToDate(statSum.getModeAsString()),
stringToDate(statSum.getMedianAsString()),
stringToDate(statSum.getMinAsString()),
stringToDate(statSum.getMaxAsString()), };
chart.getAxisSet().getYAxis(0).getTick().setVisible(false);
}
/*
* The following passage alters the definite zero of the DataType date and sets it
* to the 1st of January of the year 0 AD.
*/
if (dataType == DataType.DATE) {
barSeriesDouble[0] = barSeriesDouble[0] + (1970 * 31536000000L);
barSeriesDouble[1] = barSeriesDouble[1] + (1970 * 31536000000L);
barSeriesDouble[2] = barSeriesDouble[2] + (1970 * 31536000000L);
barSeriesDouble[3] = barSeriesDouble[3] + (1970 * 31536000000L);
}
IBarSeries barSeries = (IBarSeries) chart.getSeriesSet().createSeries(
SeriesType.BAR, attribute);
barSeries.setBarColor(new Color(Display.getDefault(), 80, 240, 180));
barSeries.setYSeries(barSeriesDouble);
IAxis xAxis = chart.getAxisSet().getXAxis(0);
if (dataType == DataType.DATE) {
xAxis.setCategorySeries(new String[] {
"Mode: " + statSum.getModeAsString(),
"Median: " + statSum.getMedianAsString(),
"Minimum: " + statSum.getMinAsString(),
"Maximum: " + statSum.getMaxAsString() });
} else {
xAxis.setCategorySeries(new String[] { "Mode", "Median", "Minimum",
"Maximum" });
}
xAxis.enableCategory(true);
ISeriesLabel valueLabel = barSeries.getLabel();
valueLabel.setFormat("
if (dataType == DataType.DATE) {
valueLabel.setVisible(false);
} else {
valueLabel.setVisible(true);
}
chart.getAxisSet().adjustRange();
return chart;
}
/*
* a method changing a String with the "DD.MM.YYYY"-format into a double
* value.
*
* @param dateString
*
* @return
*/
public Double stringToDate(String dateString) {
final DateFormat format = new SimpleDateFormat("DD.MM.YYYY");
Date d = null;
try {
d = format.parse(dateString);
} catch (ParseException e) {
}
return ((double) d.getTime());
}
}
|
package lbms.plugins.mldht.kad;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lbms.plugins.mldht.kad.utils.AddressUtils;
import lbms.plugins.mldht.kad.utils.ThreadLocalUtils;
public class RPCServerManager {
boolean destroyed;
public RPCServerManager(DHT dht) {
this.dht = dht;
updateBindAddrs();
}
DHT dht;
private ConcurrentHashMap<InetAddress,RPCServer> interfacesInUse = new ConcurrentHashMap<>();
private List<InetAddress> validBindAddresses = Collections.emptyList();
private volatile RPCServer[] activeServers = new RPCServer[0];
private SpamThrottle outgoingThrottle = new SpamThrottle();
public void refresh(long now) {
if(destroyed)
return;
startNewServers();
List<RPCServer> reachableServers = new ArrayList<>(interfacesInUse.values().size());
for(Iterator<RPCServer> it = interfacesInUse.values().iterator();it.hasNext();)
{
RPCServer srv = it.next();
srv.checkReachability(now);
if(srv.isReachable())
reachableServers.add(srv);
}
if(reachableServers.size() > 0) {
CompletableFuture<RPCServer> cf = activeServerFuture.getAndSet(null);
if(cf != null) {
cf.complete(reachableServers.get(ThreadLocalRandom.current().nextInt(reachableServers.size())));
}
}
activeServers = reachableServers.toArray(new RPCServer[reachableServers.size()]);
}
private void updateBindAddrs() {
try {
Class<? extends InetAddress> type = dht.getType().PREFERRED_ADDRESS_TYPE;
List<InetAddress> newBindAddrs = Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
.flatMap(iface -> iface.getInterfaceAddresses().stream())
.map(ifa -> ifa.getAddress())
.filter(addr -> type.isInstance(addr))
.distinct()
.collect(Collectors.toCollection(() -> new ArrayList<>()));
newBindAddrs.add(AddressUtils.getAnyLocalAddress(type));
newBindAddrs.removeIf(normalizedAddressPredicate().negate());
validBindAddresses = newBindAddrs;
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doBindChecks() {
updateBindAddrs();
getAllServers().forEach(srv -> {
if(!validBindAddresses.contains(srv.getBindAddress())) {
srv.stop();
}
});
}
private Predicate<InetAddress> normalizedAddressPredicate() {
Predicate<InetAddress> pred = dht.config.filterBindAddress();
return (addr) -> {
if(pred.test(AddressUtils.getAnyLocalAddress(addr.getClass()))) {
return true;
}
return pred.test(addr);
};
}
private void startNewServers() {
boolean multihome = dht.config.allowMultiHoming();
Class<? extends InetAddress> addressType = dht.getType().PREFERRED_ADDRESS_TYPE;
Predicate<InetAddress> addressFilter = normalizedAddressPredicate();
if(multihome) {
// we only consider global unicast addresses in multihoming mode
// this is mostly meant for server configurations
List<InetAddress> addrs = AddressUtils.getAvailableGloballyRoutableAddrs(addressType)
.stream()
.filter(addressFilter)
.collect(Collectors.toCollection(ArrayList::new));
addrs.removeAll(interfacesInUse.keySet());
// create new servers for all IPs we aren't currently haven't bound
addrs.forEach(addr -> newServer(addr));
return;
}
// single home
RPCServer current = interfacesInUse.values().stream().findAny().orElse(null);
InetAddress defaultBind = Optional.ofNullable(AddressUtils.getDefaultRoute(addressType)).filter(addressFilter).orElse(null);
// check if we have bound to an anylocaladdress because we didn't know any better and consensus converged on a local address
// that's mostly going to happen on v6 if we can't find a default route for v6
// no need to recheck address filter since it allowed any local address bind in the first place
if(current != null && current.getBindAddress().isAnyLocalAddress() && current.getConsensusExternalAddress() != null && AddressUtils.isValidBindAddress(current.getConsensusExternalAddress().getAddress()))
{
InetAddress rebindAddress = current.getConsensusExternalAddress().getAddress();
current.stop();
newServer(rebindAddress);
return;
}
// default bind changed and server is not reachable anymore. this may happen when an interface is nominally still available but not routable anymore. e.g. ipv6 temporary addresses
if(current != null && defaultBind != null && !current.getBindAddress().equals(defaultBind) && !current.isReachable() && current.age().getSeconds() > TimeUnit.MINUTES.toSeconds(2)) {
current.stop();
newServer(defaultBind);
return;
}
// single homed & already have a server -> no need for another one
if(current != null)
return;
// this is our default strategy.
if(defaultBind != null) {
newServer(defaultBind);
return;
}
// last resort for v6, try a random global unicast address, otherwise anylocal
if(addressType.isAssignableFrom(Inet6Address.class)) {
InetAddress addr = AddressUtils.getAvailableGloballyRoutableAddrs(addressType)
.stream()
.filter(addressFilter)
.findAny()
.orElse(Optional.of(AddressUtils.getAnyLocalAddress(addressType))
.filter(addressFilter)
.orElse(null));
if(addr != null) {
newServer(addr);
}
return;
}
// last resort v4: try any-local address first. If the address filter forbids that we try any of the interface addresses including non-global ones
Stream.concat(Stream.of(AddressUtils.getAnyLocalAddress(addressType)), AddressUtils.nonlocalAddresses()
.filter(dht.getType()::canUseAddress))
.filter(addressFilter)
.findFirst()
.ifPresent(addr -> {
newServer(addr);
});
}
private void newServer(InetAddress addr) {
RPCServer srv = new RPCServer(this,addr,dht.config.getListeningPort(), dht.serverStats);
// doing the socket setup takes time, do it in the background
srv.setOutgoingThrottle(outgoingThrottle);
onServerRegistration.forEach(c -> c.accept(srv));
dht.getScheduler().execute(srv::start);
interfacesInUse.put(addr, srv);
}
List<Consumer<RPCServer>> onServerRegistration = new CopyOnWriteArrayList<>();
void notifyOnServerAdded(Consumer<RPCServer> toNotify) {
onServerRegistration.add(toNotify);
}
void serverRemoved(RPCServer srv) {
interfacesInUse.remove(srv.getBindAddress(),srv);
refresh(System.currentTimeMillis());
dht.getTaskManager().removeServer(srv);
}
public void destroy() {
destroyed = true;
new ArrayList<>(interfacesInUse.values()).parallelStream().forEach(RPCServer::stop);
CompletableFuture<RPCServer> cf = activeServerFuture.getAndSet(null);
if(cf != null) {
cf.completeExceptionally(new DHTException("could not obtain active server, DHT was shut down"));
}
}
public int getServerCount() {
return interfacesInUse.size();
}
public int getActiveServerCount()
{
return activeServers.length;
}
public SpamThrottle getOutgoingRequestThrottle() {
return outgoingThrottle;
}
/**
* @param fallback tries to return an inactive server if no active one can be found
* @return a random active server, or <code>null</code> if none can be found
*/
public RPCServer getRandomActiveServer(boolean fallback)
{
RPCServer[] srvs = activeServers;
if(srvs.length == 0)
return fallback ? getRandomServer() : null;
return srvs[ThreadLocalUtils.getThreadLocalRandom().nextInt(srvs.length)];
}
AtomicReference<CompletableFuture<RPCServer>> activeServerFuture = new AtomicReference<>(null);
public CompletableFuture<RPCServer> awaitActiveServer() {
return activeServerFuture.updateAndGet(existing -> {
if(existing != null)
return existing;
return new CompletableFuture<>();
});
}
/**
* may return null
*/
public RPCServer getRandomServer() {
List<RPCServer> servers = getAllServers();
if(servers.isEmpty())
return null;
return servers.get(ThreadLocalUtils.getThreadLocalRandom().nextInt(servers.size()));
}
public List<RPCServer> getAllServers() {
return new ArrayList<>(interfacesInUse.values());
}
}
|
package cgeo.geocaching;
import butterknife.InjectView;
import butterknife.Views;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.Units;
import cgeo.geocaching.maps.CGeoMap;
import cgeo.geocaching.speech.SpeechService;
import cgeo.geocaching.ui.CompassView;
import cgeo.geocaching.utils.GeoDirHandler;
import cgeo.geocaching.utils.Log;
import org.apache.commons.lang3.StringUtils;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech.Engine;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class CompassActivity extends AbstractActivity {
@InjectView(R.id.nav_type) protected TextView navType;
@InjectView(R.id.nav_accuracy) protected TextView navAccuracy;
@InjectView(R.id.nav_satellites) protected TextView navSatellites;
@InjectView(R.id.nav_location) protected TextView navLocation;
@InjectView(R.id.distance) protected TextView distanceView;
@InjectView(R.id.heading) protected TextView headingView;
@InjectView(R.id.rose) protected CompassView compassView;
@InjectView(R.id.destination) protected TextView destinationTextView;
@InjectView(R.id.cacheinfo) protected TextView cacheInfoView;
private static final String EXTRAS_COORDS = "coords";
private static final String EXTRAS_NAME = "name";
private static final String EXTRAS_GEOCODE = "geocode";
private static final String EXTRAS_CACHE_INFO = "cacheinfo";
private static final List<IWaypoint> coordinates = new ArrayList<IWaypoint>();
private static final int COORDINATES_OFFSET = 10;
private static final int REQUEST_TTS_DATA_CHECK = 1;
private Geopoint dstCoords = null;
private float cacheHeading = 0;
private String title = null;
private String info = null;
private boolean hasMagneticFieldSensor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.compass_activity);
final SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
hasMagneticFieldSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null;
if (!hasMagneticFieldSensor) {
Settings.setUseCompass(false);
}
// get parameters
Bundle extras = getIntent().getExtras();
if (extras != null) {
title = extras.getString(EXTRAS_GEOCODE);
final String name = extras.getString(EXTRAS_NAME);
dstCoords = extras.getParcelable(EXTRAS_COORDS);
info = extras.getString(EXTRAS_CACHE_INFO);
if (StringUtils.isNotBlank(name)) {
if (StringUtils.isNotBlank(title)) {
title += ": " + name;
} else {
title = name;
}
}
} else {
Intent pointIntent = new Intent(this, NavigateAnyPointActivity.class);
startActivity(pointIntent);
finish();
return;
}
// set header
setTitle();
setDestCoords();
setCacheInfo();
Views.inject(this);
// make sure we can control the TTS volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
public void onResume() {
super.onResume();
// sensor & geolocation manager
geoDirHandler.startGeoAndDir();
}
@Override
public void onPause() {
geoDirHandler.stopGeoAndDir();
super.onPause();
}
@Override
public void onDestroy() {
compassView.destroyDrawingCache();
SpeechService.stopService(this);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.compass_activity_options, menu);
menu.findItem(R.id.menu_switch_compass_gps).setVisible(hasMagneticFieldSensor);
final SubMenu subMenu = menu.findItem(R.id.menu_select_destination).getSubMenu();
if (coordinates.size() > 1) {
for (int i = 0; i < coordinates.size(); i++) {
final IWaypoint coordinate = coordinates.get(i);
subMenu.add(0, COORDINATES_OFFSET + i, 0, coordinate.getName() + " (" + coordinate.getCoordType() + ")");
}
} else {
menu.findItem(R.id.menu_select_destination).setVisible(false);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.menu_switch_compass_gps).setTitle(res.getString(Settings.isUseCompass() ? R.string.use_gps : R.string.use_compass));
menu.findItem(R.id.menu_tts_start).setVisible(!SpeechService.isRunning());
menu.findItem(R.id.menu_tts_stop).setVisible(SpeechService.isRunning());
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu_map:
CGeoMap.startActivityCoords(this, dstCoords, null, null);
return true;
case R.id.menu_switch_compass_gps:
boolean oldSetting = Settings.isUseCompass();
Settings.setUseCompass(!oldSetting);
invalidateOptionsMenuCompatible();
if (oldSetting) {
geoDirHandler.stopDir();
} else {
geoDirHandler.startDir();
}
return true;
case R.id.menu_edit_destination:
Intent pointIntent = new Intent(this, NavigateAnyPointActivity.class);
startActivity(pointIntent);
finish();
return true;
case R.id.menu_tts_start:
initTextToSpeech();
return true;
case R.id.menu_tts_stop:
SpeechService.stopService(this);
return true;
default:
int coordinatesIndex = id - COORDINATES_OFFSET;
if (coordinatesIndex >= 0 && coordinatesIndex < coordinates.size()) {
final IWaypoint coordinate = coordinates.get(coordinatesIndex);
title = coordinate.getName();
dstCoords = coordinate.getCoords();
setTitle();
setDestCoords();
setCacheInfo();
updateDistanceInfo(app.currentGeo());
Log.d("destination set: " + title + " (" + dstCoords + ")");
return true;
}
}
return false;
}
private void initTextToSpeech() {
Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, REQUEST_TTS_DATA_CHECK);
}
@Override
protected void onActivityResult(int request, int result, Intent data) {
if (request == REQUEST_TTS_DATA_CHECK && result == Engine.CHECK_VOICE_DATA_PASS) {
SpeechService.startService(this, dstCoords);
} else {
Log.i("TTS failed to start. Request: " + request + " result: " + result);
startActivity(new Intent(Engine.ACTION_INSTALL_TTS_DATA));
}
}
private void setTitle() {
if (StringUtils.isNotBlank(title)) {
setTitle(title);
} else {
setTitle(res.getString(R.string.navigation));
}
}
private void setDestCoords() {
if (dstCoords == null) {
return;
}
destinationTextView.setText(dstCoords.toString());
}
private void setCacheInfo() {
if (info == null) {
cacheInfoView.setVisibility(View.GONE);
return;
}
cacheInfoView.setVisibility(View.VISIBLE);
cacheInfoView.setText(info);
}
private void updateDistanceInfo(final IGeoData geo) {
if (geo.getCoords() == null || dstCoords == null) {
return;
}
cacheHeading = geo.getCoords().bearingTo(dstCoords);
distanceView.setText(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(dstCoords)));
headingView.setText(Math.round(cacheHeading) + "°");
}
private GeoDirHandler geoDirHandler = new GeoDirHandler() {
@Override
public void updateGeoData(final IGeoData geo) {
try {
if (geo.getCoords() != null) {
if (geo.getSatellitesVisible() >= 0) {
navSatellites.setText(res.getString(R.string.loc_sat) + ": " + geo.getSatellitesFixed() + "/" + geo.getSatellitesVisible());
} else {
navSatellites.setText("");
}
navType.setText(res.getString(geo.getLocationProvider().resourceId));
if (geo.getAccuracy() >= 0) {
navAccuracy.setText("±" + Units.getDistanceFromMeters(geo.getAccuracy()));
} else {
navAccuracy.setText(null);
}
if (geo.getAltitude() != 0.0f) {
final String humanAlt = Units.getDistanceFromMeters((float) geo.getAltitude());
navLocation.setText(geo.getCoords() + " | " + humanAlt);
} else {
navLocation.setText(geo.getCoords().toString());
}
updateDistanceInfo(geo);
} else {
navType.setText(null);
navAccuracy.setText(null);
navLocation.setText(res.getString(R.string.loc_trying));
}
if (!Settings.isUseCompass() || geo.getSpeed() > 5) { // use GPS when speed is higher than 18 km/h
updateNorthHeading(geo.getBearing());
}
} catch (Exception e) {
Log.w("Failed to LocationUpdater location.");
}
}
@Override
public void updateDirection(final float direction) {
if (app.currentGeo().getSpeed() <= 5) { // use compass when speed is lower than 18 km/h
updateNorthHeading(DirectionProvider.getDirectionNow(CompassActivity.this, direction));
}
}
};
private void updateNorthHeading(final float northHeading) {
if (compassView != null) {
compassView.updateNorth(northHeading, cacheHeading);
}
}
public static void startActivity(final Context context, final String geocode, final String displayedName, final Geopoint coords, final Collection<IWaypoint> coordinatesWithType,
final String info) {
coordinates.clear();
if (coordinatesWithType != null) {
for (IWaypoint coordinate : coordinatesWithType) {
if (coordinate != null) {
coordinates.add(coordinate);
}
}
}
final Intent navigateIntent = new Intent(context, CompassActivity.class);
navigateIntent.putExtra(EXTRAS_COORDS, coords);
navigateIntent.putExtra(EXTRAS_GEOCODE, geocode);
if (null != displayedName) {
navigateIntent.putExtra(EXTRAS_NAME, displayedName);
}
navigateIntent.putExtra(EXTRAS_CACHE_INFO, info);
context.startActivity(navigateIntent);
}
public static void startActivity(final Context context, final String geocode, final String displayedName, final Geopoint coords, final Collection<IWaypoint> coordinatesWithType) {
CompassActivity.startActivity(context, geocode, displayedName, coords, coordinatesWithType, null);
}
}
|
package cgeo.geocaching.list;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.DataStore;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.ui.dialog.Dialogs;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import rx.functions.Action1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public final class StoredList extends AbstractList {
public static final int TEMPORARY_LIST_ID = 0;
public static final StoredList TEMPORARY_LIST = new StoredList(TEMPORARY_LIST_ID, "<temporary>", 0); // Never displayed
public static final int STANDARD_LIST_ID = 1;
private final int count; // this value is only valid as long as the list is not changed by other database operations
public StoredList(int id, String title, int count) {
super(id, title);
this.count = count;
}
@Override
public String getTitleAndCount() {
return title + " [" + count + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof StoredList)) {
return false;
}
return id == ((StoredList) obj).id;
}
public static class UserInterface {
private final Activity activity;
private final CgeoApplication app;
private final Resources res;
public UserInterface(final Activity activity) {
this.activity = activity;
app = CgeoApplication.getInstance();
res = app.getResources();
}
public void promptForListSelection(final int titleId, @NonNull final Action1<Integer> runAfterwards) {
promptForListSelection(titleId, runAfterwards, false, -1);
}
public void promptForListSelection(final int titleId, @NonNull final Action1<Integer> runAfterwards, final boolean onlyConcreteLists, final int exceptListId) {
promptForListSelection(titleId, runAfterwards, onlyConcreteLists, exceptListId, StringUtils.EMPTY);
}
public void promptForListSelection(final int titleId, @NonNull final Action1<Integer> runAfterwards, final boolean onlyConcreteLists, final int exceptListId, final String newListName) {
final List<AbstractList> lists = new ArrayList<AbstractList>();
lists.addAll(getSortedLists());
if (exceptListId > StoredList.TEMPORARY_LIST_ID) {
StoredList exceptList = DataStore.getList(exceptListId);
if (exceptList != null) {
lists.remove(exceptList);
}
}
if (!onlyConcreteLists) {
if (exceptListId != PseudoList.ALL_LIST.id) {
lists.add(PseudoList.ALL_LIST);
}
if (exceptListId != PseudoList.HISTORY_LIST.id) {
lists.add(PseudoList.HISTORY_LIST);
}
}
lists.add(PseudoList.NEW_LIST);
final List<CharSequence> listsTitle = new ArrayList<CharSequence>();
for (AbstractList list : lists) {
listsTitle.add(list.getTitleAndCount());
}
final CharSequence[] items = new CharSequence[listsTitle.size()];
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(res.getString(titleId));
builder.setItems(listsTitle.toArray(items), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int itemId) {
final AbstractList list = lists.get(itemId);
if (list == PseudoList.NEW_LIST) {
// create new list on the fly
promptForListCreation(runAfterwards, newListName);
}
else {
runAfterwards.call(lists.get(itemId).id);
}
}
});
builder.create().show();
}
@NonNull
private static List<StoredList> getSortedLists() {
final Collator collator = Collator.getInstance();
final List<StoredList> lists = DataStore.getLists();
Collections.sort(lists, new Comparator<StoredList>() {
@Override
public int compare(StoredList lhs, StoredList rhs) {
// have the standard list at the top
if (lhs.id == STANDARD_LIST_ID) {
return -1;
}
if (rhs.id == STANDARD_LIST_ID) {
return 1;
}
// otherwise sort alphabetical
return collator.compare(lhs.getTitle(), rhs.getTitle());
}
});
return lists;
}
public void promptForListCreation(@NonNull final Action1<Integer> runAfterwards, String newListName) {
handleListNameInput(newListName, R.string.list_dialog_create_title, R.string.list_dialog_create, new Action1<String>() {
// We need to update the list cache by creating a new StoredList object here.
@SuppressWarnings("unused")
@Override
public void call(final String listName) {
final int newId = DataStore.createList(listName);
new StoredList(newId, listName, 0);
if (newId >= DataStore.customListIdOffset) {
ActivityMixin.showToast(activity, res.getString(R.string.list_dialog_create_ok));
runAfterwards.call(newId);
} else {
ActivityMixin.showToast(activity, res.getString(R.string.list_dialog_create_err));
}
}
});
}
private void handleListNameInput(final String defaultValue, int dialogTitle, int buttonTitle, final Action1<String> runnable) {
Dialogs.input(activity, dialogTitle, defaultValue, buttonTitle, new Action1<String>() {
@Override
public void call(final String input) {
// remove whitespaces added by autocompletion of Android keyboard
String listName = StringUtils.trim(input);
if (StringUtils.isNotBlank(listName)) {
runnable.call(listName);
}
}
});
}
public void promptForListRename(final int listId, @NonNull final Runnable runAfterRename) {
final StoredList list = DataStore.getList(listId);
handleListNameInput(list.title, R.string.list_dialog_rename_title, R.string.list_dialog_rename, new Action1<String>() {
@Override
public void call(final String listName) {
DataStore.renameList(listId, listName);
runAfterRename.run();
}
});
}
}
/**
* Get the list title. This method is not public by intention to make clients use the {@link UserInterface} class.
*
* @return
*/
protected String getTitle() {
return title;
}
/**
* Return the given list, if it is a concrete list. Return the default list otherwise.
*/
public static int getConcreteList(int listId) {
if (listId == PseudoList.ALL_LIST.id || listId == TEMPORARY_LIST_ID || listId == PseudoList.HISTORY_LIST.id) {
return STANDARD_LIST_ID;
}
return listId;
}
@Override
public boolean isConcrete() {
return true;
}
}
|
package groovy.servlet;
import groovy.lang.MetaClass;
import groovy.util.ResourceConnector;
import groovy.util.ResourceException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
public abstract class AbstractHttpServlet extends HttpServlet implements ResourceConnector {
/**
* Content type of the HTTP response.
*/
public static final String CONTENT_TYPE_TEXT_HTML = "text/html";
/**
* Servlet API include key name: path_info
*/
public static final String INC_PATH_INFO = "javax.servlet.include.path_info";
public static final String INC_REQUEST_URI = "javax.servlet.include.request_uri";
/**
* Servlet API include key name: servlet_path
*/
public static final String INC_SERVLET_PATH = "javax.servlet.include.servlet_path";
/**
* Servlet (or the web application) context.
*/
protected ServletContext servletContext;
/**
* <b>Null</b> or compiled pattern matcher read from "resource.name.regex"
* and used in {@link AbstractHttpServlet#getResourceConnection(String)}.
*/
protected Matcher resourceNameMatcher;
/**
* The replacement used by the resource name matcher.
*/
protected String resourceNameReplacement;
/**
* The replace method to use on the matcher.
* <pre>
* true - replaceAll(resourceNameReplacement); (default)
* false - replaceFirst(resourceNameReplacement);
* </pre>
*/
protected boolean resourceNameReplaceAll;
/**
* Controls almost all log output.
*/
protected boolean verbose;
/**
* Mirrors the static value of the reflection flag in MetaClass.
* See {@link AbstractHttpServlet#logGROOVY861}
*/
protected boolean reflection;
/**
* Debug flag logging the class the class loader of the request.
*/
private boolean logGROOVY861;
/**
* Initializes all fields with default values.
*/
public AbstractHttpServlet() {
this.servletContext = null;
this.resourceNameMatcher = null;
this.resourceNameReplacement = null;
this.resourceNameReplaceAll = true;
this.verbose = false;
this.reflection = false;
this.logGROOVY861 = false;
}
/**
* Interface method for ResourceContainer. This is used by the GroovyScriptEngine.
*/
public URLConnection getResourceConnection(String name) throws ResourceException {
/*
* First, mangle resource name with the compiled pattern.
*/
Matcher matcher = resourceNameMatcher;
if (matcher != null) {
matcher.reset(name);
String replaced;
if (resourceNameReplaceAll) {
replaced = resourceNameMatcher.replaceAll(resourceNameReplacement);
} else {
replaced = resourceNameMatcher.replaceFirst(resourceNameReplacement);
}
if (!name.equals(replaced)) {
if (verbose) {
log("Replaced resource name \"" + name + "\" with \"" + replaced + "\".");
}
name = replaced;
}
}
/*
* Try to locate the resource and return an opened connection to it.
*/
try {
URL url = servletContext.getResource("/" + name);
if (url == null) {
url = servletContext.getResource("/WEB-INF/groovy/" + name);
}
if (url == null) {
throw new ResourceException("Resource \"" + name + "\" not found!");
}
return url.openConnection();
} catch (IOException e) {
throw new ResourceException("Problems getting resource named \"" + name + "\"!", e);
}
}
/**
* Returns the include-aware uri of the script or template file.
*
* @param request
* the http request to analyze
* @return the include-aware uri either parsed from request attributes or
* hints provided by the servlet container
*/
protected String getScriptUri(HttpServletRequest request) {
if (logGROOVY861) {
log("Logging request class and its class loader:");
log(" c = request.getClass() :\"" + request.getClass() + "\"");
log(" l = c.getClassLoader() :\"" + request.getClass().getClassLoader() + "\"");
log(" l.getClass() :\"" + request.getClass().getClassLoader().getClass() + "\"");
/*
* Keep logging, if we're verbose. Else turn it off.
*/
logGROOVY861 = verbose;
}
// NOTE: This piece of code is heavily inspired by Apaches Jasper2!
// src/share/org/apache/jasper/servlet/JspServlet.java?view=markup
// Why doesn't it use request.getRequestURI() or INC_REQUEST_URI?
String uri = null;
String info = null;
// Check to see if the requested script/template source file has been the
// target of a RequestDispatcher.include().
uri = (String) request.getAttribute(INC_SERVLET_PATH);
if (uri != null) {
// Requested script/template file has been target of
// RequestDispatcher.include(). Its path is assembled from the relevant
// javax.servlet.include.* request attributes and returned!
info = (String) request.getAttribute(INC_PATH_INFO);
if (info != null) {
uri += info;
}
return uri;
}
// Requested script/template file has not been the target of a
// RequestDispatcher.include(). Reconstruct its path from the request's
// getServletPath() and getPathInfo() results.
uri = request.getServletPath();
info = request.getPathInfo();
if (info != null) {
uri += info;
}
return uri;
}
/**
* Parses the http request for the real script or template source file.
*
* @param request
* the http request to analyze
* @param context
* the context of this servlet used to get the real path string
* @return a file object using an absolute file path name
*/
protected File getScriptUriAsFile(HttpServletRequest request) {
String uri = getScriptUri(request);
String real = servletContext.getRealPath(uri);
File file = new File(real).getAbsoluteFile();
return file;
}
/**
* Overrides the generic init method to set some debug flags.
*
* @param config
* the servlet coniguration provided by the container
* @throws ServletException if init() method defined in super class
* javax.servlet.GenericServlet throws it
*/
public void init(ServletConfig config) throws ServletException {
/*
* Never forget super.init()!
*/
super.init(config);
/*
* Grab the servlet context.
*/
this.servletContext = config.getServletContext();
/*
* Get verbosity hint.
*/
String value = config.getInitParameter("verbose");
if (value != null) {
this.verbose = Boolean.valueOf(value).booleanValue();
}
/*
* And now the real init work...
*/
if (verbose) {
log("Parsing init parameters...");
}
String regex = config.getInitParameter("resource.name.regex");
if (regex != null) {
String replacement = config.getInitParameter("resource.name.replacement");
if (replacement == null) {
Exception npex = new NullPointerException("resource.name.replacement");
String message = "Init-param 'resource.name.replacement' not specified!";
log(message, npex);
throw new ServletException(message, npex);
}
int flags = 0; // TODO : Parse pattern compile flags.
this.resourceNameMatcher = Pattern.compile(regex, flags).matcher("");
this.resourceNameReplacement = replacement;
String all = config.getInitParameter("resource.name.replace.all");
if (all != null) {
this.resourceNameReplaceAll = Boolean.valueOf(all).booleanValue();
}
}
value = config.getInitParameter("reflection");
if (value != null) {
this.reflection = Boolean.valueOf(value).booleanValue();
MetaClass.setUseReflection(reflection);
}
value = config.getInitParameter("logGROOVY861");
if (value != null) {
this.logGROOVY861 = Boolean.valueOf(value).booleanValue();
// nothing else to do here
}
/*
* If verbose, log the parameter values.
*/
if (verbose) {
log("(Abstract) init done. Listing some parameter name/value pairs:");
log("verbose = " + verbose); // this *is* verbose! ;)
log("reflection = " + reflection);
log("logGROOVY861 = " + logGROOVY861);
if (resourceNameMatcher != null) {
log("resource.name.regex = " + resourceNameMatcher.pattern().pattern());
}
else {
log("resource.name.regex = null");
}
log("resource.name.replacement = " + resourceNameReplacement);
}
}
}
|
package is.xyz.mpv;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.content.Intent;
import android.net.Uri;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MPVActivity extends Activity implements EventObserver {
private static final String TAG = "mpv";
// how long should controls be displayed on screen
private static final int CONTROLS_DISPLAY_TIMEOUT = 2000;
MPVView player;
View controls;
Handler fadeHandler;
FadeOutControlsRunnable fadeRunnable;
SeekBar seekbar;
boolean userIsOperatingSeekbar = false;
private SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!fromUser)
return;
player.setTimePos(progress);
updatePlaybackPos(progress);
}
@Override public void onStartTrackingTouch(SeekBar seekBar) {
userIsOperatingSeekbar = true;
}
@Override public void onStopTrackingTouch(SeekBar seekBar) {
userIsOperatingSeekbar = false;
}
};
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Do copyAssets here and not in MainActivity because mpv can be launched from a file browser
copyAssets();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.player);
controls = findViewById(R.id.controls);
seekbar = (SeekBar) findViewById(R.id.controls_seekbar);
// Init controls to be hidden and view fullscreen
initControls();
// set up a callback handler and a runnable for fading the controls out
fadeHandler = new Handler();
fadeRunnable = new FadeOutControlsRunnable(this, controls);
String filepath = null;
Intent i = getIntent();
String action = i.getAction();
if (action != null && action.equals(Intent.ACTION_VIEW)) {
// launched as viewer for a specific file
Uri u = i.getData();
if (u.getScheme().equals("file"))
filepath = u.getPath();
else if (u.getScheme().equals("content"))
filepath = getRealPathFromURI(u);
else if (u.getScheme().equals("http"))
filepath = u.toString();
if (filepath == null) {
Log.e(TAG, "unknown scheme: " + u.getScheme());
}
} else {
filepath = i.getStringExtra("filepath");
}
player = (MPVView) findViewById(R.id.mpv_view);
player.initialize(getApplicationContext().getFilesDir().getPath());
player.addObserver(this);
player.playFile(filepath);
seekbar.setOnSeekBarChangeListener(seekBarChangeListener);
// After hiding the interface with SYSTEM_UI_FLAG_HIDE_NAVIGATION the next tap only shows the UI without
// calling dispatchTouchEvent. Use this to showControls even in this case.
player.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int vis) {
if (vis == 0) {
showControls();
}
}
});
}
@Override protected void onDestroy() {
player.destroy();
player = null;
super.onDestroy();
}
private String getRealPathFromURI(Uri contentUri) {
// http://stackoverflow.com/questions/3401579/#3414749
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null)
cursor.close();
}
}
private void copyAssets() {
AssetManager assetManager = getApplicationContext().getAssets();
String files[] = {"subfont.ttf"};
String configDir = getApplicationContext().getFilesDir().getPath();
for (String filename : files) {
InputStream in;
OutputStream out;
try {
in = assetManager.open(filename, AssetManager.ACCESS_STREAMING);
File outFile = new File(configDir + "/" + filename);
// XXX: .available() officially returns an *estimated* number of bytes available
// this is only accurate for generic streams, asset streams return the full file size
if (outFile.length() == in.available()) {
in.close();
Log.w(TAG, "Skipping copy of asset file (exists same size): " + filename);
continue;
}
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
out.close();
Log.w(TAG, "Copied asset file: " + filename);
} catch(IOException e) {
Log.e(TAG, "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[32768];
int r;
while ((r = in.read(buf)) != -1)
out.write(buf, 0, r);
}
@Override protected void onPause() {
player.onPause();
super.onPause();
}
@Override protected void onResume() {
// Init controls to be hidden and view fullscreen
initControls();
player.onResume();
super.onResume();
}
private void showControls() {
// remove all callbacks that were to be run for fading
fadeHandler.removeCallbacks(fadeRunnable);
// set the main controls as 75%, actual seek bar|buttons as 100%
controls.setAlpha(1f);
// Open, Sesame!
controls.setVisibility(View.VISIBLE);
// add a new callback to hide the controls once again
fadeHandler.postDelayed(fadeRunnable, CONTROLS_DISPLAY_TIMEOUT);
}
public void initControls() {
/* Init controls to be hidden */
// use GONE here instead of INVISIBLE (which makes more sense) because of Android bug with surface views
controls.setVisibility(View.GONE);
int flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(flags);
}
@Override public boolean dispatchTouchEvent(MotionEvent ev) {
showControls();
return super.dispatchTouchEvent(ev);
}
public void playPause(View view) {
player.cyclePause();
}
public void cycleAudio(View view) {
player.cycleAudio();
}
public void cycleSub(View view) {
player.cycleSub();
}
public void switchDecoder(View view) {
player.cycleHwdec();
updateDecoderButton();
}
String prettyTime(int d) {
long hours = d / 3600, minutes = (d % 3600) / 60, seconds = d % 60;
if (hours == 0)
return String.format("%02d:%02d", minutes, seconds);
return String.format("%d:%02d:%02d", hours, minutes, seconds);
}
public void updatePlaybackPos(int position) {
TextView positionView = (TextView) findViewById(R.id.controls_position);
positionView.setText(prettyTime(position));
if (!userIsOperatingSeekbar)
seekbar.setProgress(position);
updateDecoderButton();
}
public void updatePlaybackDuration(int duration) {
TextView durationView = (TextView) findViewById(R.id.controls_duration);
durationView.setText(prettyTime(duration));
if (!userIsOperatingSeekbar)
seekbar.setMax(duration);
}
public void updatePlaybackStatus(boolean paused) {
ImageButton playBtn = (ImageButton) findViewById(R.id.controls_play);
if (paused)
playBtn.setImageResource(R.drawable.ic_play_arrow_black_24dp);
else
playBtn.setImageResource(R.drawable.ic_pause_black_24dp);
}
public void updateDecoderButton() {
Button switchDecoderBtn = (Button) findViewById(R.id.switchDecoder);
switchDecoderBtn.setText(player.isHwdecActive() ? "HW" : "SW");
}
public void eventPropertyUi(String property) {
}
public void eventPropertyUi(String property, boolean value) {
switch (property) {
case "pause":
updatePlaybackStatus(value);
break;
}
}
public void eventPropertyUi(String property, long value) {
switch (property) {
case "time-pos":
updatePlaybackPos((int) value);
break;
case "duration":
updatePlaybackDuration((int) value);
break;
}
}
public void eventPropertyUi(String property, String value) {
}
@Override public void eventProperty(final String property) {
runOnUiThread(new Runnable() { public void run() { eventPropertyUi(property); } });
}
@Override public void eventProperty(final String property, final boolean value) {
runOnUiThread(new Runnable() { public void run() { eventPropertyUi(property, value); } });
}
@Override public void eventProperty(final String property, final long value) {
runOnUiThread(new Runnable() { public void run() { eventPropertyUi(property, value); } });
}
@Override public void eventProperty(final String property, final String value) {
runOnUiThread(new Runnable() { public void run() { eventPropertyUi(property, value); } });
}
}
class FadeOutControlsRunnable implements Runnable {
private final MPVActivity activity;
private final View controls;
public FadeOutControlsRunnable(MPVActivity activity_, View controls_) {
super();
activity = activity_;
controls = controls_;
}
@Override
public void run() {
// use GONE here instead of INVISIBLE (which makes more sense) because of Android bug with surface views
controls.animate()
.alpha(0f)
.setDuration(500)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
activity.initControls();
}
});
}
}
|
package com.ezardlabs.lostsector;
import com.ezardlabs.dethsquare.Animator;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.LevelManager;
import com.ezardlabs.dethsquare.Renderer;
import com.ezardlabs.dethsquare.Rigidbody;
import com.ezardlabs.dethsquare.TextureAtlas;
import com.ezardlabs.dethsquare.multiplayer.NetworkAnimator;
import com.ezardlabs.dethsquare.multiplayer.NetworkRenderer;
import com.ezardlabs.dethsquare.multiplayer.NetworkTransform;
import com.ezardlabs.dethsquare.prefabs.PrefabManager;
import com.ezardlabs.dethsquare.util.BaseGame;
import com.ezardlabs.lostsector.levels.ExploreLevel;
import com.ezardlabs.lostsector.levels.MainMenuLevel;
import com.ezardlabs.lostsector.levels.MultiplayerLevel;
import com.ezardlabs.lostsector.levels.MultiplayerLobbyLevel;
import com.ezardlabs.lostsector.levels.ProceduralLevel;
import com.ezardlabs.lostsector.levels.SurvivalLevel;
import com.ezardlabs.lostsector.objects.Player;
import com.ezardlabs.lostsector.objects.enemies.corpus.crewmen.DeraCrewman;
import com.ezardlabs.lostsector.objects.enemies.corpus.crewmen.ProvaCrewman;
import com.ezardlabs.lostsector.objects.enemies.corpus.crewmen.SupraCrewman;
import com.ezardlabs.lostsector.objects.environment.Door;
import com.ezardlabs.lostsector.objects.environment.LaserDoor;
import com.ezardlabs.lostsector.objects.environment.Locker;
import com.ezardlabs.lostsector.objects.hud.HUD;
import com.ezardlabs.lostsector.objects.projectiles.LankaBeam;
import com.ezardlabs.lostsector.objects.warframes.Frost;
public class Game extends BaseGame {
public static GameObject[] players;
public enum DamageType {
NORMAL,
SLASH,
COLD,
KUBROW
}
@Override
public void create() {
LevelManager.registerLevel("explore", new ExploreLevel());
LevelManager.registerLevel("survival", new SurvivalLevel());
LevelManager.registerLevel("procedural", new ProceduralLevel());
LevelManager.registerLevel("multiplayer_lobby", new MultiplayerLobbyLevel());
LevelManager.registerLevel("multiplayer", new MultiplayerLevel());
LevelManager.registerLevel("main_menu", new MainMenuLevel());
registerPlayerPrefabs();
registerProjectilePrefabs();
registerDoorPrefabs();
registerLockerPrefabs();
registerEnemyPrefabs();
LevelManager.loadLevel("main_menu");
}
private void registerPlayerPrefabs() {
PrefabManager.addPrefab("player",
() -> new GameObject("Player", "player", new Player(), new HUD(), new Renderer(),
new Animator(), new Frost(), new Collider(200, 200), new Rigidbody(),
new NetworkTransform(), new NetworkRenderer(), new NetworkAnimator()),
() -> new GameObject("Other Player", "player", new Renderer(), new Animator(),
new Frost(), new Collider(200, 200), new NetworkTransform(),
new NetworkRenderer(), new NetworkAnimator()));
}
private void registerProjectilePrefabs() {
PrefabManager.addPrefab("lanka_beam",
() -> new GameObject("Lanka Beam", new Renderer("images/blue.png", 0, 0),
new LankaBeam(500), new NetworkTransform(), new NetworkRenderer()),
() -> new GameObject("Lanka Beam", new Renderer("images/blue.png", 0, 0),
new NetworkTransform(), new NetworkRenderer()));
}
private void registerDoorPrefabs() {
PrefabManager.addPrefab("door", () -> new GameObject("Door", new Door(
new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")),
new Renderer(), new Animator(), new Collider(100, 500, true),
new NetworkAnimator()), () -> new GameObject("Door", new Door(
new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")),
new Renderer(), new Animator(), new NetworkAnimator()));
PrefabManager.addPrefab("laser_door", () -> new GameObject("Laser Door", new LaserDoor(
new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")),
new Renderer(), new Animator(), new Collider(100, 500, true),
new NetworkAnimator()), () -> new GameObject("Laser Door", new LaserDoor(
new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")),
new Renderer(), new Animator(), new NetworkAnimator()));
}
private void registerLockerPrefabs() {
PrefabManager.addPrefab("locker_locked",
() -> new GameObject("Locker", true, new Renderer(), new Locker(true,
new TextureAtlas("images/environment/atlas.png",
"images/environment/atlas.txt"))));
PrefabManager.addPrefab("locker_unlocked",
() -> new GameObject("Locker", true, new Renderer(), new Locker(false,
new TextureAtlas("images/environment/atlas.png",
"images/environment/atlas.txt")), new Collider(100, 200, true),
new Animator(), new NetworkAnimator()),
() -> new GameObject("Locker", true, new Renderer(), new Locker(false,
new TextureAtlas("images/environment/atlas.png",
"images/environment/atlas.txt")), new Animator(),
new NetworkAnimator()));
}
private void registerEnemyPrefabs() {
PrefabManager.addPrefab("dera_crewman",
() -> new GameObject("Dera Crewman", new Renderer(), new Animator(),
new Collider(200, 200), new Rigidbody(), new DeraCrewman(),
new NetworkTransform(), new NetworkRenderer(), new NetworkAnimator()),
() -> new GameObject("Dera Crewman", new Renderer(), new Animator(),
new Collider(200, 200), new NetworkTransform(), new NetworkRenderer(),
new NetworkAnimator()));
PrefabManager.addPrefab("prova_crewman",
() -> new GameObject("Prova Crewman", new Renderer(), new Animator(),
new Collider(200, 200), new Rigidbody(), new ProvaCrewman(),
new NetworkTransform(), new NetworkRenderer(), new NetworkAnimator()),
() -> new GameObject("Prova Crewman", new Renderer(), new Animator(),
new Collider(200, 200), new NetworkTransform(), new NetworkRenderer(),
new NetworkAnimator()));
PrefabManager.addPrefab("supra_crewman",
() -> new GameObject("Supra Crewman", new Renderer(), new Animator(),
new Collider(200, 200), new Rigidbody(), new SupraCrewman(),
new NetworkTransform(), new NetworkRenderer(), new NetworkAnimator()),
() -> new GameObject("Supra Crewman", new Renderer(), new Animator(),
new Collider(200, 200), new NetworkTransform(), new NetworkRenderer(),
new NetworkAnimator()));
}
}
|
package com.fishercoder.solutions;
/**
* 64. Minimum Path Sum
*
* Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
*
* Note: You can only move either down or right at any point in time.
*/
public class _64 {
public static class Solution1 {
/**
* Same idea as _70: have to initialize the first row and the first column and start the for
* loop from i==1 and j==1 for the rest of the matrix.
*/
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int height = grid.length;
int width = grid[0].length;
int[][] dp = new int[height][width];
dp[0][0] = grid[0][0];
for (int i = 1; i < height; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
for (int j = 1; j < width; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
for (int i = 1; i < height; i++) {
for (int j = 1; j < width; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[height - 1][width - 1];
}
}
}
|
package com.jarvis.cache;
import com.jarvis.cache.annotation.Cache;
import com.jarvis.cache.annotation.Magic;
import com.jarvis.cache.aop.CacheAopProxyChain;
import com.jarvis.cache.to.CacheKeyTO;
import com.jarvis.cache.to.CacheWrapper;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
/**
* MagicHandler
*
* @author jiayu.qiu
*/
@Slf4j
public class MagicHandler {
private final CacheHandler cacheHandler;
private final CacheAopProxyChain pjp;
private final Cache cache;
private final Magic magic;
private final Object[] arguments;
private final int iterableArgIndex;
private final Object[] iterableArrayArg;
private final Collection<Object> iterableCollectionArg;
private final Method method;
private final Class<?> returnType;
private CacheKeyTO[] cacheKeys;
private final Class<?>[] parameterTypes;
private final Object target;
private final String methodName;
public MagicHandler(CacheHandler cacheHandler, CacheAopProxyChain pjp, Cache cache) {
this.cacheHandler = cacheHandler;
this.pjp = pjp;
this.cache = cache;
this.magic = cache.magic();
this.arguments = pjp.getArgs();
this.iterableArgIndex = magic.iterableArgIndex();
if (iterableArgIndex >= 0 && iterableArgIndex < arguments.length) {
Object tmpArg = arguments[iterableArgIndex];
if (tmpArg instanceof Collection) {
this.iterableCollectionArg = (Collection<Object>) tmpArg;
this.iterableArrayArg = null;
} else if (tmpArg.getClass().isArray()) {
this.iterableArrayArg = (Object[]) tmpArg;
this.iterableCollectionArg = null;
} else {
this.iterableArrayArg = null;
this.iterableCollectionArg = null;
}
} else {
this.iterableArrayArg = null;
this.iterableCollectionArg = null;
}
this.method = pjp.getMethod();
this.returnType = method.getReturnType();
this.parameterTypes = method.getParameterTypes();
this.target = pjp.getTarget();
this.methodName = pjp.getMethod().getName();
}
public static boolean isMagic(Cache cache, Method method) throws Exception {
Class<?>[] parameterTypes = method.getParameterTypes();
Magic magic = cache.magic();
int iterableArgIndex = magic.iterableArgIndex();
String key = magic.key();
boolean rv = null != key && key.length() > 0;
if (rv) {
if (parameterTypes.length > 0) {
if (iterableArgIndex < 0) {
throw new Exception("iterableArgIndex0");
}
if (iterableArgIndex >= parameterTypes.length) {
throw new Exception("iterableArgIndex" + parameterTypes.length);
}
Class<?> tmp = parameterTypes[iterableArgIndex];
// List\Set\\
if (tmp.isArray() || Collection.class.isAssignableFrom(tmp)) {
//rv = true;
} else {
throw new Exception("magic" + iterableArgIndex + "Collection");
}
}
Class<?> returnType = method.getReturnType();
if (returnType.isArray() || Collection.class.isAssignableFrom(returnType)) {
// rv = true;
} else {
throw new Exception("magicCollection");
}
}
return rv;
}
private Collection<Object> newCollection(Class<?> collectionType, int resSize) throws Exception {
Collection<Object> res;
if (LinkedList.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptyList();
}
res = new LinkedList<>();
} else if (List.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptyList();
}
res = new ArrayList<>(resSize);
} else if (LinkedHashSet.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptySet();
}
res = new LinkedHashSet<>(resSize);
} else if (Set.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptySet();
}
res = new HashSet<>(resSize);
} else {
throw new Exception("Unsupported type:" + collectionType.getName());
}
return res;
}
private Type getRealReturnType() {
if (returnType.isArray()) {
return returnType.getComponentType();
} else {
return ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
}
}
public Object magic() throws Throwable {
if (parameterTypes.length == 0) {
Object newValue = this.cacheHandler.getData(pjp, null);
writeMagicCache(newValue);
return newValue;
}
Map<CacheKeyTO, Object> keyArgMap = getCacheKeyForMagic();
if (null == keyArgMap || keyArgMap.isEmpty()) {
if (returnType.isArray()) {
return Array.newInstance(returnType.getComponentType(), 0);
}
return newCollection(returnType, 0);
}
Type returnItemType = getRealReturnType();
Map<CacheKeyTO, CacheWrapper<Object>> cacheValues = this.cacheHandler.mget(method, returnItemType, keyArgMap.keySet());
// key
int argSize = keyArgMap.size() - cacheValues.size();
if (argSize <= 0) {
return convertToReturnObject(cacheValues, null, Collections.emptyMap());
}
Object[] args = getUnmatchArg(keyArgMap, cacheValues, argSize);
Object newValue = this.cacheHandler.getData(pjp, args);
args[iterableArgIndex] = null;
Map<CacheKeyTO, MSetParam> unmatchCache = writeMagicCache(newValue, args, cacheValues, keyArgMap);
return convertToReturnObject(cacheValues, newValue, unmatchCache);
}
/**
*
*
* @param keyArgMap
* @param cacheValues
* @param argSize
* @return
* @throws Exception
*/
private Object[] getUnmatchArg(Map<CacheKeyTO, Object> keyArgMap, Map<CacheKeyTO, CacheWrapper<Object>> cacheValues, int argSize) throws Exception {
Iterator<Map.Entry<CacheKeyTO, Object>> keyArgMapIt = keyArgMap.entrySet().iterator();
Object unmatchArg;
if (null != iterableCollectionArg) {
Collection<Object> argList = newCollection(iterableCollectionArg.getClass(), argSize);
while (keyArgMapIt.hasNext()) {
Map.Entry<CacheKeyTO, Object> item = keyArgMapIt.next();
if (!cacheValues.containsKey(item.getKey())) {
argList.add(item.getValue());
}
}
unmatchArg = argList;
} else {
Object arg = iterableArrayArg[0];
Object[] args = (Object[]) Array.newInstance(arg.getClass(), argSize);
int i = 0;
while (keyArgMapIt.hasNext()) {
Map.Entry<CacheKeyTO, Object> item = keyArgMapIt.next();
if (!cacheValues.containsKey(item.getKey())) {
args[i] = item.getValue();
i++;
}
}
unmatchArg = args;
}
Object[] args = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (i == iterableArgIndex) {
args[i] = unmatchArg;
} else {
args[i] = arguments[i];
}
}
return args;
}
/**
*
*
* @param newValue
* @return
* @throws Exception
*/
private Map<CacheKeyTO, MSetParam> writeMagicCache(Object newValue) throws Exception {
if (null == newValue) {
return Collections.emptyMap();
}
Map<CacheKeyTO, MSetParam> unmatchCache;
Object[] args = null;
if (newValue.getClass().isArray()) {
Object[] newValues = (Object[]) newValue;
unmatchCache = new HashMap<>(newValues.length);
for (Object value : newValues) {
MSetParam mSetParam = genCacheWrapper(value, args);
unmatchCache.put(mSetParam.getCacheKey(), mSetParam);
}
} else if (newValue instanceof Collection) {
Collection<Object> newValues = (Collection<Object>) newValue;
unmatchCache = new HashMap<>(newValues.size());
for (Object value : newValues) {
MSetParam mSetParam = genCacheWrapper(value, args);
unmatchCache.put(mSetParam.getCacheKey(), mSetParam);
}
} else {
throw new Exception("MagicCollection");
}
if (null != unmatchCache && unmatchCache.size() > 0) {
this.cacheHandler.mset(pjp.getMethod(), unmatchCache.values());
}
return unmatchCache;
}
/**
*
*
* @param newValue
* @param args
* @param cacheValues
* @param keyArgMap Key
* @return
* @throws Exception
*/
private Map<CacheKeyTO, MSetParam> writeMagicCache(Object newValue, Object[] args, Map<CacheKeyTO, CacheWrapper<Object>> cacheValues, Map<CacheKeyTO, Object> keyArgMap) throws Exception {
int cachedSize = null == cacheValues ? 0 : cacheValues.size();
int unmatchSize = keyArgMap.size() - cachedSize;
Map<CacheKeyTO, MSetParam> unmatchCache = new HashMap<>(unmatchSize);
if (null != newValue) {
if (newValue.getClass().isArray()) {
Object[] newValues = (Object[]) newValue;
for (Object value : newValues) {
MSetParam mSetParam = genCacheWrapper(value, args);
unmatchCache.put(mSetParam.getCacheKey(), mSetParam);
}
} else if (newValue instanceof Collection) {
Collection<Object> newValues = (Collection<Object>) newValue;
for (Object value : newValues) {
MSetParam mSetParam = genCacheWrapper(value, args);
unmatchCache.put(mSetParam.getCacheKey(), mSetParam);
}
} else {
throw new Exception("MagicCollection");
}
}
if (unmatchCache.size() < unmatchSize) {
Set<CacheKeyTO> cacheKeySet = keyArgMap.keySet();
// Keynull
for (CacheKeyTO cacheKeyTO : cacheKeySet) {
if (unmatchCache.containsKey(cacheKeyTO)) {
continue;
}
if (null != cacheValues && cacheValues.containsKey(cacheKeyTO)) {
continue;
}
MSetParam mSetParam = genCacheWrapper(cacheKeyTO, null, args);
unmatchCache.put(mSetParam.getCacheKey(), mSetParam);
}
}
if (null != unmatchCache && unmatchCache.size() > 0) {
this.cacheHandler.mset(pjp.getMethod(), unmatchCache.values());
}
return unmatchCache;
}
private MSetParam genCacheWrapper(Object value, Object[] args) throws Exception {
String keyExpression = magic.key();
String hfieldExpression = magic.hfield();
CacheKeyTO cacheKeyTO = this.cacheHandler.getCacheKey(target, methodName, args, keyExpression, hfieldExpression, value, true);
int expire = this.cacheHandler.getScriptParser().getRealExpire(cache.expire(), cache.expireExpression(), args, value);
return new MSetParam(cacheKeyTO, new CacheWrapper<>(value, expire));
}
private MSetParam genCacheWrapper(CacheKeyTO cacheKeyTO, Object value, Object[] args) throws Exception {
int expire = this.cacheHandler.getScriptParser().getRealExpire(cache.expire(), cache.expireExpression(), args, value);
return new MSetParam(cacheKeyTO, new CacheWrapper<>(value, expire));
}
/**
*
*
* @param cacheValues
* @param newValue
* @param unmatchCache
* @return
* @throws Throwable
*/
private Object convertToReturnObject(Map<CacheKeyTO, CacheWrapper<Object>> cacheValues, Object newValue, Map<CacheKeyTO, MSetParam> unmatchCache) throws Throwable {
if (returnType.isArray()) {
int resSize;
if (magic.returnNullValue()) {
resSize = cacheKeys.length;
} else {
Object[] newValues = (Object[]) newValue;
resSize = cacheValues.size() + (null == newValues ? 0 : newValues.length);
}
Object res = Array.newInstance(returnType.getComponentType(), resSize);
int ind = 0;
for (CacheKeyTO cacheKeyTO : cacheKeys) {
Object val = getValueFormCacheOrDatasource(cacheKeyTO, cacheValues, unmatchCache);
if (!magic.returnNullValue() && null == val) {
continue;
}
Array.set(res, ind, val);
ind++;
}
return res;
} else {
int resSize;
if (magic.returnNullValue()) {
resSize = cacheKeys.length;
} else {
Collection<Object> newValues = (Collection<Object>) newValue;
resSize = cacheValues.size() + (null == newValues ? 0 : newValues.size());
}
Collection<Object> res = newCollection(returnType, resSize);
for (CacheKeyTO cacheKeyTO : cacheKeys) {
Object val = getValueFormCacheOrDatasource(cacheKeyTO, cacheValues, unmatchCache);
if (!magic.returnNullValue() && null == val) {
continue;
}
res.add(val);
}
return res;
}
}
private Object getValueFormCacheOrDatasource(CacheKeyTO cacheKeyTO, Map<CacheKeyTO, CacheWrapper<Object>> cacheValues, Map<CacheKeyTO, MSetParam> unmatchCache) {
boolean isCache = false;
CacheWrapper<Object> cacheWrapper = cacheValues.get(cacheKeyTO);
if (null == cacheWrapper) {
MSetParam mSetParam = unmatchCache.get(cacheKeyTO);
if (null != mSetParam) {
cacheWrapper = mSetParam.getResult();
}
} else {
isCache = true;
}
Object val = null;
if (null != cacheWrapper) {
val = cacheWrapper.getCacheObject();
}
if (log.isDebugEnabled()) {
String from = isCache ? "cache" : "datasource";
String message = "the data for key:" + cacheKeyTO + " is from " + from;
if (null != val) {
message += ", value is not null";
} else {
message += ", value is null";
}
if (null != cacheWrapper) {
message += ", expire :" + cacheWrapper.getExpire();
}
log.debug(message);
}
return val;
}
/**
* Key
*
* @return
*/
private Map<CacheKeyTO, Object> getCacheKeyForMagic() {
Map<CacheKeyTO, Object> keyArgMap = null;
if (null != iterableCollectionArg) {
cacheKeys = new CacheKeyTO[iterableCollectionArg.size()];
keyArgMap = new HashMap<>(iterableCollectionArg.size());
int ind = 0;
for (Object arg : iterableCollectionArg) {
CacheKeyTO cacheKeyTO = buildCacheKey(arg);
keyArgMap.put(cacheKeyTO, arg);
cacheKeys[ind] = cacheKeyTO;
ind++;
}
} else if (null != iterableArrayArg) {
cacheKeys = new CacheKeyTO[iterableArrayArg.length];
keyArgMap = new HashMap<>(iterableArrayArg.length);
for (int ind = 0; ind < iterableArrayArg.length; ind++) {
Object arg = iterableArrayArg[ind];
CacheKeyTO cacheKeyTO = buildCacheKey(arg);
keyArgMap.put(cacheKeyTO, arg);
cacheKeys[ind] = cacheKeyTO;
}
}
return keyArgMap;
}
private CacheKeyTO buildCacheKey(Object arg) {
Object[] tmpArgs = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (i == iterableArgIndex) {
tmpArgs[i] = arg;
} else {
tmpArgs[i] = arguments[i];
}
}
String keyExpression = cache.key();
String hfieldExpression = cache.hfield();
return this.cacheHandler.getCacheKey(target, methodName, tmpArgs, keyExpression, hfieldExpression, null, false);
}
}
|
package com.jcabi.aspects.aj;
import com.jcabi.aspects.RetryOnFailure;
import com.jcabi.log.Logger;
import java.util.concurrent.TimeUnit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
/**
* Repeat execution in case of exception.
*
* @author Yegor Bugayenko (yegor@jcabi.com)
* @version $Id$
* @since 0.1.10
* @see com.jcabi.aspects.RetryOnFailure
*/
@Aspect
public final class Repeater {
@Around("execution(* * (..)) && @annotation(com.jcabi.aspects.RetryOnFailure)")
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public Object wrap(final ProceedingJoinPoint point) throws Throwable {
final RetryOnFailure rof = MethodSignature.class
.cast(point.getSignature())
.getMethod()
.getAnnotation(RetryOnFailure.class);
int attempt = 0;
while (true) {
try {
return point.proceed();
} catch (InterruptedException ex) {
throw ex;
} catch (Throwable ex) {
++attempt;
Logger.warn(
this,
"attempt #%d of %d failed: %[exception]s",
attempt,
rof.attempts(),
ex
);
if (attempt > rof.attempts()) {
throw ex;
}
TimeUnit.MILLISECONDS.sleep(rof.delay() * attempt);
}
}
}
}
|
package com.nerodesk.takes.doc;
import com.nerodesk.om.Base;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.rq.RqHref;
import org.takes.rs.RsWithBody;
import org.takes.rs.RsWithHeader;
/**
* Read file content.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 0.2
*/
final class TkRead implements Take {
/**
* Base.
*/
private final transient Base base;
/**
* Ctor.
* @param bse Base
*/
TkRead(final Base bse) {
this.base = bse;
}
@Override
public Response act(final Request req) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
new RqDoc(req, this.base).doc().read(baos);
return new RsWithHeader(
new RsWithBody(new ByteArrayInputStream(baos.toByteArray())),
"Content-Disposition",
String.format(
"attachment; filename=\"%s\"",
new RqHref.Smart(new RqHref.Base(req)).single("file")
)
);
}
}
|
package tlc2.tool;
import tlc2.util.IdThread;
import tlc2.util.ObjLongTable;
import tlc2.value.Value;
import util.ToolIO;
public class Worker extends IdThread implements IWorker {
/**
* Multi-threading helps only when running on multiprocessors. TLC
* can pretty much eat up all the cycles of a processor running
* single threaded. We expect to get linear speedup with respect
* to the number of processors.
*/
private ModelChecker tlc;
private StateQueue squeue;
private ObjLongTable astCounts;
private Value[] localValues;
// SZ Feb 20, 2009: changed due to super type introduction
public Worker(int id, AbstractChecker tlc) {
super(id);
this.tlc = (ModelChecker) tlc;
this.squeue = this.tlc.theStateQueue;
this.astCounts = new ObjLongTable(10);
this.localValues = new Value[4];
}
public final ObjLongTable getCounts() { return this.astCounts; }
public Value getLocalValue(int idx) {
if (idx < this.localValues.length) {
return this.localValues[idx];
}
return null;
}
public void setLocalValue(int idx, Value val) {
if (idx >= this.localValues.length) {
Value[] vals = new Value[idx+1];
System.arraycopy(this.localValues, 0, vals, 0, this.localValues.length);
this.localValues = vals;
}
this.localValues[idx] = val;
}
/**
* This method gets a state from the queue, generates all the
* possible next states of the state, checks the invariants, and
* updates the state set and state queue.
*/
public final void run() {
TLCState curState = null;
try {
while (true) {
curState = (TLCState)this.squeue.sDequeue();
if (curState == null) {
synchronized(this.tlc) {
this.tlc.setDone();
this.tlc.notify();
}
this.squeue.finishAll();
return;
}
if (this.tlc.doNext(curState, this.astCounts)) return;
}
}
catch (Throwable e) {
// Something bad happened. Quit ...
// Assert.printStack(e);
synchronized(this.tlc) {
if (this.tlc.setErrState(curState, null, true)) {
ToolIO.err.println("Error: " + e.getMessage());
}
this.squeue.finishAll();
this.tlc.notify();
}
return;
}
}
}
|
package processing.app;
import org.junit.Test;
import java.io.*;
import java.util.*;
import static org.junit.Assert.assertTrue;
public class I18NTest {
private Set<String> loadAllI18NKeys() throws IOException {
Properties properties = new Properties();
for (File file : listPropertiesFiles()) {
properties.putAll(loadProperties(file));
}
Set<String> keys = new HashSet<String>();
for (Object key : properties.keySet()) {
keys.add(key.toString());
}
return keys;
}
private File[] listPropertiesFiles() {
return new File(I18NTest.class.getResource(".").getFile()).listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".properties");
}
});
}
private Properties loadProperties(File file) throws IOException {
Properties properties = new Properties();
InputStream is = null;
try {
is = new FileInputStream(file);
properties.load(is);
} finally {
if (is != null) {
is.close();
}
}
return properties;
}
@Test
public void ensureEveryTranslationIsComplete() throws Exception {
Set<String> keys = loadAllI18NKeys();
Map<String, List<String>> missingTranslationsPerFile = new HashMap<String, List<String>>();
for (File file : listPropertiesFiles()) {
Properties properties = loadProperties(file);
for (String key : keys) {
if (!properties.containsKey(key) || properties.get(key).equals("")) {
addMissingTranslation(missingTranslationsPerFile, file, key);
}
}
}
if (!missingTranslationsPerFile.isEmpty()) {
for (Map.Entry<String, List<String>> entry : missingTranslationsPerFile.entrySet()) {
System.out.println("Following translations in file " + entry.getKey() + " are missing:");
for (String key : entry.getValue()) {
System.out.println("==> '" + key.replaceAll("\n", "\\\\n").replaceAll(" ", "\\\\ ") + "'");
}
System.out.println();
}
assertTrue(false);
}
}
private void addMissingTranslation(Map<String, List<String>> missingTranslationsPerFile, File file, String key) {
if (!missingTranslationsPerFile.containsKey(file.getName())) {
missingTranslationsPerFile.put(file.getName(), new LinkedList<String>());
}
missingTranslationsPerFile.get(file.getName()).add(key);
}
}
|
package io.spine.util;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.Message;
import io.spine.protobuf.Messages;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.spine.protobuf.Messages.isNotDefault;
import static io.spine.util.Exceptions.newIllegalArgumentException;
/**
* Utilities for checking preconditions.
*/
public final class Preconditions2 {
/** Prevents instantiation of this utility class. */
private Preconditions2() {
}
@CanIgnoreReturnValue
public static String checkNotEmptyOrBlank(String str) {
return checkNotEmptyOrBlank(
str, "Non-empty and non-blank string expected. Encountered: \"%s\".", str
);
}
@CanIgnoreReturnValue
public static String checkNotEmptyOrBlank(String str,
@Nullable String errorMessageTemplate,
@Nullable Object @Nullable ... errorMessageArgs) {
checkNotNull(str, errorMessageTemplate);
checkArgument(!str.trim().isEmpty(), errorMessageTemplate, errorMessageArgs);
return str;
}
public static long checkPositive(long value) {
if (value <= 0) {
throw newIllegalArgumentException("A positive value expected. Encountered: %d.", value);
}
return value;
}
public static long checkPositive(long value,
@Nullable String errorMessageTemplate,
@Nullable Object @Nullable ... errorMessageArgs) {
checkArgument(value > 0L, errorMessageTemplate, errorMessageArgs);
return value;
}
@CanIgnoreReturnValue
public static <T extends @NonNull Message> T checkNotDefaultArg(T message) {
checkArgument(!Messages.isDefault(message));
return message;
}
@CanIgnoreReturnValue
public static <T extends @NonNull Message> T checkNotDefaultState(T message) {
checkState(!Messages.isDefault(message));
return message;
}
@CanIgnoreReturnValue
public static <M extends Message>
M checkNotDefaultArg(M object, @Nullable Object errorMessage) {
checkNotNull(object);
checkArgument(isNotDefault(object), errorMessage);
return object;
}
@CanIgnoreReturnValue
public static <M extends Message>
M checkNotDefaultState(M object, @Nullable Object errorMessage) {
checkNotNull(object);
checkState(isNotDefault(object), errorMessage);
return object;
}
@CanIgnoreReturnValue
@SuppressWarnings("OverloadedVarargsMethod")
public static <M extends Message>
M checkNotDefaultArg(M object,
@Nullable String errorMessageTemplate,
@Nullable Object @Nullable ... errorMessageArgs) {
checkNotNull(object);
checkArgument(isNotDefault(object), errorMessageTemplate, errorMessageArgs);
return object;
}
@CanIgnoreReturnValue
@SuppressWarnings("OverloadedVarargsMethod")
public static <M extends Message>
M checkNotDefaultState(M object,
@Nullable String errorMessageTemplate,
@Nullable Object @Nullable ... errorMessageArgs) {
checkNotNull(object);
checkState(isNotDefault(object), errorMessageTemplate, errorMessageArgs);
return object;
}
/**
* Ensures that the passed value is within the specified range.
*
* <p>Both ends of the range are inclusive.
*
* @param value
* the value to check
* @param paramName
* the name of the parameter which is included into the error messages
* if the check fails
* @param lowBound
* the lower bound to check
* @param highBound
* the higher bound
*/
public static void checkBounds(int value, String paramName, int lowBound, int highBound) {
checkNotNull(paramName);
if (!isBetween(value, lowBound, highBound)) {
throw newIllegalArgumentException(
"`%s` (value: %d) must be in bounds [%d, %d] inclusive.",
paramName, value, lowBound, highBound);
}
}
private static boolean isBetween(int value, int lowBound, int highBound) {
return lowBound <= value && value <= highBound;
}
}
|
package commands;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import utils.Constants;
import utils.DiscordID;
import utils.Emoji;
import java.awt.*;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class GuildCommandListener extends ListenerAdapter {
private final Map<String, GuildAction> commands;
private final Random rand;
public GuildCommandListener() {
commands = new HashMap<>();
rand = new Random();
addCommands();
}
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String command = event.getMessage().getContentRaw().split(" ", 2)[0].toLowerCase();
if (commands.containsKey(command))
commands.get(command).run(event);
}
private void addCommands() {
addPollCommand();
addPingCommand();
addRollCommand();
addPoopCommand();
}
private GuildAction addPollCommand() {
GuildAction action = new GuildAction() {
public String getCommand() {
return "poll";
}
public void run(GuildMessageReceivedEvent event) {
String invalidMessage = "Invalid Poll Format. Please use the format `"
+ Constants.PREFIX
+ "poll yourquestion | option1 | option2 | option3 ...`";
String[] command = event.getMessage().getContentRaw().split(" ", 2);
if (command.length < 2) {
event.getChannel().sendMessage(invalidMessage).queue();
return;
}
String[] params = command[1].split("\\|");
if (params.length < 3) {
event.getChannel().sendMessage(invalidMessage).queue();
return;
} else if (params.length > 10) {
event.getChannel().sendMessage("You can only have up to 9 different answers in a poll.").queue();
return;
}
event.getMessage().delete().queue();
EmbedBuilder msg = new EmbedBuilder();
msg.setAuthor(event.getAuthor().getName() + " created a poll!", null, event.getAuthor().getEffectiveAvatarUrl());
msg.setTitle(params[0], null);
msg.setColor(Color.MAGENTA);
StringBuilder answers = new StringBuilder();
for (int i = 1; i < params.length; i++) {
answers.append(Emoji.NUMBER[i]);
answers.append(' ');
answers.append(params[i].trim());
answers.append('\n');
}
msg.setDescription(answers.toString());
Message poll = event.getChannel().sendMessage(msg.build()).complete();
for (int i = 1; i < params.length; i++) {
poll.addReaction(Emoji.NUMBER[i]).complete();
}
}
};
commands.put(Constants.PREFIX + action.getCommand(), action);
return action;
}
private GuildAction addPingCommand() {
GuildAction action = new GuildAction() {
public String getCommand() {
return "pingg";
}
public void run(GuildMessageReceivedEvent event) {
event.getChannel().sendMessage("Ping: ...").queue(m -> {
long ping = event.getMessage().getTimeCreated().until(m.getTimeCreated(), ChronoUnit.MILLIS);
m.editMessage("Ping: " + ping + "ms | Websocket: " + event.getJDA().getGatewayPing() + "ms").queue();
});
}
};
commands.put(Constants.PREFIX + action.getCommand(), action);
return action;
}
private GuildAction addRollCommand() {
GuildAction action = new GuildAction() {
public String getCommand() {
return "roll";
}
public void run(GuildMessageReceivedEvent event) {
String[] command = event.getMessage().getContentRaw().split(" ", 2);
int max = 100;
if (command.length > 1) {
try {
max = Integer.parseInt(command[1]) + 1;
} catch (NumberFormatException ex) {
event.getChannel().sendMessage("Invalid format. Use `!roll [max]`. Example: `!roll 1000`").queue();
return;
}
}
event.getChannel().sendMessage("You rolled a " + rand.nextInt(max) + "!").queue();
}
};
commands.put(Constants.PREFIX + action.getCommand(), action);
return action;
}
private GuildAction addPoopCommand() {
GuildAction action = new GuildAction() {
public String getCommand() {
return "poop";
}
public void run(GuildMessageReceivedEvent event) {
if (event.getAuthor().getId().equals(DiscordID.KAGA))
event.getChannel().sendMessage("no").queue();
}
};
commands.put(Constants.PREFIX + action.getCommand(), action);
return action;
}
}
|
package de.gymnew.sudoku.model;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Sudoku {
private Field[][] fields;
private Row[] rows;
private Column[] columns;
private Block[][] blocks;
public Sudoku() {
fields = new Field[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
fields[i][j] = new Field();
}
}
columns = new Column[9];
for (int i = 0; i < 9; i++) {
columns[i] = new Column(i, this);
}
rows = new Row[9];
for (int i = 0; i < 9; i++) {
rows[i] = new Row(i, this);
}
blocks = new Block[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int r, s;
r = i * 3;
s = j * 3;
blocks[i][j] = new Block(r, s, this);
}
}
}
public Field getField(int column, int row) {
return fields[column][row];
}
@Override
public Sudoku clone() {
Sudoku sudoku = new Sudoku();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
Field src = fields[i][j];
Field dst = sudoku.getField(i, j);
dst.setValue(src.getValue());
dst.addNotes(src.getNotes());
}
}
return null;
}
@Override
public String toString() {
String s = "";
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
s += fields[i][j].getValue();
}
s += "|";
}
return s;
}
private void load(String string) throws IOException {
// TODO check sudoku
for (int i = 0; i < 9; i++) {
int r = i * 9;
for (int j = 0; j < 9; j++) {
try {
byte value = Byte.parseByte(String.valueOf(string.charAt(j + r)));
fields[i][j].setValue(value);
} catch (NumberFormatException e) {
throw new IOException("No Number");
}
}
if (String.valueOf(string.charAt(r + 9)).equals("|") == false) {
throw new IOException("False Sign");
}
}
}
public static Sudoku load(File file) throws IOException {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
Sudoku s = new Sudoku();
s.load(br.readLine());
br.close();
fr.close();
return s;
}
}
|
package edu.jhu.prim.util.random;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import edu.jhu.prim.util.random.UnlockedXORShiftRNG.DeterministicSeedGenerator;
/**
* A "no-dependencies" version of Prng.
* @author mgormley
*/
public class Prng {
public enum PrngSetting {
REPLICABLE_THREADSAFE,
REPLICABLE_NOT_THREADSAFE,
NOT_REPLICABLE_THREADSAFE,
}
public static final long DEFAULT_SEED;
private static Random curRandom;
private static long seed;
private static boolean useThreadLocalRandom;
static {
DEFAULT_SEED = 123456789101112l;
System.out.println("WARNING: pseudo random number generator is not thread safe");
init(DEFAULT_SEED, PrngSetting.REPLICABLE_THREADSAFE);
}
private Prng() {
// private constructor.
}
public static void seed(long seed) {
Prng.seed = seed;
curRandom.setSeed(seed);
}
public static void init(long seed, PrngSetting setting) {
System.out.println("SEED="+seed);
Prng.seed = seed;
Prng.useThreadLocalRandom = false;
if (setting == PrngSetting.REPLICABLE_THREADSAFE) {
curRandom = new Random(seed);
} else if (setting == PrngSetting.REPLICABLE_NOT_THREADSAFE) {
curRandom = new UnlockedXORShiftRNG(new DeterministicSeedGenerator(seed));
} else if (setting == PrngSetting.NOT_REPLICABLE_THREADSAFE) {
curRandom = null;
Prng.useThreadLocalRandom = true;
} else {
throw new RuntimeException("Unsupported setting: " + setting);
}
}
public static double nextDouble() {
if (useThreadLocalRandom) {
return ThreadLocalRandom.current().nextDouble();
} else {
return curRandom.nextDouble();
}
}
public static float nextFloat() {
if (useThreadLocalRandom) {
return ThreadLocalRandom.current().nextFloat();
} else {
return curRandom.nextFloat();
}
}
public static boolean nextBoolean() {
if (useThreadLocalRandom) {
return ThreadLocalRandom.current().nextBoolean();
} else {
return curRandom.nextBoolean();
}
}
public static short nextShort() {
if (useThreadLocalRandom) {
return (short) ThreadLocalRandom.current().nextInt();
} else {
return (short) curRandom.nextInt();
}
}
public static int nextInt() {
if (useThreadLocalRandom) {
return ThreadLocalRandom.current().nextInt();
} else {
return curRandom.nextInt();
}
}
public static int nextInt(int n) {
if (useThreadLocalRandom) {
return ThreadLocalRandom.current().nextInt(n);
} else {
return curRandom.nextInt(n);
}
}
public static long nextLong() {
if (useThreadLocalRandom) {
return ThreadLocalRandom.current().nextLong();
} else {
return curRandom.nextLong();
}
}
public static long getSeed() {
return seed;
}
public static void setRandom(Random curRandom) {
Prng.curRandom = curRandom;
}
public static Random getRandom() {
return curRandom;
}
}
|
package edu.mines.jtk.sgl;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import edu.mines.jtk.awt.*;
import edu.mines.jtk.dsp.Sampling;
/**
* A simple frame for 3D graphics.
* @author Chris Engelsma and Dave Hale, Colorado School of Mines.
* @version 2010.12.09
*/
public class SimpleFrame extends JFrame {
/**
* Constructs a simple frame with default parameters.
* Axes orientation defaults to x-right, y-out and z-down.
*/
public SimpleFrame() {
this(null,null);
}
/**
* Constructs a simple frame with specified axes orientation.
* @param ao the axes orientation.
*/
public SimpleFrame(AxesOrientation ao) {
this(null,ao);
}
/**
* Constructs a simple frame with the specified world.
* @param world the world view.
*/
public SimpleFrame(World world) {
this(world,null);
}
/**
* Constructs a simple frame with the specified world and orientation.
* @param world the world view.
* @param ao the axes orientation.
*/
public SimpleFrame(World world, AxesOrientation ao) {
if (world==null) world = new World();
if (ao==null) ao = AxesOrientation.XRIGHT_YOUT_ZDOWN;
_world = world;
_view = new OrbitView(_world);
_view.setAxesOrientation(ao);
_canvas = new ViewCanvas();
_canvas.setView(_view);
_modeManager = new ModeManager();
_modeManager.add(_canvas);
OrbitViewMode ovm = new OrbitViewMode(_modeManager);
SelectDragMode sdm = new SelectDragMode(_modeManager);
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
Action exitAction = new AbstractAction("Exit") {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
};
JMenuItem exitItem = fileMenu.add(exitAction);
exitItem.setMnemonic('X');
JMenu modeMenu = new JMenu("Mode");
modeMenu.setMnemonic('M');
JMenuItem ovmItem = new JMenuItem(ovm);
modeMenu.add(ovmItem);
JMenuItem sdmItem = new JMenuItem(sdm);
modeMenu.add(sdmItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(modeMenu);
_toolBar = new JToolBar(SwingConstants.VERTICAL);
_toolBar.setRollover(true);
JToggleButton ovmButton = new ModeToggleButton(ovm);
_toolBar.add(ovmButton);
JToggleButton sdmButton = new ModeToggleButton(sdm);
_toolBar.add(sdmButton);
ovm.setActive(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(new Dimension(SIZE,SIZE));
this.add(_canvas,BorderLayout.CENTER);
this.add(_toolBar,BorderLayout.WEST);
this.setJMenuBar(menuBar);
this.setVisible(true);
}
/**
* Gets the mode manager for this simple frame.
* @return the mode manager.
*/
public ModeManager getModeManager() {
return _modeManager;
}
/**
* Gets the JToolBar for this simple frame.
* @return the JToolBar.
*/
public JToolBar getJToolBar() {
return _toolBar;
}
/**
* Returns a new simple frame with a triangle group.
* Triangles will be constructed as vertex normals.
* @param xyz array of packed vertex coordinates.
* @return a simple frame.
*/
public static SimpleFrame asTriangles(float[] xyz) {
return asTriangles(true,xyz);
}
/**
* Returns a new simple frame with a triangle group.
* @param vn true, for vertex normals; false, for triangle normals.
* @param xyz array of packed vertex coordinates.
* @return the simple frame.
*/
public static SimpleFrame asTriangles(boolean vn, float[] xyz) {
return asTriangles(vn,xyz,null);
}
/**
* Returns a new simple frame with a triangle group.
* Triangles will be constructed as vertex normals.
* @param xyz array of packed vertex coordinates.
* @param rgb array of packed color coordinates.
* @return the simple frame.
*/
public static SimpleFrame asTriangles(float[] xyz, float[] rgb) {
return asTriangles(true,xyz,rgb);
}
/**
* Returns a new simple frame with a triangle group.
* @param vn true, for vertex normals; false, for triangle normals.
* @param sx sampling of x coordinates; may be non-uniform.
* @param sy sampling of y coordinates; may be non-uniform.
* @param z array[nx][ny] of z coordinates z = f(x,y).
*/
public static SimpleFrame asTriangles(
boolean vn, Sampling sx, Sampling sy, float[][] z)
{
return asTriangles(new TriangleGroup(vn,sx,sy,z));
}
/**
* Returns a new simple frame with a triangle group.
* @param vn true, for vertex normals; false, for triangle normals.
* @param sx sampling of x coordinates; may be non-uniform.
* @param sy sampling of y coordinates; may be non-uniform.
* @param z array[nx][ny] of z coordinates z = f(x,y).
* @param r array[nx][ny] of red color components.
* @param g array[nx][ny] of green color components.
* @param b array[nx][ny] of blue color components.
*/
public static SimpleFrame asTriangles(
boolean vn, Sampling sx, Sampling sy, float[][] z,
float[][] r, float[][] g, float[][] b)
{
return asTriangles(new TriangleGroup(vn,sx,sy,z,r,g,b));
}
/**
* Returns a new simple frame with a triangle group.
* @param vn true, for vertex normals; false, for triangle normals
* @param xyz array of packed vertex coordinates.
* @param rgb array of packed color coordinates.
* @return the simple frame.
*/
public static SimpleFrame asTriangles(boolean vn, float[] xyz, float[] rgb) {
return asTriangles(new TriangleGroup(vn,xyz,rgb));
}
/**
* Returns a new simple frame with a triangle group.
* @param tg a triangle group.
* @return the simple frame.
*/
public static SimpleFrame asTriangles(TriangleGroup tg) {
SimpleFrame sf = new SimpleFrame();
sf.addTriangles(tg);
sf.getOrbitView().setWorldSphere(tg.getBoundingSphere(true));
return sf;
}
/**
* Returns a new simple frame with an image panel group.
* @param f a 3D array.
* @return the simple frame.
*/
public static SimpleFrame asImagePanels(float[][][] f) {
return asImagePanels(new ImagePanelGroup(f));
}
/**
* Returns a new simple frame with an image panel group.
* @param s1 sampling in the 1st dimension (Z).
* @param s2 sampling in the 2nd dimension (Y).
* @param s3 sampling in the 3rd dimension (X).
* @param f a 3D array.
* @return the simple frame.
*/
public static SimpleFrame asImagePanels(
Sampling s1, Sampling s2, Sampling s3, float[][][] f) {
return asImagePanels(new ImagePanelGroup(s1,s2,s3,f));
}
/**
* Returns a new simple frame with an image panel group.
* @param ipg an image panel group.
* @return the simple frame.
*/
public static SimpleFrame asImagePanels(ImagePanelGroup ipg) {
SimpleFrame sf = new SimpleFrame();
sf.addImagePanels(ipg);
sf.getOrbitView().setWorldSphere(ipg.getBoundingSphere(true));
return sf;
}
/**
* Adds a triangle group with specified vertex coordinates.
* @param xyz array of packed vertex coordinates.
* @return the triangle group.
*/
public TriangleGroup addTriangles(float[] xyz) {
return addTriangles(new TriangleGroup(true,xyz,null));
}
/**
* Adds a triangle group with specified vertex coordinates and colors.
* @param xyz array of packed vertex coordinates.
* @param rgb array of packed color components.
* @return the triangle group.
*/
public TriangleGroup addTriangles(float[] xyz, float[] rgb) {
return addTriangles(new TriangleGroup(true,xyz,rgb));
}
/**
* Adds a triangle group for a sampled function z = f(x,y).
* @param sx sampling of x coordinates; may be non-uniform.
* @param sy sampling of y coordinates; may be non-uniform.
* @param z array[nx][ny] of z coordinates z = f(x,y).
*/
public TriangleGroup addTriangles(Sampling sx, Sampling sy, float[][] z) {
return addTriangles(new TriangleGroup(true,sx,sy,z));
}
/**
* Adds a triangle group to a simple frame from a given triangle group.
* @param tg a triangle group.
* @return the attached triangle group.
*/
public TriangleGroup addTriangles(TriangleGroup tg) {
_world.addChild(tg);
return tg;
}
/**
* Adds an image panel group to a simple frame from a given 3D array
* @param f a 3D array.
* @return the image panel group.
*/
public ImagePanelGroup addImagePanels(float[][][] f) {
return addImagePanels(new Sampling(f[0][0].length),
new Sampling(f[0].length),
new Sampling(f.length),
f);
}
/**
* Adds an image panel group to a simple frame from given samplings and
* a 3D array.
* @param s1 sampling in the 1st dimension (Z).
* @param s2 sampling in the 2nd dimension (Y).
* @param s3 sampling in the 3rd dimension (X).
* @param f a 3D array.
* @return the image panel group.
*/
public ImagePanelGroup addImagePanels(
Sampling s1, Sampling s2, Sampling s3, float[][][] f) {
return addImagePanels(new ImagePanelGroup(s1,s2,s3,f));
}
/**
* Adds an image panel group to a simple frame from a given image panel
* group.
* @param ipg an image panel group.
* @return the attached image panel group.
*/
public ImagePanelGroup addImagePanels(ImagePanelGroup ipg) {
_world.addChild(ipg);
return ipg;
}
/**
* Gets the view canvas for this frame.
* @return the view canvas.
*/
public ViewCanvas getViewCanvas() {
return _canvas;
}
/**
* Gets the orbit view for this frame.
* @return the orbit view.
*/
public OrbitView getOrbitView() {
return _view;
}
/**
* Gets the world for this frame.
* @return the world.
*/
public World getWorld() {
return _world;
}
/**
* Sets the bounding sphere of the frame with a given center point and
* radius.
* @param p the center point.
* @param r the radius.
*/
public void setWorldSphere(Point3 p, int r) {
setWorldSphere(new BoundingSphere(p,r));
}
/**
* Sets the bounding sphere of the frame with a given center x, y, z and
* radius.
* @param x the center X-coordinate.
* @param y the center Y-coordinate.
* @param z the center Z-coordinate.
* @param r the radius.
*/
public void setWorldSphere(double x, double y, double z, double r) {
setWorldSphere(new BoundingSphere(x,y,z,r));
}
/**
* Sets the bounding sphere of the frame.
* @param xmin the minimum x coordinate.
* @param ymin the minimum y coordinate.
* @param zmin the minimum z coordinate.
* @param xmax the maximum x coordinate.
* @param ymax the maximum y coordinate.
* @param zmax the maximum z coordinate.
*/
public void setWorldSphere(
double xmin, double ymin, double zmin,
double xmax, double ymax, double zmax)
{
setWorldSphere(
new BoundingSphere(
new BoundingBox(xmin,ymin,zmin,xmax,ymax,zmax)));
}
/**
* Sets the bounding sphere of the frame.
* @param bs the bounding sphere.
*/
public void setWorldSphere(BoundingSphere bs) {
_view.setWorldSphere(bs);
}
/**
* Paints the view canvas to an image in a file with specified name.
* Uses the file suffix to determine the format of the image.
* @param fileName name of the file to contain the image.
*/
public void paintToFile(String fileName) {
_canvas.paintToFile(fileName);
}
// private
private ViewCanvas _canvas;
private OrbitView _view;
private World _world;
private ModeManager _modeManager;
private JToolBar _toolBar;
private static final int SIZE = 600;
}
|
package frc.team4215.stronghold;
/**
* <pre>
* <strong>Structure of this class:</strong>
* <b>class</b> <spam style="color:#f00">Const</spam>
* <b>class</b> <spam style="color:#f0f">Motor</spam>
* <b>class</b> <spam style="color:#00f">Num</spam>
* <spam style="color:#3d8">FrontLeft</spam> = 0
* <spam style="color:#3d8">BackLeft</spam> = 1
* <spam style="color:#3d8">BackRight</spam> = 2
* <spam style="color:#3d8">FrontRight</spam> = 3
* <spam style="color:#3d8">Arm</spam> = 4
* <spam style="color:#3d8">Intake</spam> = 5
* <b>class</b> <spam style="color:#00f">Run</spam>
* <spam style="color:#3d8">Forward</spam> = 1
* <spam style="color:#3d8">Backward</spam> = -1
* <spam style="color:#3d8">Stop</spam> = 0
* <b>class</b> <spam style="color:#f0f">JoyStick</spam>
* <b>class</b> <spam style="color:#00f">Num</spam>
* <spam style="color:#3d8">PlayStation</spam> = 1
* <spam style="color:#3d8">GameCube</spam> = 2
* <b>class</b> <spam style="color:#00f">Axis</spam>
* <spam style="color:#3d8">PlayStationCtrlLeft_UD</spam> = 1
* <spam style="color:#3d8">PlayStationCtrlRight_UD</spam> = 5
* <spam style="color:#3d8">GameCubeCtrl_UD</spam> = 1
* <b>class</b> <spam style="color:#00f">Button</spam>
* <spam style="color:#3d8">GameCube_Y</spam> = 1
* <spam style="color:#3d8">GameCube_X</spam> = 2
* <spam style="color:#3d8">GameCube_A</spam> = 3
* <spam style="color:#3d8">GameCube_B</spam> = 4
* </pre>
*
* @author James Yu
*/
public final class Const {
public final class Motor {
public final class Num {
public final static int FrontLeft = 0, BackLeft = 1, BackRight = 2,
FrontRight = 3, Arm = 4, Intake = 5;
}
public final class Run {
public final static double Forward = 1d, Backward = -1d, Stop = 0d;
}
}
public final class JoyStick {
public final class Num {
public final static int PlayStation = 1, GameCube = 2;
}
public final class Axis {
public final static int PlayStationCtrlLeft_UD = 1,
PlayStationCtrlRight_UD = 5;
public final static int GameCubeCtrl_UD = 1, GameCubeCtrl_LR = 0;
}
public final class Button {
public final static int GameCube_Y = 1, GameCube_X = 2,
GameCube_A = 3, GameCube_B = 4;
}
}
}
|
package gaiamod.blocks;
import gaiamod.GaiaMod;
import gaiamod.gui.ModGui;
import gaiamod.tileentities.TileEntityGaiaAltar;
import gaiamod.util.References;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.internal.FMLNetworkHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class GaiaAltarBlock extends BlockContainer {
private Random rand;
private final boolean isActive;
private final boolean isPowered;
private static boolean keepInventory = false;
@SideOnly(Side.CLIENT)
private IIcon gaiaAltarFront;
@SideOnly(Side.CLIENT)
private IIcon gaiaAltarTop;
public GaiaAltarBlock(boolean blockState, boolean fuelState) {
super(Material.rock);
rand = new Random();
isActive = blockState;
isPowered = fuelState;
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons (IIconRegister iconRegister) {
//this.blockIcon = iconRegister.registerIcon(References.MODID + ":" + getUnlocalizedName().substring(5) + "_side");
this.blockIcon = iconRegister.registerIcon(References.MODID + ":" + getUnlocalizedName().substring(5) + "_side");
//this.gaiaAltarFront = iconRegister.registerIcon(References.MODID + ":" + getUnlocalizedName().substring(5) + "_front");
this.gaiaAltarTop = iconRegister.registerIcon(References.MODID + ":" + getUnlocalizedName().substring(5) + "_top");
//this.gaiaAltarTop = iconRegister.registerIcon(References.MODID + ":" + getUnlocalizedName().substring(5) + "_top");
this.gaiaAltarFront = iconRegister.registerIcon(References.MODID + ":" + (this.isActive ? getUnlocalizedName().substring(5) + "_front" : (this.isPowered ? getUnlocalizedName().substring(5) + "_front" : getUnlocalizedName().substring(5) + "_front")));
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int metadata)
{
//return side == 1 ? this.gaiaAltarTop : (side == 0 ? this.gaiaAltarTop : (side != metadata ? this.blockIcon : this.gaiaAltarFront));
//return metadata == 0 && side == 1 ? this.gaiaAltarTop : (side == metadata ? this.gaiaAltarTop : this.blockIcon);
//return side == 1 ? this.gaiaAltarTop : this.blockIcon;
//return side == 1 ? this.gaiaAltarTop : (side == 0 ? this.gaiaAltarTop : (side != metadata ? this.blockIcon : this.gaiaAltarFront));
return side == 1 || side == 0 ? this.gaiaAltarTop : (side == 3 && metadata == 0 ? this.gaiaAltarFront : (side != metadata ? this.blockIcon : this.gaiaAltarFront));
}
public void onBlockAdded(World world, int x, int y, int z)
{
super.onBlockAdded(world, x, y, z);
this.setDefaultDirection(world, x, y, z);
}
private void setDefaultDirection(World world, int x, int y, int z) {
if (!world.isRemote)
{
Block block = world.getBlock(x, y, z - 1);
Block block1 = world.getBlock(x, y, z + 1);
Block block2 = world.getBlock(x - 1, y, z);
Block block3 = world.getBlock(x + 1, y, z);
byte b0 = 3;
if (block.func_149730_j() && !block1.func_149730_j())
{
b0 = 3;
}
if (block1.func_149730_j() && !block.func_149730_j())
{
b0 = 2;
}
if (block2.func_149730_j() && !block3.func_149730_j())
{
b0 = 5;
}
if (block3.func_149730_j() && !block2.func_149730_j())
{
b0 = 4;
}
world.setBlockMetadataWithNotify(x, y, z, b0, 2);
}
}
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack itemstack)
{
int l = MathHelper.floor_double((double)(entity.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
if (l == 0)
{
world.setBlockMetadataWithNotify(x, y, z, 2, 2);
}
if (l == 1)
{
world.setBlockMetadataWithNotify(x, y, z, 5, 2);
}
if (l == 2)
{
world.setBlockMetadataWithNotify(x, y, z, 3, 2);
}
if (l == 3)
{
world.setBlockMetadataWithNotify(x, y, z, 4, 2);
}
if (itemstack.hasDisplayName())
{
//((TileEntityGaiaAltar)world.getTileEntity(x, y, z)).setCustomName(itemstack.getDisplayName());
}
}
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) {
if(world.isRemote) {
return true;
}else if (!player.isSneaking()){
TileEntityGaiaAltar entity =(TileEntityGaiaAltar)world.getTileEntity(x, y, z);
if (entity != null){
FMLNetworkHandler.openGui(player, GaiaMod.instance, ModGui.guiIDGaiaAltar, world, x, y, z);
}
return true;
}else{
return false;
}
}
@Override
public TileEntity createNewTileEntity(World world, int i) {
return new TileEntityGaiaAltar();
}
public static void updateBlockState(boolean isAltaring, boolean hasPower, World world, int xCoord, int yCoord, int zCoord) {
int i = world.getBlockMetadata(xCoord, yCoord, zCoord);
TileEntity entity = world.getTileEntity(xCoord, yCoord, zCoord);
keepInventory = true;
if(isAltaring){
world.setBlock(xCoord, yCoord, zCoord, ModBlocks.gaiaAltarBlockActive);
}else{
if(hasPower){
world.setBlock(xCoord, yCoord, zCoord, ModBlocks.gaiaAltarBlockIdleFull);
}else{
world.setBlock(xCoord, yCoord, zCoord, ModBlocks.gaiaAltarBlockIdleEmpty);
}
}
keepInventory = false;
world.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, i, 2);
if(entity != null){
entity.validate();
world.setTileEntity(xCoord, yCoord, zCoord, entity);
}
}
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World world, int x, int y, int z, Random rand){
if(this.isActive) {
int direction = world.getBlockMetadata(x, y, z);
float x1 = (float)x + rand.nextFloat();
float y1 = (float)y + 0.7F;
float z1 = (float)z + 0.5F;
float f = 0.52F;
float f1 = rand.nextFloat() * 0.6F - 0.3F;
world.spawnParticle("smoke", (double)(x1), (double)(y1 + f), (double)(z1 + f1), 0D, 0D, 0D);
world.spawnParticle("flame", (double)(x1), (double)(y1 + f), (double)(z1 + f1), 0D, 0D, 0D);
world.spawnParticle("spell", (double)(x1), (double)(y1 + f), (double)(z1 + f1), 0D, 0D, 0D);
}
}
public Item getItemDropped(World world, int x , int y, int z) {
return Item.getItemFromBlock(ModBlocks.gaiaAltarBlockIdleEmpty);
}
}
|
package jabsc.classgen;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import bnfc.abs.Absyn.Case;
import bnfc.abs.Absyn.EAdd;
import bnfc.abs.Absyn.EAnd;
import bnfc.abs.Absyn.EDiv;
import bnfc.abs.Absyn.EEq;
import bnfc.abs.Absyn.EFunCall;
import bnfc.abs.Absyn.EGe;
import bnfc.abs.Absyn.EGt;
import bnfc.abs.Absyn.EIntNeg;
import bnfc.abs.Absyn.ELe;
import bnfc.abs.Absyn.ELit;
import bnfc.abs.Absyn.ELogNeg;
import bnfc.abs.Absyn.ELt;
import bnfc.abs.Absyn.EMod;
import bnfc.abs.Absyn.EMul;
import bnfc.abs.Absyn.ENaryFunCall;
import bnfc.abs.Absyn.ENaryQualFunCall;
import bnfc.abs.Absyn.ENeq;
import bnfc.abs.Absyn.EOr;
import bnfc.abs.Absyn.EParamConstr;
import bnfc.abs.Absyn.EQualFunCall;
import bnfc.abs.Absyn.EQualVar;
import bnfc.abs.Absyn.ESinglConstr;
import bnfc.abs.Absyn.ESub;
import bnfc.abs.Absyn.EThis;
import bnfc.abs.Absyn.EVar;
import bnfc.abs.Absyn.If;
import bnfc.abs.Absyn.Let;
import bnfc.abs.Absyn.PureExp;
import bnfc.abs.Absyn.PureExp.Visitor;
import jabsc.classgen.VisitorState.ModuleInfo;
import javassist.bytecode.Bytecode;
import javassist.bytecode.Opcode;
final class PureExpVisitor implements Visitor<Bytecode, Bytecode> {
private static final Map<String, String> FUNCTIONALS = new HashMap<>();
static {
FUNCTIONALS.put("toString", "(Ljava/lang/Object;)Ljava/lang/String;");
}
private final VisitorState state;
private final LiteralVisitor literalVisitor;
private final ModuleInfo currentModule;
PureExpVisitor(VisitorState state) {
this(null, state);
}
@Deprecated
PureExpVisitor(MethodState methodState, VisitorState state) {
this.state = state;
this.literalVisitor = new LiteralVisitor();
this.currentModule = state.getCurrentModule();
}
/**
* Evaluate a boolean statement (conjunction or disjunction)
*
* @param lhs
* @param rhs
* @param branchOp boolean operation (conjunction or disjunction)
* @param defaultValue
* @param branchValue
* @param arg
* @return
*/
private Bytecode booleanOp(PureExp lhs, PureExp rhs, int branchOp, int defaultValue,
int branchValue, Bytecode arg) {
// Evaluate lhs
Bytecode sub = lhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.toBooleanValue(ByteCodeUtil.add(sub, arg));
// branch to endOffset if operation is true
arg.addOpcode(branchOp);
// 2 byte place holders for offset
int offsetIndexLhs = arg.currentPc();
arg.add(-1, -1);
// Evaluate rhs
sub = rhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.toBooleanValue(ByteCodeUtil.add(sub, arg));
// branch to endOffset if operation is true
arg.addOpcode(branchOp);
// 2 byte place holders for offset
int offsetIndexRhs = arg.currentPc();
arg.add(-1, -1);
// fall through value
arg.addOpcode(defaultValue);
arg.add(Opcode.GOTO);
// 2 byte place holders for offset
int offsetIndexEnd = arg.currentPc();
arg.add(-1, -1);
// branch value
int endOffset = arg.currentPc();
arg.addOpcode(branchValue);
// Update offsets
arg.write16bit(offsetIndexLhs, endOffset - offsetIndexLhs + 1);
arg.write16bit(offsetIndexRhs, endOffset - offsetIndexRhs + 1);
arg.write16bit(offsetIndexEnd, arg.currentPc() - offsetIndexEnd + 1);
return ByteCodeUtil.toBoolean(arg);
}
@Override
public Bytecode visit(EOr p, Bytecode arg) {
/*
* branch to endOffset if 1 (true)
* Opcode.ICONST_0 if ! (lhs || rhs)
* Opcode.ICONST_1 if lhs || rhs
*/
return booleanOp(p.pureexp_1, p.pureexp_2, Opcode.IFNE, Opcode.ICONST_0, Opcode.ICONST_1, arg);
}
@Override
public Bytecode visit(EAnd p, Bytecode arg) {
/*
* branch to endOffset if 0 (false)
* Opcode.ICONST_1 if lhs && rhs
* Opcode.ICONST_0 if ! (lhs && rhs)
*/
return booleanOp(p.pureexp_1, p.pureexp_2, Opcode.IFEQ, Opcode.ICONST_1, Opcode.ICONST_0, arg);
}
private Bytecode equals(PureExp lhs, PureExp rhs, Bytecode arg) {
Bytecode sub = lhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.add(sub, arg);
sub = rhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.add(sub, arg);
arg.addInvokestatic("java/util/Objects", "equals", "(Ljava/lang/Object;Ljava/lang/Object;)Z");
return ByteCodeUtil.toBoolean(arg);
}
@Override
public Bytecode visit(EEq p, Bytecode arg) {
return equals(p.pureexp_1, p.pureexp_2, arg);
}
@Override
public Bytecode visit(ENeq p, Bytecode arg) {
/*
* branch to endOffset if 0 (false)
* Opcode.ICONST_1 if exp
* Opcode.ICONST_0 if ! exp
*/
// Evaluate expression against equals
Bytecode sub = equals(p.pureexp_1, p.pureexp_2, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.toBooleanValue(ByteCodeUtil.add(sub, arg));
// branch to endOffset if operation is false
arg.addOpcode(Opcode.IFNE);
// 2 byte place holders for offset
int offsetIndex = arg.currentPc();
arg.add(-1, -1);
// fall through value
arg.addOpcode(Opcode.ICONST_1);
arg.add(Opcode.GOTO);
// 2 byte place holders for offset
int offsetIndexEnd = arg.currentPc();
arg.add(-1, -1);
// branch value
int endOffset = arg.currentPc();
arg.addOpcode(Opcode.ICONST_0);
// Update offsets
arg.write16bit(offsetIndex, endOffset - offsetIndex + 1);
arg.write16bit(offsetIndexEnd, arg.currentPc() - offsetIndexEnd + 1);
return ByteCodeUtil.toBoolean(arg);
}
private Bytecode longComparison(PureExp lhs, PureExp rhs, int cmpOp, Bytecode arg) {
// Evaluate lhs
Bytecode sub = lhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.toLongValue(ByteCodeUtil.add(sub, arg));
// Evaluate rhs
sub = rhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.toLongValue(ByteCodeUtil.add(sub, arg));
// Compare two values
arg.addOpcode(Opcode.LCMP);
// branch to endOffset if operation is true
arg.addOpcode(cmpOp);
// 2 byte place holders for offset
int offsetIndex = arg.currentPc();
arg.add(-1, -1);
// fall through location
arg.addOpcode(Opcode.ICONST_0);
arg.add(Opcode.GOTO);
// 2 byte place holders for offset
int offsetIndexEnd = arg.currentPc();
arg.add(-1, -1);
// branch location
int endOffset = arg.currentPc();
arg.addOpcode(Opcode.ICONST_1);
// Update offsets
arg.write16bit(offsetIndex, endOffset - offsetIndex + 1);
arg.write16bit(offsetIndexEnd, arg.currentPc() - offsetIndexEnd + 1);
return ByteCodeUtil.toBoolean(arg);
}
@Override
public Bytecode visit(ELt p, Bytecode arg) {
return longComparison(p.pureexp_1, p.pureexp_2, Opcode.IFLT, arg);
}
@Override
public Bytecode visit(ELe p, Bytecode arg) {
return longComparison(p.pureexp_1, p.pureexp_2, Opcode.IFLE, arg);
}
@Override
public Bytecode visit(EGt p, Bytecode arg) {
return longComparison(p.pureexp_1, p.pureexp_2, Opcode.IFGT, arg);
}
@Override
public Bytecode visit(EGe p, Bytecode arg) {
return longComparison(p.pureexp_1, p.pureexp_2, Opcode.IFGE, arg);
}
private Bytecode arithmetic(PureExp lhs, PureExp rhs, int operation, Bytecode arg) {
Bytecode sub = lhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.toLongValue(ByteCodeUtil.add(sub, arg));
sub = rhs.accept(this, ByteCodeUtil.newByteCode(arg));
arg = ByteCodeUtil.toLongValue(ByteCodeUtil.add(sub, arg));
arg.addOpcode(operation);
return ByteCodeUtil.toLong(arg);
}
@Override
public Bytecode visit(EAdd p, Bytecode arg) {
return arithmetic(p.pureexp_1, p.pureexp_2, Opcode.LADD, arg);
}
@Override
public Bytecode visit(ESub p, Bytecode arg) {
return arithmetic(p.pureexp_1, p.pureexp_2, Opcode.LSUB, arg);
}
@Override
public Bytecode visit(EMul p, Bytecode arg) {
return arithmetic(p.pureexp_1, p.pureexp_2, Opcode.LMUL, arg);
}
@Override
public Bytecode visit(EDiv p, Bytecode arg) {
return arithmetic(p.pureexp_1, p.pureexp_2, Opcode.LDIV, arg);
}
@Override
public Bytecode visit(EMod p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(ELogNeg p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(EIntNeg p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(EFunCall p, Bytecode arg) {
String dotPrefix = "." + p.lident_;
Optional<String> fullImport =
currentModule.getImports().stream().filter(s -> s.endsWith(dotPrefix)).findFirst();
p.listpureexp_.forEach(e -> e.accept(this, arg));
if (fullImport.isPresent()) {
String qualified = fullImport.get();
String descriptor = state.getDescriptor(qualified);
String module = qualified.substring(0, qualified.length() - dotPrefix.length());
String function = state.getModuleInfos(module).getFunctionClassName();
String className = (module + '.' + function).replace('.', '/');
arg.addInvokestatic(className, p.lident_, descriptor);
} else {
String descriptor = FUNCTIONALS.get(p.lident_);
arg.addInvokestatic(StateUtil.FUNCTIONAL, p.lident_, descriptor);
}
return arg;
}
@Override
public Bytecode visit(EQualFunCall p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(ENaryFunCall p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(ENaryQualFunCall p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(EVar p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(EThis p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(EQualVar p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(ESinglConstr p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(EParamConstr p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(ELit p, Bytecode arg) {
return p.literal_.accept(literalVisitor, arg);
}
@Override
public Bytecode visit(Let p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(If p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bytecode visit(Case p, Bytecode arg) {
// TODO Auto-generated method stub
return null;
}
}
|
package org.hyperic.sigar.cmd;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.SigarException;
/**
* Display network info.
*/
public class NetInfo extends SigarCommandBase {
public NetInfo(Shell shell) {
super(shell);
}
public NetInfo() {
super();
}
public String getUsageShort() {
return "Display network info";
}
public void output(String[] args) throws SigarException {
NetInterfaceConfig config = this.sigar.getNetInterfaceConfig(null);
println("primary interface....." +
config.getName());
println("primary ip address...." +
config.getAddress());
println("primary mac address..." +
config.getHwaddr());
println("primary netmask......." +
config.getNetmask());
org.hyperic.sigar.NetInfo info =
this.sigar.getNetInfo();
println("host name............." +
info.getHostName());
println("domain name..........." +
info.getDomainName());
println("default gateway......." +
info.getDefaultGateway());
println("primary dns..........." +
info.getPrimaryDns());
println("secondary dns........." +
info.getSecondaryDns());
}
public static void main(String[] args) throws Exception {
new NetInfo().processCommand(args);
}
}
|
package japsa.tools.seq;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
public class SequenceUtils {
public static Iterator<SAMRecord> getSAMIteratorFromFastq(File inFile, String mm2Index, String mm2_path,
int mm2_threads, String mm2Preset, String mm2_mem, String mm2_splicing) throws IOException{
return new FastqToSAMRecord(inFile, mm2Index, mm2_path,mm2_threads, mm2Preset, mm2_mem , mm2_splicing);
}
public static Iterator<SAMRecord> getSAMIteratorFromFastq(File inFile, String mm2Index, String mm2_path,
int mm2_threads, String mm2Preset, String mm2_mem) throws IOException{
return new FastqToSAMRecord(inFile, mm2Index, mm2_path,mm2_threads, mm2Preset, mm2_mem , null);
}
private static class FastqToSAMRecord implements Iterator<SAMRecord> {
// ProcessBuilder pb;
SamReader reader;
SAMRecordIterator iterator;
public FastqToSAMRecord(File inFile, String mm2Index, String mm2_path, int mm2_threads, String mm2Preset, String mm2_mem, String splicing) throws IOException{
ProcessBuilder pb;
if(splicing==null) pb = new ProcessBuilder(mm2_path,
"-t",
"" + mm2_threads,
"-ax",
mm2Preset,
// "--for-only",
"-I",
mm2_mem,
// "200M",
mm2Index,
"-"
);
else pb = new ProcessBuilder(mm2_path,
"-t",
"" + mm2_threads,
"-ax",
mm2Preset,
splicing,
// "--for-only",
"-I",
mm2_mem,
// "200M",
mm2Index,
"-"
);
Process mm2Process = pb.redirectInput(ProcessBuilder.Redirect.from(inFile)).redirectError(ProcessBuilder.Redirect.to(new File("err.txt"))).start();
// Process mm2Process = pb.redirectError(ProcessBuilder.Redirect.to(new File("err.txt"))).start();
// OutputStream os = mm2Process.getOutputStream();
reader = SamReaderFactory.makeDefault().open(SamInputResource.of(mm2Process.getInputStream()));
iterator = reader.iterator();
}
@Override
public boolean hasNext() {
boolean res = iterator.hasNext();
try{
if(!res) reader.close();
}catch(IOException exc){
exc.printStackTrace();
}
return res;
}
@Override
public SAMRecord next() {
return iterator.next();
}
}
public static String src_tag = "SC";
public static String pool_tag = "PT";
public static class CombinedIterator implements Iterator<SAMRecord> {
private final Iterator<SAMRecord>[] samIters;
int current_sam_index =0;
int currentIndex =0; //relates to chromosome
private final SAMRecord[] currentVals;
private final boolean[] returned;
private final int[] cnts ;
int max;
Collection<String>[] readList ;
Map<Integer, int[]> chrs;
public CombinedIterator(Iterator<SAMRecord>[] samIters, int max, Collection<String>[]readList, Map<Integer, int[]> chrs) {
this.samIters = samIters;
this.readList = readList;
currentVals = new SAMRecord[samIters.length];
returned = new boolean [samIters.length];
this.max = max;
cnts = new int[samIters.length];
this.chrs = chrs.size()>0 ? chrs : null;
}
/*public void close(){
for(int i=0; i<samIters.length; i++){
samIters[i].close();
}
}*/
@Override
public boolean hasNext() {
for(int i=0; i<samIters.length; i++){
if(samIters[i].hasNext() && cnts[i]<max) return true;
}
// this.close();
return false;
}
int pool_ind=-1;
private SAMRecord next(int i){
SAMRecord sr;
if(currentVals[i]!=null && !returned[i]){
sr = currentVals[i];
}else{
if(cnts[i]<max){
//sr = samIters[i].next();
/* while(!(
sr==null ||
(readList==null || readList.contains(sr.getReadName())) ||
(chrs==null || chrs.contains(sr.getReferenceIndex()))
)
)*/
inner: while(true)
{
sr = samIters[i].next();
if(sr==null) break inner;
pool_ind =-1;
if(readList!=null){
inner1: for(int i2=0; i2<readList.length; i2++){
if(readList[i2].contains(sr.getReadName())){
pool_ind = i2;
break inner1;
}
}
}
if(readList!=null && pool_ind>=0) break inner;
if(readList==null && chrs!=null && contains(chrs,sr)) break inner;
if(readList==null && chrs==null) break inner;
}
if(sr!=null) {
sr.setAttribute(pool_tag, pool_ind);
sr.setAttribute(src_tag, i);
}
currentVals[i] = sr;
returned[i] = false;
}else{
sr = null;
}
}
return sr;
}
private boolean contains(Map<Integer, int[]> chrs2, SAMRecord sr) {
int[] obj = chrs2.get(sr.getReferenceIndex());
if(obj==null) return false;
else{
if(sr.getAlignmentStart()>=obj[0] && sr.getAlignmentEnd() <=obj[1]) return true;
else return false;
}
}
@Override
public SAMRecord next() {
//int curr_index = current_sam_index;
SAMRecord sr = next(current_sam_index);
if(sr==null || sr.getReferenceIndex()>currentIndex ){
int[] ref_inds = new int[samIters.length];
int min_ind =-1;
int minv = Integer.MAX_VALUE;
for(int i=0; i<samIters.length; i++){
SAMRecord sr_i = next(i);
if(sr_i!=null) {
ref_inds[i] = sr_i.getReferenceIndex(); //note this only advances if not returned;
if(ref_inds[i]<minv){
min_ind = i;
minv = ref_inds[i];
}
}
}
current_sam_index = min_ind;
}
if(current_sam_index<0) return null;
sr = this.currentVals[current_sam_index];
if(sr!=null) this.currentIndex = sr.getReferenceIndex();
cnts[current_sam_index]++;
returned[current_sam_index] = true;
return sr;
}
}
public static Iterator<SAMRecord> getCombined(Iterator<SAMRecord>[] samReaders, Collection[] reads, int max_reads,String chroms){
Map<Integer, int[]>chromIndices = new HashMap<Integer, int[]>();
return getCombined(samReaders,reads, max_reads, chroms, chromIndices);
}
//chroms is string e.g 0:1:2 or 0,0,2400000:1,0,240000
public static Iterator<SAMRecord> getCombined(Iterator<SAMRecord>[] samReaders, Collection[] reads, int max_reads,String chroms,
Map<Integer, int[]>chromIndices ){
// Map<Integer, int[] > chromIndices = null;
if(chroms!=null && !chroms.equals("all")){
String[] chri = chroms.split(":");
for(int i=0; i<chri.length; i++){
String[] str = chri[i].split(",");
int[] vals ;
if(str.length==1) vals = new int[] {0,Integer.MAX_VALUE};
else{
vals = new int[] {Integer.parseInt(str[1]), Integer.parseInt(str[2])};
}
chromIndices.put(Integer.parseInt(str[0]), vals);
}
}
int len = samReaders.length;
// SAMRecordIterator[] samIters = new SAMRecordIterator[len];
//for (int ii = 0; ii < len; ii++) {
// samIters[ii] = samReaders[ii].iterator();
//if(reads==null && chrom_indices_to_include==null && samReaders.length==1){
// samIter = samIters[0];
// }else{
return new CombinedIterator(samReaders, max_reads,reads, chromIndices);
}
public static String minimapIndex(File refFile, String mm2, String mem, boolean overwrite) throws IOException, InterruptedException {
File indexFile = new File(refFile.getAbsolutePath()+".mmi");
if(indexFile.exists() && !overwrite){
System.out.println("minimap index exists");
}else{
ProcessBuilder pb = new ProcessBuilder(mm2,
"-I",
mem,
"-d",
indexFile.toString(),
refFile.toString()
);
//System.err.println(pb.toString());
Process p = pb.redirectError(ProcessBuilder.Redirect.to(new File("/dev/null"))).start();
p.waitFor();
}
return indexFile.getAbsolutePath();
}
}
|
package org.myeslib.jdbi.storage;
import com.google.common.cache.Cache;
import org.myeslib.core.AggregateRoot;
import org.myeslib.core.Event;
import org.myeslib.data.Snapshot;
import org.myeslib.data.UnitOfWork;
import org.myeslib.function.ApplyEventsFunction;
import org.myeslib.jdbi.storage.dao.UnitOfWorkDao;
import org.myeslib.storage.SnapshotReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.Collator;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
public class JdbiReader<K, A extends AggregateRoot> implements SnapshotReader<K, A> {
private static final Logger logger = LoggerFactory.getLogger(JdbiReader.class);
private final Supplier<A> supplier;
private final UnitOfWorkDao<K> dao;
private final Cache<K, Snapshot<A>> cache;
private final ApplyEventsFunction<A> applyEventsFunction;
public JdbiReader(Supplier<A> supplier, UnitOfWorkDao<K> dao,
Cache<K, Snapshot<A>> cache, ApplyEventsFunction<A> ApplyEventsFunction) {
checkNotNull(supplier);
this.supplier = supplier;
checkNotNull(dao);
this.dao = dao;
checkNotNull(cache);
this.cache = cache;
checkNotNull(ApplyEventsFunction);
this.applyEventsFunction = ApplyEventsFunction;
}
/*
* (non-Javadoc)
* @see org.myeslib.storage.SnapshotReader#getPartial(java.lang.Object)
*/
public Snapshot<A> getSnapshot(final K id) {
checkNotNull(id);
final Snapshot<A> lastSnapshot;
final AtomicBoolean wasDaoCalled = new AtomicBoolean(false);
try {
logger.debug("id {} cache.get(id)", id);
lastSnapshot = cache.get(id, () -> {
logger.debug("id {} cache.get(id) does not contain anything for this id. Will have to search on dao", id);
wasDaoCalled.set(true);
List<UnitOfWork> uows = dao.getFull(id);
return new Snapshot<>(applyEventsFunction.apply(supplier.get(), unfold(uows)), lastVersion(uows));
});
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
logger.debug("id {} wasDaoCalled ? {}", id, wasDaoCalled.get());
if (wasDaoCalled.get()) {
return lastSnapshot;
}
logger.debug("id {} lastSnapshot has version {}. will check if there any version beyond it", id, lastSnapshot.getVersion());
final List<UnitOfWork> partialTransactionHistory = dao.getPartial(id, lastSnapshot.getVersion());
if (partialTransactionHistory.isEmpty()) {
return lastSnapshot;
}
logger.debug("id {} found {} pending transactions. Last version is {}", id, partialTransactionHistory.size(), lastVersion(partialTransactionHistory));
final A ar = applyEventsFunction.apply(lastSnapshot.getAggregateInstance(), unfold(partialTransactionHistory));
final Snapshot<A> latestSnapshot = new Snapshot<>(ar, lastVersion(partialTransactionHistory));
cache.put(id, latestSnapshot); // TODO assert this on tests
return latestSnapshot;
}
List<Event> unfold(List<UnitOfWork> uows) {
return uows.stream().flatMap((unitOfWork) -> unitOfWork.getEvents().stream()).collect(Collectors.toList());
}
Long lastVersion(List<UnitOfWork> uows) {
return uows.isEmpty() ? 0L : uows.get(uows.size()-1).getVersion();
}
}
|
package net.md_5.bungee;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static net.md_5.bungee.Logger.$;
import net.md_5.bungee.command.CommandSender;
import net.md_5.bungee.command.ConsoleCommandSender;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
/**
* Core configuration for the proxy.
*/
public class Configuration
{
/**
* Reconnect locations file.
*/
private transient File reconnect = new File("locations.yml");
/**
* Loaded reconnect locations.
*/
private transient Map<String, String> reconnectLocations;
/**
* Config file.
*/
private transient File file = new File("config.yml");
/**
* Yaml instance.
*/
private transient Yaml yaml;
/**
* Loaded config.
*/
private transient Map<String, Object> config;
/**
* Bind host.
*/
public String bindHost = "0.0.0.0:25577";
/**
* Server ping motd.
*/
public String motd = "BungeeCord Proxy Instance";
/**
* Name of default server.
*/
public String defaultServerName = "default";
/**
* Max players as displayed in list ping. Soft limit.
*/
public int maxPlayers = 1;
/**
* Tab list 1: For a tab list that is global over all server (using their
* Minecraft name) and updating their ping frequently 2: Same as 1 but does
* not update their ping frequently, just once, 3: Makes the individual
* servers handle the tab list (server unique).
*/
public int tabList = 1;
/**
* Socket timeout.
*/
public int timeout = 15000;
/**
* All servers.
*/
public Map<String, String> servers = new HashMap<String, String>()
{
{
put(defaultServerName, "127.0.0.1:1338");
put("pvp", "127.0.0.1:1337");
}
};
/**
* Forced servers.
*/
public Map<String, String> forcedServers = new HashMap<String, String>()
{
{
put("pvp.md-5.net", "pvp");
}
};
/**
* Proxy admins.
*/
public List<String> admins = new ArrayList<String>()
{
{
add("Insert Admins Here");
}
};
/**
* Proxy moderators.
*/
public List<String> moderators = new ArrayList<String>()
{
{
add("Insert Moderators Here");
}
};
/**
* Commands which will be blocked completely.
*/
public List<String> disabledCommands = new ArrayList<String>()
{
{
add("glist");
}
};
/**
* Maximum number of lines to log before old ones are removed.
*/
public int logNumLines = 1 << 14;
/**
* UUID for Metrics.
*/
public String statsUuid = UUID.randomUUID().toString();
/**
* Load the configuration and save default values.
*/
public void load()
{
try
{
file.createNewFile();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yaml = new Yaml(options);
try (InputStream is = new FileInputStream(file))
{
config = (Map) yaml.load(is);
}
if (config == null)
{
config = new LinkedHashMap<>();
}
$().info("
for (Field field : getClass().getDeclaredFields())
{
if (!Modifier.isTransient(field.getModifiers()))
{
String name = Util.normalize(field.getName());
try
{
Object def = field.get(this);
Object value = get(name, def);
field.set(this, value);
$().info(name + ": " + value);
} catch (IllegalAccessException ex)
{
$().severe("Could not get config node: " + name);
}
}
}
$().info("
if (servers.get(defaultServerName) == null)
{
throw new IllegalArgumentException("Server '" + defaultServerName + "' not defined");
}
if (forcedServers != null)
{
for (String server : forcedServers.values())
{
if (!servers.containsKey(server))
{
throw new IllegalArgumentException("Forced server " + server + " is not defined in servers");
}
}
}
motd = ChatColor.translateAlternateColorCodes('&', motd);
reconnect.createNewFile();
try (FileInputStream recon = new FileInputStream(reconnect))
{
reconnectLocations = (Map) yaml.load(recon);
}
if (reconnectLocations == null)
{
reconnectLocations = new LinkedHashMap<>();
}
} catch (IOException ex)
{
$().severe("Could not load config!");
ex.printStackTrace();
}
}
private <T> T get(String path, T def)
{
if (!config.containsKey(path))
{
config.put(path, def);
save(file, config);
}
return (T) config.get(path);
}
private void save(File fileToSave, Map toSave)
{
try
{
try (FileWriter wr = new FileWriter(fileToSave))
{
yaml.dump(toSave, wr);
}
} catch (IOException ex)
{
$().severe("Could not save config file " + fileToSave);
ex.printStackTrace();
}
}
/**
* Get which server a user should be connected to, taking into account their
* name and virtual host.
*
* @param user to get a server for
* @param requestedHost the host which they connected to
* @return the name of the server which they should be connected to.
*/
public String getServer(String user, String requestedHost)
{
String server = (forcedServers == null) ? null : forcedServers.get(requestedHost);
if (server == null)
{
server = reconnectLocations.get(user);
}
if (server == null)
{
server = servers.get(defaultServerName);
}
return server;
}
/**
* Save the last server which the user was on.
*
* @param user the name of the user
* @param server which they were last on
*/
public void setServer(UserConnection user, String server)
{
reconnectLocations.put(user.username, server);
}
/**
* Gets the connectable address of a server defined in the configuration.
*
* @param name the friendly name of a server
* @return the usable {@link InetSocketAddress} mapped to this server
*/
public InetSocketAddress getServer(String name)
{
String server = servers.get((name == null) ? defaultServerName : name);
return (server != null) ? Util.getAddr(server) : getServer(null);
}
/**
* Save the current mappings of users to servers.
*/
public void saveHosts()
{
save(reconnect, reconnectLocations);
$().info("Saved reconnect locations to " + reconnect);
}
public Permission getPermission(CommandSender sender)
{
Permission permission = Permission.DEFAULT;
if (admins.contains(sender.getName()) || sender instanceof ConsoleCommandSender)
{
permission = Permission.ADMIN;
} else if (moderators.contains(sender.getName()))
{
permission = Permission.MODERATOR;
}
return permission;
}
}
|
package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import nl.mpi.kinnate.ui.KinTypeEgoSelectionTestPanel;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
import javax.xml.transform.TransformerException;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.ImdiTableModel;
import nl.mpi.arbil.clarin.CmdiComponentBuilder;
import nl.mpi.arbil.data.ImdiLoader;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kintypestrings.KinTerms;
import org.apache.batik.bridge.UpdateManager;
import org.apache.batik.dom.events.DOMMouseEvent;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGLocatable;
import org.w3c.dom.svg.SVGRect;
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
private JSVGCanvas svgCanvas;
private SVGDocument doc;
private Element currentDraggedElement;
private Cursor preDragCursor;
private HashSet<URI> egoSet = new HashSet<URI>();
private String[] kinTypeStrings = new String[]{};
private IndexerParameters indexParameters;
private KinTerms kinTerms;
private ImdiTableModel imdiTableModel;
private GraphData graphData;
private boolean requiresSave = false;
private File svgFile = null;
private GraphPanelSize graphPanelSize;
private ArrayList<String> selectedGroupElement;
private String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
private String kinDataNameSpace = "kin";
private String kinDataNameSpaceLocation = "http://mpi.nl/tla/kin";
public GraphPanel(KinTypeEgoSelectionTestPanel egoSelectionPanel) {
selectedGroupElement = new ArrayList<String>();
graphPanelSize = new GraphPanelSize();
indexParameters = new IndexerParameters();
kinTerms = new KinTerms();
this.setLayout(new BorderLayout());
svgCanvas = new JSVGCanvas();
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
AffineTransform at = new AffineTransform();
// System.out.println("R: " + e.getWheelRotation());
// System.out.println("A: " + e.getScrollAmount());
// System.out.println("U: " + e.getUnitsToScroll());
at.scale(1 + e.getUnitsToScroll() / 10.0, 1 + e.getUnitsToScroll() / 10.0);
// at.translate(e.getX()/10.0, e.getY()/10.0);
// System.out.println("x: " + e.getX());
// System.out.println("y: " + e.getY());
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
MouseInputAdapter mouseInputAdapter = new MouseInputAdapter() {
@Override
public void mouseDragged(MouseEvent me) {
// System.out.println("mouseDragged: " + me.toString());
if (currentDraggedElement != null) {
svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
updateDragNode(currentDraggedElement, me.getX(), me.getY());
}
}
@Override
public void mouseReleased(MouseEvent me) {
// System.out.println("mouseReleased: " + me.toString());
if (currentDraggedElement != null) {
svgCanvas.setCursor(preDragCursor);
updateDragNode(currentDraggedElement, me.getX(), me.getY());
currentDraggedElement = null;
}
}
};
svgCanvas.addMouseListener(mouseInputAdapter);
svgCanvas.addMouseMotionListener(mouseInputAdapter);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
this.add(BorderLayout.CENTER, jSVGScrollPane);
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(egoSelectionPanel, this, graphPanelSize));
}
public void setImdiTableModel(ImdiTableModel imdiTableModelLocal) {
imdiTableModel = imdiTableModelLocal;
}
public void readSvg(File svgFilePath) {
svgFile = svgFilePath;
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString());
svgCanvas.setDocument(doc);
requiresSave = false;
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// svgCanvas.setURI(svgFilePath.toURI().toString());
ArrayList<String> egoStringArray = new ArrayList<String>();
egoSet.clear();
for (String currentEgoString : getSingleParametersFromDom("EgoList")) {
try {
egoSet.add(new URI(currentEgoString));
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
kinTypeStrings = getSingleParametersFromDom("KinTypeStrings");
indexParameters.ancestorFields.setValues(getDoubleParametersFromDom("AncestorFields"));
indexParameters.decendantFields.setValues(getDoubleParametersFromDom("DecendantFields"));
indexParameters.labelFields.setValues(getDoubleParametersFromDom("LabelFields"));
indexParameters.symbolFieldsFields.setValues(getDoubleParametersFromDom("SymbolFieldsFields"));
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
new CmdiComponentBuilder().savePrettyFormatting(doc, svgFilePath);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
private String[] getSingleParametersFromDom(String parameterName) {
ArrayList<String> parameterList = new ArrayList<String>();
if (doc != null) {
// printNodeNames(doc);
try {
// todo: resolve names space issue
// todo: try setting the XPath namespaces
NodeList parameterNodeList = org.apache.xpath.XPathAPI.selectNodeList(doc, "/svg:svg/kin:KinDiagramData/kin:" + parameterName);
for (int nodeCounter = 0; nodeCounter < parameterNodeList.getLength(); nodeCounter++) {
Node parameterNode = parameterNodeList.item(nodeCounter);
if (parameterNode != null) {
parameterList.add(parameterNode.getAttributes().getNamedItem("value").getNodeValue());
}
}
} catch (TransformerException transformerException) {
GuiHelper.linorgBugCatcher.logError(transformerException);
}
// // todo: populate the avaiable symbols indexParameters.symbolFieldsFields.setAvailableValues(new String[]{"circle", "triangle", "square", "union"});
}
return parameterList.toArray(new String[]{});
}
private String[][] getDoubleParametersFromDom(String parameterName) {
ArrayList<String[]> parameterList = new ArrayList<String[]>();
if (doc != null) {
try {
// todo: resolve names space issue
NodeList parameterNodeList = org.apache.xpath.XPathAPI.selectNodeList(doc, "/svg/KinDiagramData/" + parameterName);
for (int nodeCounter = 0; nodeCounter < parameterNodeList.getLength(); nodeCounter++) {
Node parameterNode = parameterNodeList.item(nodeCounter);
if (parameterNode != null) {
parameterList.add(new String[]{parameterNode.getAttributes().getNamedItem("path").getNodeValue(), parameterNode.getAttributes().getNamedItem("value").getNodeValue()});
}
}
} catch (TransformerException transformerException) {
GuiHelper.linorgBugCatcher.logError(transformerException);
}
// // todo: populate the avaiable symbols indexParameters.symbolFieldsFields.setAvailableValues(new String[]{"circle", "triangle", "square", "union"});
}
return parameterList.toArray(new String[][]{});
}
public String[] getKinTypeStrigs() {
return kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
HashSet<String> kinTypeStringSet = new HashSet<String>();
for (String kinTypeString : kinTypeStringArray) {
if (kinTypeString != null && kinTypeString.trim().length() > 0) {
kinTypeStringSet.add(kinTypeString.trim());
}
}
kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
}
public IndexerParameters getIndexParameters() {
return indexParameters;
}
public KinTerms getkinTerms() {
return kinTerms;
}
public URI[] getEgoList() {
return egoSet.toArray(new URI[]{});
}
public void setEgoList(URI[] egoListArray) {
egoSet = new HashSet<URI>(Arrays.asList(egoListArray));
}
public String[] getSelectedPaths() {
return selectedGroupElement.toArray(new String[]{});
}
private void storeParameter(Element dataStoreElement, String parameterName, String[] ParameterValues) {
for (String currentKinType : ParameterValues) {
Element dataRecordNode = doc.createElementNS(kinDataNameSpace, parameterName);
// Element dataRecordNode = doc.createElement(kinDataNameSpace + ":" + parameterName);
dataRecordNode.setAttributeNS(kinDataNameSpace, "value", currentKinType);
dataStoreElement.appendChild(dataRecordNode);
}
}
private void storeParameter(Element dataStoreElement, String parameterName, String[][] ParameterValues) {
for (String[] currentKinType : ParameterValues) {
Element dataRecordNode = doc.createElementNS(kinDataNameSpace, parameterName);
// Element dataRecordNode = doc.createElement(kinDataNameSpace + ":" + parameterName);
if (currentKinType.length == 1) {
dataRecordNode.setAttributeNS(kinDataNameSpace, "value", currentKinType[0]);
} else if (currentKinType.length == 2) {
dataRecordNode.setAttributeNS(kinDataNameSpace, "path", currentKinType[0]);
dataRecordNode.setAttributeNS(kinDataNameSpace, "value", currentKinType[1]);
} else {
// todo: add any other datatypes if required
throw new UnsupportedOperationException();
}
dataStoreElement.appendChild(dataRecordNode);
}
}
public void resetZoom() {
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void drawNodes() {
drawNodes(graphData);
}
private void updateDragNode(final Element updateDragNodeElement, final int updateDragNodeX, final int updateDragNodeY) {
UpdateManager updateManager = svgCanvas.getUpdateManager();
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
System.out.println("updateDragNodeX: " + updateDragNodeX);
System.out.println("updateDragNodeY: " + updateDragNodeY);
if (updateDragNodeElement != null) {
SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox();
// ((SVGLocatable) currentDraggedElement).g
updateDragNodeElement.setAttribute("transform", "translate(" + String.valueOf(updateDragNodeX * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeY - bbox.getY()) + ")");
// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeX));
// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeY));
}
// SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox();
// System.out.println("bbox X: " + bbox.getX());
// System.out.println("bbox Y: " + bbox.getY());
// System.out.println("bbox W: " + bbox.getWidth());
// System.out.println("bbox H: " + bbox.getHeight());
// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned
// SVGLocatable.getTransformToElement()
// SVGPoint.matrixTransform()
svgCanvas.revalidate();
}
});
}
private void addHighlightToGroup() {
UpdateManager updateManager = svgCanvas.getUpdateManager();
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
if (doc != null) {
Element svgRoot = doc.getDocumentElement();
for (Node currentChild = svgRoot.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
if (idAttrubite != null) {
String entityPath = idAttrubite.getTextContent();
System.out.println("group id (entityPath): " + entityPath);
Node existingHighlight = null;
// find any existing highlight
for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) {
if ("rect".equals(subGoupNode.getLocalName())) {
Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id");
if (subGroupIdAttrubite != null) {
if ("highlight".equals(subGroupIdAttrubite.getTextContent())) {
existingHighlight = subGoupNode;
}
}
}
}
if (!selectedGroupElement.contains(entityPath)) {
// remove all old highlights
if (existingHighlight != null) {
currentChild.removeChild(existingHighlight);
}
// add the current highlights
} else {
if (existingHighlight == null) {
svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
System.out.println("bbox X: " + bbox.getX());
System.out.println("bbox Y: " + bbox.getY());
System.out.println("bbox W: " + bbox.getWidth());
System.out.println("bbox H: " + bbox.getHeight());
Element symbolNode = doc.createElementNS(svgNameSpace, "rect");
int paddingDistance = 20;
symbolNode.setAttribute("id", "highlight");
symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance));
symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance));
symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2));
symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2));
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("stroke-width", "1");
symbolNode.setAttribute("stroke", "blue");
symbolNode.setAttribute("stroke-dasharray", "3");
symbolNode.setAttribute("stroke-dashoffset", "0");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("style", ":none;fill-opacity:1;fill-rule:nonzero;stroke:#6674ff;stroke-opacity:1;stroke-width:1;stroke-miterlimit:4;"
// + "stroke-dasharray:1, 1;stroke-dashoffset:0");
currentChild.appendChild(symbolNode);
}
}
}
}
}
}
}
});
}
private Element createEntitySymbol(GraphDataNode currentNode, int hSpacing, int vSpacing, int symbolSize) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
groupNode.setAttribute("id", currentNode.getEntityPath());
// counterTest++;
Element symbolNode;
String symbolType = currentNode.getSymbolType();
if ("circle".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "circle");
symbolNode.setAttribute("cx", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
symbolNode.setAttribute("cy", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
symbolNode.setAttribute("r", Integer.toString(symbolSize / 2));
symbolNode.setAttribute("height", Integer.toString(symbolSize));
// <circle id="_16" cx="120.0" cy="155.0" r="50" fill="red" stroke="black" stroke-width="1"/>
// <polygon id="_17" transform="matrix(0.7457627,0.0,0.0,circle0.6567164,467.339,103.462685)" points="20,10 80,40 40,80" fill="blue" stroke="black" stroke-width="1"/>
} else if ("square".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "rect");
symbolNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2));
symbolNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
symbolNode.setAttribute("width", Integer.toString(symbolSize));
symbolNode.setAttribute("height", Integer.toString(symbolSize));
} else if ("resource".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "rect");
symbolNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2));
symbolNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
symbolNode.setAttribute("width", Integer.toString(symbolSize));
symbolNode.setAttribute("height", Integer.toString(symbolSize));
symbolNode.setAttribute("transform", "rotate(-45 " + Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2) + " " + Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + ")");
symbolNode.setAttribute("stroke-width", "4");
symbolNode.setAttribute("fill", "black");
} else if ("union".equals(symbolType)) {
// DOMUtilities.deepCloneDocument(doc, doc.getImplementation());
// symbolNode = doc.createElementNS(svgNS, "layer");
// Element upperNode = doc.createElementNS(svgNS, "rect");
// Element lowerNode = doc.createElementNS(svgNS, "rect");
// upperNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2));
// upperNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// upperNode.setAttribute("width", Integer.toString(symbolSize));
// upperNode.setAttribute("height", Integer.toString(symbolSize / 3));
// lowerNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2 + (symbolSize / 3) * 2));
// lowerNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// lowerNode.setAttribute("width", Integer.toString(symbolSize));
// lowerNode.setAttribute("height", Integer.toString(symbolSize / 3));
// lowerNode.appendChild(upperNode);
// symbolNode.appendChild(lowerNode);
symbolNode = doc.createElementNS(svgNameSpace, "polyline");
int posXa = currentNode.xPos * hSpacing + hSpacing - symbolSize / 2;
int posYa = currentNode.yPos * vSpacing + vSpacing + symbolSize / 2;
int offsetAmounta = symbolSize / 2;
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("points", (posXa + offsetAmounta * 3) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa - offsetAmounta) + " " + (posXa + offsetAmounta * 3) + "," + (posYa - offsetAmounta));
} else if ("triangle".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "polygon");
int posXt = currentNode.xPos * hSpacing + hSpacing;
int posYt = currentNode.yPos * vSpacing + vSpacing;
int triangleHeight = (int) (Math.sqrt(3) * symbolSize / 2);
symbolNode.setAttribute("points",
(posXt - symbolSize / 2) + "," + (posYt + triangleHeight / 2) + " "
+ (posXt) + "," + (posYt - +triangleHeight / 2) + " "
+ (posXt + symbolSize / 2) + "," + (posYt + triangleHeight / 2));
// case equals:
// symbolNode = doc.createElementNS(svgNS, "rect");
// symbolNode.setAttribute("x", Integer.toString(currentNode.xPos * stepNumber + stepNumber - symbolSize));
// symbolNode.setAttribute("y", Integer.toString(currentNode.yPos * stepNumber + stepNumber));
// symbolNode.setAttribute("width", Integer.toString(symbolSize / 2));
// symbolNode.setAttribute("height", Integer.toString(symbolSize / 2));
// break;
} else {
symbolNode = doc.createElementNS(svgNameSpace, "polyline");
int posX = currentNode.xPos * hSpacing + hSpacing - symbolSize / 2;
int posY = currentNode.yPos * vSpacing + vSpacing + symbolSize / 2;
int offsetAmount = symbolSize / 2;
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("points", (posX - offsetAmount) + "," + (posY - offsetAmount) + " " + (posX + offsetAmount) + "," + (posY + offsetAmount) + " " + (posX) + "," + (posY) + " " + (posX - offsetAmount) + "," + (posY + offsetAmount) + " " + (posX + offsetAmount) + "," + (posY - offsetAmount));
}
// if (currentNode.isEgo) {
// symbolNode.setAttribute("fill", "red");
// } else {
// symbolNode.setAttribute("fill", "none");
if (currentNode.isEgo) {
symbolNode.setAttribute("fill", "black");
} else {
symbolNode.setAttribute("fill", "white");
}
symbolNode.setAttribute("stroke", "black");
symbolNode.setAttribute("stroke-width", "2");
groupNode.appendChild(symbolNode);
////////////////////////////// tspan method appears to fail in batik rendering process unless saved and reloaded ////////////////////////////////////////////////
// Element labelText = doc.createElementNS(svgNS, "text");
//// labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
//// labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// labelText.setAttribute("fill", "black");
// labelText.setAttribute("fill-opacity", "1");
// labelText.setAttribute("stroke-width", "0");
// labelText.setAttribute("font-size", "14px");
//// labelText.setAttribute("text-anchor", "end");
//// labelText.setAttribute("style", "font-size:14px;text-anchor:end;fill:black;fill-opacity:1");
// //labelText.setNodeValue(currentChild.toString());
// //String textWithUni = "\u0041";
// int textSpanCounter = 0;
// int lineSpacing = 10;
// for (String currentTextLable : currentNode.getLabel()) {
// Text textNode = doc.createTextNode(currentTextLable);
// Element tspanElement = doc.createElement("tspan");
// tspanElement.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
// tspanElement.setAttribute("y", Integer.toString((currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + textSpanCounter));
//// tspanElement.setAttribute("y", Integer.toString(textSpanCounter * lineSpacing));
// tspanElement.appendChild(textNode);
// labelText.appendChild(tspanElement);
// textSpanCounter += lineSpacing;
// groupNode.appendChild(labelText);
////////////////////////////// end tspan method appears to fail in batik rendering process ////////////////////////////////////////////////
////////////////////////////// alternate method ////////////////////////////////////////////////
// todo: this method has the draw back that the text is not selectable as a block
int textSpanCounter = 0;
int lineSpacing = 15;
for (String currentTextLable : currentNode.getLabel()) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2 + textSpanCounter));
labelText.setAttribute("fill", "black");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
Text textNode = doc.createTextNode(currentTextLable);
labelText.appendChild(textNode);
textSpanCounter += lineSpacing;
groupNode.appendChild(labelText);
}
////////////////////////////// end alternate method ////////////////////////////////////////////////
((EventTarget) groupNode).addEventListener("mousedown", new EventListener() {
public void handleEvent(Event evt) {
boolean shiftDown = false;
if (evt instanceof DOMMouseEvent) {
shiftDown = ((DOMMouseEvent) evt).getShiftKey();
}
System.out.println("mousedown: " + evt.getCurrentTarget());
currentDraggedElement = ((Element) evt.getCurrentTarget());
preDragCursor = svgCanvas.getCursor();
// get the entityPath
String entityPath = currentDraggedElement.getAttribute("id");
System.out.println("entityPath: " + entityPath);
boolean nodeAlreadySelected = selectedGroupElement.contains(entityPath);
if (!shiftDown) {
System.out.println("Clear selection");
selectedGroupElement.clear();
}
// toggle the highlight
if (nodeAlreadySelected) {
selectedGroupElement.remove(entityPath);
} else {
selectedGroupElement.add(entityPath);
}
addHighlightToGroup();
// update the table selection
if (imdiTableModel != null) {
imdiTableModel.removeAllImdiRows();
try {
for (String currentSelectedPath : selectedGroupElement) {
imdiTableModel.addSingleImdiObject(ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentSelectedPath)));
}
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
}
}, false);
return groupNode;
}
public void drawNodes(GraphData graphDataLocal) {
requiresSave = true;
graphData = graphDataLocal;
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
// Get the root element (the 'svg' element).
Element svgRoot = doc.getDocumentElement();
// todo: set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// int maxTextLength = 0;
// for (GraphDataNode currentNode : graphData.getDataNodes()) {
// if (currentNode.getLabel()[0].length() > maxTextLength) {
// maxTextLength = currentNode.getLabel()[0].length();
int vSpacing = graphPanelSize.getVerticalSpacing(graphData.gridHeight);
// todo: find the real text size from batik
// todo: get the user selected canvas size and adjust the hSpacing and vSpacing to fit
// int hSpacing = maxTextLength * 10 + 100;
int hSpacing = graphPanelSize.getHorizontalSpacing(graphData.gridWidth);
int symbolSize = 15;
int strokeWidth = 2;
// int preferedWidth = graphData.gridWidth * hSpacing + hSpacing * 2;
// int preferedHeight = graphData.gridHeight * vSpacing + vSpacing * 2;
// Set the width and height attributes on the root 'svg' element.
svgRoot.setAttribute("width", Integer.toString(graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
svgRoot.setAttribute("height", Integer.toString(graphPanelSize.getHeight(graphData.gridHeight, vSpacing)));
this.setPreferredSize(new Dimension(graphPanelSize.getHeight(graphData.gridHeight, vSpacing), graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
// create string array to store the selected ego nodes in the dom
ArrayList<String> egoStringArray = new ArrayList<String>();
for (URI currentEgoUri : egoSet) {
egoStringArray.add(currentEgoUri.toASCIIString());
}
// store the selected kin type strings and other data in the dom
// Namespace sNS = Namespace.getNamespace("someNS", "someNamespace");
// Element element = new Element("SomeElement", sNS);
Element kinTypesRecordNode = doc.createElementNS(kinDataNameSpace, "KinDiagramData");
// Element kinTypesRecordNode = doc.createElement(kinDataNameSpace + ":KinDiagramData");
kinTypesRecordNode.setAttribute("xmlns:" + kinDataNameSpace, kinDataNameSpaceLocation); // todo: this surely is not the only nor the best way to st the namespace
storeParameter(kinTypesRecordNode, "EgoList", egoStringArray.toArray(new String[]{}));
storeParameter(kinTypesRecordNode, "KinTypeStrings", kinTypeStrings);
storeParameter(kinTypesRecordNode, "AncestorFields", indexParameters.ancestorFields.getValues());
storeParameter(kinTypesRecordNode, "DecendantFields", indexParameters.decendantFields.getValues());
storeParameter(kinTypesRecordNode, "LabelFields", indexParameters.labelFields.getValues());
storeParameter(kinTypesRecordNode, "SymbolFieldsFields", indexParameters.symbolFieldsFields.getValues());
svgRoot.appendChild(kinTypesRecordNode);
// end store the selected kin type strings and other data in the dom
svgCanvas.setSVGDocument(doc);
// svgCanvas.setDocument(doc);
// int counterTest = 0;
for (GraphDataNode currentNode : graphData.getDataNodes()) {
// set up the mouse listners on the group node
// ((EventTarget) groupNode).addEventListener("mouseover", new EventListener() {
// public void handleEvent(Event evt) {
// System.out.println("OnMouseOverCircleAction: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "green");
// }, false);
// ((EventTarget) groupNode).addEventListener("mouseout", new EventListener() {
// public void handleEvent(Event evt) {
// System.out.println("mouseout: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "none");
// }, false);
// draw links
for (GraphDataNode.NodeRelation graphLinkNode : currentNode.getNodeRelations()) {
if (graphLinkNode.sourceNode.equals(currentNode)) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
Element defsNode = doc.createElementNS(svgNameSpace, "defs");
String lineIdString = currentNode.getEntityPath() + "-" + graphLinkNode.linkedNode.getEntityPath();
// todo: groupNode.setAttribute("id", currentNode.getEntityPath()+ ";"+and the other end);
// set the line end points
int fromX = (currentNode.xPos * hSpacing + hSpacing);
int fromY = (currentNode.yPos * vSpacing + vSpacing);
int toX = (graphLinkNode.linkedNode.xPos * hSpacing + hSpacing);
int toY = (graphLinkNode.linkedNode.yPos * vSpacing + vSpacing);
// set the label position
int labelX = (fromX + toX) / 2;
int labelY = (fromY + toY) / 2;
switch (graphLinkNode.relationLineType) {
case horizontalCurve:
// this case uses the following case
case verticalCurve:
// todo: groupNode.setAttribute("id", );
// System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
//// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
// Element linkLine = doc.createElementNS(svgNS, "line");
// linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("stroke", "black");
// linkLine.setAttribute("stroke-width", "1");
// // Attach the rectangle to the root 'svg' element.
// svgRoot.appendChild(linkLine);
System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
Element linkLine = doc.createElementNS(svgNameSpace, "path");
int fromBezX;
int fromBezY;
int toBezX;
int toBezY;
if (graphLinkNode.relationLineType == GraphDataNode.RelationLineType.verticalCurve) {
fromBezX = fromX;
fromBezY = toY;
toBezX = toX;
toBezY = fromY;
if (currentNode.yPos == graphLinkNode.linkedNode.yPos) {
fromBezX = fromX;
fromBezY = toY - vSpacing / 2;
toBezX = toX;
toBezY = fromY - vSpacing / 2;
// set the label postion and lower it a bit
labelY = toBezY + vSpacing / 3;
;
}
} else {
fromBezX = toX;
fromBezY = fromY;
toBezX = fromX;
toBezY = toY;
if (currentNode.xPos == graphLinkNode.linkedNode.xPos) {
fromBezY = fromY;
fromBezX = toX - hSpacing / 2;
toBezY = toY;
toBezX = fromX - hSpacing / 2;
// set the label postion
labelX = toBezX;
}
}
linkLine.setAttribute("d", "M " + fromX + "," + fromY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + toX + "," + toY);
// linkLine.setAttribute("x1", );
// linkLine.setAttribute("y1", );
// linkLine.setAttribute("x2", );
linkLine.setAttribute("fill", "none");
linkLine.setAttribute("stroke", "blue");
linkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
linkLine.setAttribute("id", lineIdString);
defsNode.appendChild(linkLine);
break;
case square:
// Element squareLinkLine = doc.createElement("line");
// squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("stroke", "grey");
// squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
Element squareLinkLine = doc.createElementNS(svgNameSpace, "polyline");
int midY = (fromY + toY) / 2;
if (toY == fromY) {
// make sure that union lines go below the entities and sibling lines go above
if (graphLinkNode.relationType == GraphDataNode.RelationType.sibling) {
midY = toY - vSpacing / 2;
} else if (graphLinkNode.relationType == GraphDataNode.RelationType.union) {
midY = toY + vSpacing / 2;
}
}
squareLinkLine.setAttribute("points",
fromX + "," + fromY + " "
+ fromX + "," + midY + " "
+ toX + "," + midY + " "
+ toX + "," + toY);
squareLinkLine.setAttribute("fill", "none");
squareLinkLine.setAttribute("stroke", "grey");
squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
squareLinkLine.setAttribute("id", lineIdString);
defsNode.appendChild(squareLinkLine);
break;
}
groupNode.appendChild(defsNode);
Element useNode = doc.createElementNS(svgNameSpace, "use");
useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// useNode.setAttribute("href", "#" + lineIdString);
groupNode.appendChild(useNode);
// add the relation label
if (graphLinkNode.labelString != null) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("text-anchor", "middle");
// labelText.setAttribute("x", Integer.toString(labelX));
// labelText.setAttribute("y", Integer.toString(labelY));
labelText.setAttribute("fill", "blue");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
// labelText.setAttribute("transform", "rotate(45)");
Element textPath = doc.createElementNS(svgNameSpace, "textPath");
textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
textPath.setAttribute("startOffset", "50%");
// textPath.setAttribute("text-anchor", "middle");
Text textNode = doc.createTextNode(graphLinkNode.labelString);
textPath.appendChild(textNode);
labelText.appendChild(textPath);
groupNode.appendChild(labelText);
}
svgRoot.appendChild(groupNode);
}
}
}
// add the entity symbols on top of the links
for (GraphDataNode currentNode : graphData.getDataNodes()) {
svgRoot.appendChild(createEntitySymbol(currentNode, hSpacing, vSpacing, symbolSize));
}
//new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg"));
svgCanvas.revalidate();
// todo: populate this correctly with the available symbols
indexParameters.symbolFieldsFields.setAvailableValues(new String[]{"circle", "triangle", "square", "union"});
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public boolean requiresSave() {
return requiresSave;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package org.antlr.gunit;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import java.io.*;
import java.lang.reflect.*;
public class gUnitExecuter {
public Interp interpreter;
/** If error during execution, store stderr here */
protected String stderr;
protected String stdout;
protected boolean invalidInput; // valid input if current index of tokens = size of tokens - 1
private int numOfTest;
private int numOfSuccess;
private int numOfFailure;
private String title;
private int numOfInvalidInput;
private StringBuffer bufInvalid;
private StringBuffer bufResult;
private String parserName;
private String lexerName;
public gUnitExecuter(Interp interpreter) {
this.interpreter = interpreter;
numOfTest = 0;
numOfSuccess = 0;
numOfFailure = 0;
numOfInvalidInput = 0;
bufInvalid = new StringBuffer();
bufResult = new StringBuffer();
}
public void execTest() throws IOException{
try {
/** Set up appropriate path for parser/lexer if using package */
if (interpreter.header!=null ) {
parserName = interpreter.header+"."+interpreter.grammarName+"Parser";
lexerName = interpreter.header+"."+interpreter.grammarName+"Lexer";
}
else {
parserName = interpreter.grammarName+"Parser";
lexerName = interpreter.grammarName+"Lexer";
}
/*** Start Unit/Functional Testing ***/
if ( interpreter.treeGrammarName!=null ) { // Execute unit test of for tree grammar
title = "executing testsuite for tree grammar:"+interpreter.treeGrammarName+" walks "+parserName;
executeTests(true);
}
else { // Execute unit test of for grammar
title = "executing testsuite for grammar:"+interpreter.grammarName;
executeTests(false);
} // End of exection of unit testing
interpreter.unitTestResult.append("
interpreter.unitTestResult.append(title+" with "+numOfTest+" tests\n");
interpreter.unitTestResult.append("
if( numOfFailure>0 ) {
interpreter.unitTestResult.append(numOfFailure+" failures found:\n");
interpreter.unitTestResult.append(bufResult.toString()+"\n");
}
if( numOfInvalidInput>0 ) {
interpreter.unitTestResult.append(numOfInvalidInput+" invalid inputs found:\n");
interpreter.unitTestResult.append(bufInvalid.toString()+"\n");
}
interpreter.unitTestResult.append("Tests run: "+numOfTest+", "+"Failures: "+numOfFailure+"\n\n");
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private void reportTestHeader(StringBuffer buffer, String rule, String treeRule) {
buffer.append("test" + numOfTest + " (");
if (treeRule != null)
buffer.append(treeRule+" walks ");
buffer.append(rule + ")" + " - " + "\n");
}
// TODO: throw more specific exceptions
private Object runCorrectParser(String parserName, String lexerName, String rule, String treeRule, gUnitTestInput input) throws Exception
{
if (treeRule == null)
return runParser(parserName, lexerName, rule, input);
else
return runTreeParser(parserName, lexerName, rule, treeRule, input);
}
private void executeTests(boolean isTreeTests) throws Exception {
for ( gUnitTestSuite ts: interpreter.ruleTestSuites ) {
String rule = ts.rule;
String treeRule = null;
if (isTreeTests)
treeRule = ts.treeRule;
for ( gUnitTestInput input: ts.testSuites.keySet() ) { // each rule may contain multiple tests
numOfTest++;
// Run parser, and get the return value or stdout or stderr if there is
Object result = runCorrectParser(parserName, lexerName, rule, treeRule, input);
if ( invalidInput==true ) {
numOfInvalidInput++;
reportTestHeader(bufInvalid, rule, treeRule);
bufInvalid.append("invalid input: "+input.testInput+"\n\n");
}
if ( ts.testSuites.get(input).getType()==27 ) { // expected Token: OK
if ( this.stderr==null ) {
numOfSuccess++;
}
else {
numOfFailure++;
reportTestHeader(bufResult, rule, treeRule);
bufResult.append("expected: OK"+"\n");
bufResult.append("actual: FAIL"+"\n\n");
}
}
else if ( ts.testSuites.get(input).getType()==28 ) { // expected Token: FAIL
if ( this.stderr!=null ) {
numOfSuccess++;
}
else {
numOfFailure++;
reportTestHeader(bufResult, rule, treeRule);
bufResult.append("expected: FAIL"+"\n");
bufResult.append("actual: OK"+"\n\n");
}
}
else if ( result==null ) { // prevent comparing null return
numOfFailure++;
reportTestHeader(bufResult, rule, treeRule);
bufResult.append("expected: "+ts.testSuites.get(input).getText()+"\n");
bufResult.append("actual: null\n\n");
}
else if ( ts.testSuites.get(input).getType()==7 ) { // expected Token: RETURN
/** Interpreter only compares the return value as String */
String stringResult = String.valueOf(result);
String expect = ts.testSuites.get(input).getText();
if ( expect.charAt(0)=='"' && expect.charAt(expect.length()-1)=='"' ) {
expect = expect.substring(1, expect.length()-1);
}
if( stringResult.equals(expect) ) {
numOfSuccess++;
}
else {
numOfFailure++;
reportTestHeader(bufResult, rule, treeRule);
bufResult.append("expected: "+expect+"\n");
bufResult.append("actual: "+result+"\n\n");
}
}
else if ( ts.testSuites.get(input).getType()==6 ) { // expected Token: ACTION
numOfFailure++;
reportTestHeader(bufResult, rule, treeRule);
bufResult.append("\t"+"{ACTION} is not supported in the interpreter yet...\n\n");
}
else {
if( result.equals(ts.testSuites.get(input).getText()) ) {
numOfSuccess++;
}
else {
numOfFailure++;
reportTestHeader(bufResult, rule, treeRule);
bufResult.append("expected: "+ts.testSuites.get(input).getText()+"\n");
bufResult.append("actual: "+result+"\n\n");
}
}
}
}
}
protected Object runParser(String parserName, String lexerName, String testRuleName, gUnitTestInput testInput) throws Exception {
CharStream input;
/** Set up ANTLR input stream based on input source, file or String */
if ( testInput.inputIsFile==true ) {
input = new ANTLRFileStream(testInput.testInput);
}
else {
input = new ANTLRStringStream(testInput.testInput);
}
Class lexer = null;
Class parser = null;
try {
/** Use Reflection to create instances of lexer and parser */
lexer = Class.forName(lexerName);
Class[] lexArgTypes = new Class[]{CharStream.class}; // assign type to lexer's args
Constructor lexConstructor = lexer.getConstructor(lexArgTypes);
Object[] lexArgs = new Object[]{input}; // assign value to lexer's args
Object lexObj = lexConstructor.newInstance(lexArgs); // makes new instance of lexer
CommonTokenStream tokens = new CommonTokenStream((Lexer) lexObj);
parser = Class.forName(parserName);
Class[] parArgTypes = new Class[]{TokenStream.class}; // assign type to parser's args
Constructor parConstructor = parser.getConstructor(parArgTypes);
Object[] parArgs = new Object[]{tokens}; // assign value to parser's args
Object parObj = parConstructor.newInstance(parArgs); // makes new instance of parser
Method ruleName = parser.getMethod(testRuleName);
/** Start of I/O Redirecting */
PipedInputStream pipedIn = new PipedInputStream();
PipedOutputStream pipedOut = new PipedOutputStream();
PipedInputStream pipedErrIn = new PipedInputStream();
PipedOutputStream pipedErrOut = new PipedOutputStream();
try {
pipedOut.connect(pipedIn);
pipedErrOut.connect(pipedErrIn);
}
catch(IOException e) {
System.err.println("connection failed...");
System.exit(1);
}
PrintStream console = System.out;
PrintStream consoleErr = System.err;
PrintStream ps = new PrintStream(pipedOut);
PrintStream ps2 = new PrintStream(pipedErrOut);
System.setOut(ps);
System.setErr(ps2);
/** End of redirecting */
/** Invoke grammar rule, and store if there is a return value */
Object ruleReturn = ruleName.invoke(parObj);
String astString = null;
/** If rule has return value, determine if it's an AST */
if ( ruleReturn!=null ) {
/** If return object is instanceof AST, get the toStringTree */
if ( ruleReturn.toString().indexOf(testRuleName+"_return")>0 ) {
try { // NullPointerException may happen here...
Class _return = Class.forName(parserName+"$"+testRuleName+"_return");
Method[] methods = _return.getDeclaredMethods();
for(Method method : methods) {
if ( method.getName().equals("getTree") ) {
Method returnName = _return.getMethod("getTree");
CommonTree tree = (CommonTree) returnName.invoke(ruleReturn);
astString = tree.toStringTree();
}
}
}
catch(Exception e) {
System.err.println(e);
}
}
}
/** Invalid input */
if ( tokens.index()!=tokens.size() ) {
this.invalidInput = true;
}
else {
this.invalidInput = false;
}
StreamVacuum stdoutVacuum = new StreamVacuum(pipedIn);
StreamVacuum stderrVacuum = new StreamVacuum(pipedErrIn);
ps.close();
ps2.close();
System.setOut(console); // Reset standard output
System.setErr(consoleErr); // Reset standard err out
this.stdout = null;
this.stderr = null;
stdoutVacuum.start();
stderrVacuum.start();
stdoutVacuum.join();
stderrVacuum.join();
if ( stderrVacuum.toString().length()>0 ) {
this.stderr = stderrVacuum.toString();
return this.stderr;
}
if ( stdoutVacuum.toString().length()>0 ) {
this.stdout = stdoutVacuum.toString();
}
if ( astString!=null ) { // Return toStringTree of AST
return astString;
}
if ( ruleReturn!=null ) {
return ruleReturn;
}
if ( stderrVacuum.toString().length()==0 && stdoutVacuum.toString().length()==0 ) {
return null;
}
} catch (ClassNotFoundException e) {
e.printStackTrace(); System.exit(1);
} catch (SecurityException e) {
e.printStackTrace(); System.exit(1);
} catch (NoSuchMethodException e) {
e.printStackTrace(); System.exit(1);
} catch (IllegalArgumentException e) {
e.printStackTrace(); System.exit(1);
} catch (InstantiationException e) {
e.printStackTrace(); System.exit(1);
} catch (IllegalAccessException e) {
e.printStackTrace(); System.exit(1);
} catch (InvocationTargetException e) {
e.printStackTrace(); System.exit(1);
} catch (InterruptedException e) {
e.printStackTrace(); System.exit(1);
}
return stdout;
}
protected Object runTreeParser(String parserName, String lexerName, String testRuleName, String testTreeRuleName, gUnitTestInput testInput) throws Exception {
CharStream input;
String treeParserPath;
/** Set up ANTLR input stream based on input source, file or String */
if ( testInput.inputIsFile==true ) {
input = new ANTLRFileStream(testInput.testInput);
}
else {
input = new ANTLRStringStream(testInput.testInput);
}
/** Set up appropriate path for tree parser if using package */
if ( interpreter.header!=null ) {
treeParserPath = interpreter.header+"."+interpreter.treeGrammarName;
}
else {
treeParserPath = interpreter.treeGrammarName;
}
Class lexer = null;
Class parser = null;
Class treeParser = null;
try {
/** Use Reflection to create instances of lexer and parser */
lexer = Class.forName(lexerName);
Class[] lexArgTypes = new Class[]{CharStream.class}; // assign type to lexer's args
Constructor lexConstructor = lexer.getConstructor(lexArgTypes);
Object[] lexArgs = new Object[]{input}; // assign value to lexer's args
Object lexObj = lexConstructor.newInstance(lexArgs); // makes new instance of lexer
CommonTokenStream tokens = new CommonTokenStream((Lexer) lexObj);
parser = Class.forName(parserName);
Class[] parArgTypes = new Class[]{TokenStream.class}; // assign type to parser's args
Constructor parConstructor = parser.getConstructor(parArgTypes);
Object[] parArgs = new Object[]{tokens}; // assign value to parser's args
Object parObj = parConstructor.newInstance(parArgs); // makes new instance of parser
Method ruleName = parser.getMethod(testRuleName);
/** Start of I/O Redirecting */
PipedInputStream pipedIn = new PipedInputStream();
PipedOutputStream pipedOut = new PipedOutputStream();
PipedInputStream pipedErrIn = new PipedInputStream();
PipedOutputStream pipedErrOut = new PipedOutputStream();
try {
pipedOut.connect(pipedIn);
pipedErrOut.connect(pipedErrIn);
}
catch(IOException e) {
System.err.println("connection failed...");
System.exit(1);
}
PrintStream console = System.out;
PrintStream consoleErr = System.err;
PrintStream ps = new PrintStream(pipedOut);
PrintStream ps2 = new PrintStream(pipedErrOut);
System.setOut(ps);
System.setErr(ps2);
/** End of redirecting */
/** Invoke grammar rule, and get the return value */
Object ruleReturn = ruleName.invoke(parObj);
Class _return = Class.forName(parserName+"$"+testRuleName+"_return");
Method returnName = _return.getMethod("getTree");
CommonTree tree = (CommonTree) returnName.invoke(ruleReturn);
// Walk resulting tree; create tree nodes stream first
CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
// AST nodes have payload that point into token stream
nodes.setTokenStream(tokens);
// Create a tree walker attached to the nodes stream
treeParser = Class.forName(treeParserPath);
Class[] treeParArgTypes = new Class[]{TreeNodeStream.class}; // assign type to tree parser's args
Constructor treeParConstructor = treeParser.getConstructor(treeParArgTypes);
Object[] treeParArgs = new Object[]{nodes}; // assign value to tree parser's args
Object treeParObj = treeParConstructor.newInstance(treeParArgs); // makes new instance of tree parser
// Invoke the tree rule, and store the return value if there is
Method treeRuleName = treeParser.getMethod(testTreeRuleName);
Object treeRuleReturn = treeRuleName.invoke(treeParObj);
String astString = null;
/** If tree rule has return value, determine if it's an AST */
if ( treeRuleReturn!=null ) {
/** If return object is instanceof AST, get the toStringTree */
if ( treeRuleReturn.toString().indexOf(testTreeRuleName+"_return")>0 ) {
try { // NullPointerException may happen here...
Class _treeReturn = Class.forName(treeParserPath+"$"+testTreeRuleName+"_return");
Method[] methods = _treeReturn.getDeclaredMethods();
for(Method method : methods) {
if ( method.getName().equals("getTree") ) {
Method treeReturnName = _treeReturn.getMethod("getTree");
CommonTree returnTree = (CommonTree) treeReturnName.invoke(treeRuleReturn);
astString = returnTree.toStringTree();
}
}
}
catch(Exception e) {
System.err.println(e);
}
}
}
/** Invalid input */
if ( tokens.index()!=tokens.size() ) {
this.invalidInput = true;
}
else {
this.invalidInput = false;
}
StreamVacuum stdoutVacuum = new StreamVacuum(pipedIn);
StreamVacuum stderrVacuum = new StreamVacuum(pipedErrIn);
ps.close();
ps2.close();
System.setOut(console); // Reset standard output
System.setErr(consoleErr); // Reset standard err out
this.stdout = null;
this.stderr = null;
stdoutVacuum.start();
stderrVacuum.start();
stdoutVacuum.join();
stderrVacuum.join();
if ( stderrVacuum.toString().length()>0 ) {
this.stderr = stderrVacuum.toString();
return this.stderr;
}
if ( stdoutVacuum.toString().length()>0 ) {
this.stdout = stdoutVacuum.toString();
}
if ( astString!=null ) { // Return toStringTree of AST
return astString;
}
if ( treeRuleReturn!=null ) {
return treeRuleReturn;
}
if ( stderrVacuum.toString().length()==0 && stdoutVacuum.toString().length()==0 ) {
return null;
}
} catch (ClassNotFoundException e) {
e.printStackTrace(); System.exit(1);
} catch (SecurityException e) {
e.printStackTrace(); System.exit(1);
} catch (NoSuchMethodException e) {
e.printStackTrace(); System.exit(1);
} catch (IllegalArgumentException e) {
e.printStackTrace(); System.exit(1);
} catch (InstantiationException e) {
e.printStackTrace(); System.exit(1);
} catch (IllegalAccessException e) {
e.printStackTrace(); System.exit(1);
} catch (InvocationTargetException e) {
e.printStackTrace(); System.exit(1);
} catch (InterruptedException e) {
e.printStackTrace(); System.exit(1);
}
return stdout;
}
public static class StreamVacuum implements Runnable {
StringBuffer buf = new StringBuffer();
BufferedReader in;
Thread sucker;
public StreamVacuum(InputStream in) {
this.in = new BufferedReader( new InputStreamReader(in) );
}
public void start() {
sucker = new Thread(this);
sucker.start();
}
public void run() {
try {
String line = in.readLine();
while (line!=null) {
buf.append(line);
buf.append('\n');
line = in.readLine();
}
}
catch (IOException ioe) {
System.err.println("can't read output from standard (error) output");
}
}
/** wait for the thread to finish */
public void join() throws InterruptedException {
sucker.join();
}
public String toString() {
return buf.toString();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.