answer
stringlengths 17
10.2M
|
|---|
package org.spongepowered.api.data.type;
import org.spongepowered.api.Sponge;
import java.util.function.Supplier;
public final class ArmorTypes {
// SORTFIELDS:ON
public static final Supplier<ArmorType> CHAINMAIL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(ArmorType.class, "CHAINMAIL");
public static final Supplier<ArmorType> DIAMOND = Sponge.getRegistry().getCatalogRegistry().provideSupplier(ArmorType.class, "DIAMOND");
public static final Supplier<ArmorType> GOLD = Sponge.getRegistry().getCatalogRegistry().provideSupplier(ArmorType.class, "GOLD");
public static final Supplier<ArmorType> IRON = Sponge.getRegistry().getCatalogRegistry().provideSupplier(ArmorType.class, "IRON");
public static final Supplier<ArmorType> LEATHER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(ArmorType.class, "LEATHER");
public static final Supplier<ArmorType> TURTLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(ArmorType.class, "TURTLE");
// SORTFIELDS:OFF
// Suppress default constructor to ensure non-instantiability.
private ArmorTypes() {
throw new AssertionError("You should not be attempting to instantiate this class.");
}
}
|
package cn.sevensencond.petmonitor;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import cn.sevensencond.petmonitor.DevicePageActivity.MAP_ID;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.TextOverlay;
import com.baidu.mapapi.map.Symbol.Stroke;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
public class MapActivity extends Activity {
BMapManager mBMapMan = null;
MapView mMapView = null;
MapController mMapController = null;
LocationClient mLocClient;
LocationData locData = null;
public MyLocationListenner myListener = new MyLocationListenner();
MyLocationOverlay myLocationOverlay = null;
// boolean isFirstLoc = true;//
MKSearch mMKSearch = null;
RouteOverlay routeOverlay = null;
// Target Location,
int targetLat = 40057031;
int targetLgt = 116307852;
boolean fenceIn = false;
CircleView circleView = null;
private RelativeLayout mapLocationLayout = null;
private RelativeLayout mapFenceLayout = null;
boolean isCurLocTarget = false;
ImageButton routeButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBMapMan = new BMapManager(getApplication());
mBMapMan.init("MBwMkvhVTIRMlnsqlCeXZybo", null);
// setContentViewBMapManager
setContentView(R.layout.activity_map);
mMapView = (MapView) findViewById(R.id.bmapsView);
// mMapView.setBuiltInZoomControls(true);
// mMapView,
mMapController = mMapView.getController();
// GeoPoint ( * 1E6)
// GeoPoint point =new GeoPoint((int)(39.915* 1E6),(int)(116.404* 1E6));
// mMapController.setCenter(point); //
mMapController.setZoom(14);// zoom
mMKSearch = new MKSearch();
mMKSearch.init(mBMapMan, new MySearchListener());//MKSearchListener
mapLocationLayout = (RelativeLayout)findViewById(R.id.maplocation_layout);
mapFenceLayout = (RelativeLayout)findViewById(R.id.fence_relativelayout_buttons);
Bundle localBundle = getIntent().getBundleExtra("cn.sevensencond.petmonitor.map");
int mapType = localBundle.getInt("cn.sevensencond.petmonitor.mapType", -1);
if (mapType == MAP_ID.TRACK.ordinal()) {
mapLocationLayout.setVisibility(View.VISIBLE);
mapFenceLayout.setVisibility(View.GONE);
addFence();
mLocClient = new LocationClient(this);
locData = new LocationData();
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);// gps
option.setCoorType("bd09ll");
option.setScanSpan(1000);
mLocClient.setLocOption(option);
mLocClient.start();
myLocationOverlay = new MyLocationOverlay(mMapView);
myLocationOverlay.setData(locData);
myLocationOverlay.setMarker(getResources().getDrawable(R.drawable.point1));
mMapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableCompass();
mMapView.refresh();
routeButton = (ImageButton)findViewById(R.id.maplocation_button_route);
ImageButton preLocButton = (ImageButton)findViewById(R.id.maplocation_button_prev);
ImageButton nextLocButton = (ImageButton)findViewById(R.id.maplocation_button_next);
View.OnClickListener locListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (isCurLocTarget) {
locateUser(v);
} else {
locateTarget(v);
}
}
};
preLocButton.setOnClickListener(locListener);
nextLocButton.setOnClickListener(locListener);
addTargetOverlay();
locateTarget(mMapView);
} else if (mapType == MAP_ID.FENCE.ordinal()) {
}
MKMapViewListener mapViewListener = new MKMapViewListener() {
@Override
public void onMapMoveFinish() {
}
@Override
public void onClickMapPoi(MapPoi arg0) {
}
@Override
public void onGetCurrentMap(Bitmap b) {
//MapView.getCurrentMap().
}
@Override
public void onMapAnimationFinish() {
/**
* : animationTo()
*/
}
@Override
public void onMapLoadFinish() {
int mapWidth = mMapView.getWidth();
int mapHeight = mMapView.getHeight();
Log.d("MapView", "width is "+mapWidth+" height is "+mapHeight);
// Point centerPoint = mMapView.getCenterPixel();
// addCircleView(centerPoint, mapWidth, mapHeight);
}
};
mMapView.regMapViewListener(mBMapMan, mapViewListener);
}
public void addFence(){
GraphicsOverlay graphicsOverlay = new GraphicsOverlay(mMapView);
mMapView.getOverlays().add(graphicsOverlay);
// graphicsOverlay.setData(drawPoint());
// graphicsOverlay.setData(drawLine());
// graphicsOverlay.setData(drawPolygon());
int radius = 2500;
double lat = targetLat/1E6, lon = targetLgt/1E6;
boolean isFenceIn = true;
graphicsOverlay.setData(drawCircle(radius, lat, lon, isFenceIn));
TextOverlay textOverlay = new TextOverlay(mMapView);
mMapView.getOverlays().add(textOverlay);
// textOverlay.addText(drawText());
mMapView.refresh();
}
/**
*
* @return
*/
public Graphic drawCircle(int mRadius, double mLat, double mLon, boolean isFenceIn) {
int lat = (int) (mLat*1E6);
int lon = (int) (mLon*1E6);
GeoPoint centerPoint = new GeoPoint(lat, lon);
Geometry circleGeometry = new Geometry();
circleGeometry.setCircle(centerPoint, mRadius);
Symbol circleSymbol = new Symbol();
Symbol.Color circleColor, translucentCircleColor;
if (isFenceIn) {
circleColor = circleSymbol.new Color(0xFF0000FF);
translucentCircleColor = circleSymbol.new Color(0x200000FF);
} else {
circleColor = circleSymbol.new Color(0xFFFF0000);
translucentCircleColor = circleSymbol.new Color(0x20FF0000);
}
circleSymbol.setSurface(translucentCircleColor, 1, 3, new Stroke(3, circleColor));
//Graphic
Graphic circleGraphic = new Graphic(circleGeometry, circleSymbol);
return circleGraphic;
}
public class MySearchListener implements MKSearchListener {
@Override
public void onGetAddrResult(MKAddrInfo result, int iError) {
}
@Override
public void onGetDrivingRouteResult(MKDrivingRouteResult result, int iError) {
if (result == null) {
return;
}
routeOverlay = new RouteOverlay(MapActivity.this, mMapView);
routeOverlay.setData(result.getPlan(0).getRoute(0));
mMapView.getOverlays().add(routeOverlay);
mMapView.refresh();
}
@Override
public void onGetPoiResult(MKPoiResult result, int type, int iError) {
//poi
}
@Override
public void onGetTransitRouteResult(MKTransitRouteResult result, int iError) {
}
@Override
public void onGetWalkingRouteResult(MKWalkingRouteResult result, int iError) {
}
@Override
public void onGetBusDetailResult(MKBusLineResult result, int iError) {
}
@Override
public void onGetSuggestionResult(MKSuggestionResult result, int iError) {
}
@Override
public void onGetShareUrlResult(MKShareUrlResult result , int type, int error) {
}
@Override
public void onGetPoiDetailSearchResult(int arg0, int arg1) {
// TODO Auto-generated method stub
}
}
public class CircleView extends View {
// default center pixel coordinate and default radius
int x = 240;
int y = 378;
int r = 200;
int color = Color.RED;
Paint strokePaint, fillPaint;
public CircleView(Context context) {
super(context);
strokePaint = new Paint();
fillPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// canvas.drawColor(Color.CYAN);
// smooths
strokePaint.setAntiAlias(true);
strokePaint.setColor(color);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(3f);
canvas.drawCircle(x, y, r, strokePaint);
fillPaint.setAntiAlias(true);
fillPaint.setColor(color);
fillPaint.setStyle(Paint.Style.FILL);
fillPaint.setAlpha(0x20);
canvas.drawCircle(x, y, r, fillPaint);
}
public void setRadius(int r) {
this.r = r;
}
public void setCenterPixel(Point pt) {
this.x = pt.x;
this.y = pt.y;
}
public void setColor(int color) {
this.color = color;
}
}
/**
* SDK
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null)
return;
locData.latitude = location.getLatitude();
locData.longitude = location.getLongitude();
// accuracy0
locData.accuracy = location.getRadius();
// locData, SDK
locData.direction = location.getDerect();
myLocationOverlay.setData(locData);
mMapView.refresh();
// if (isFirstLoc) {
// Log.d("LocationOverlay", "receive location, animate to it");
// locateUser(mMapView);
//// mMapController.animateTo(new GeoPoint(
//// (int) (locData.latitude * 1e6),
//// (int) (locData.longitude * 1e6)));
// // myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);
// isFirstLoc = false;
}
public void onReceivePoi(BDLocation poiLocation) {
if (poiLocation == null) {
return;
}
}
}
public void addCircleView(Point centerPoint, int minWidth, int minHeight) {
circleView = new CircleView(getApplicationContext());
circleView.setMinimumWidth(minWidth);
circleView.setMinimumHeight(minHeight);
circleView.setCenterPixel(centerPoint);
circleView.setRadius((int)(minWidth*0.9/2));
circleView.setColor(Color.RED);
MapView.LayoutParams layoutParam = new MapView.LayoutParams(
// ,ViewGroup.LayoutParams
MapView.LayoutParams.WRAP_CONTENT,
// ,ViewGroup.LayoutParams
MapView.LayoutParams.WRAP_CONTENT,
0, 0,
MapView.LayoutParams.TOP);
// ViewMapView
mMapView.addView(circleView, layoutParam);
}
public void addTargetOverlay() {
//overlay
Drawable mark= getResources().getDrawable(R.drawable.point2);
//OverlayItemOverlay
OverlayItem item1 = new OverlayItem(new GeoPoint(targetLat, targetLgt),"item1","item1");
item1.setAnchor(OverlayItem.ALING_CENTER);
//IteminizedOverlay
ItemizedOverlay<OverlayItem> itemOverlay = new ItemizedOverlay<OverlayItem>(mark, mMapView);
//IteminizedOverlayMapView
mMapView.getOverlays().add(itemOverlay);
//overlay, OverlayaddItem(List<OverlayItem>)
itemOverlay.addItem(item1);
mMapView.refresh();
//overlay .
//itemOverlay.removeItem(itemOverlay.getItem(0));
//mMapView.refresh();
//overlay
// itemOverlay.removeAll();
// mMapView.refresh();
}
public void locateUser(View view) {
Log.d("ClickButton", "Click lacate user button");
mMapController.animateTo(new GeoPoint(
(int) (locData.latitude * 1e6),
(int) (locData.longitude * 1e6)));
isCurLocTarget = false;
routeButton.setEnabled(false);
}
public void locateTarget(View view) {
Log.d("ClickButton", "Click lacate target button");
mMapController.animateTo(new GeoPoint(targetLat, targetLgt));
isCurLocTarget = true;
routeButton.setEnabled(true);
}
public void handleRoute(View view) {
Log.d("ClickButton", "Click handle route button");
if (routeOverlay != null) {
mMapView.getOverlays().remove(routeOverlay);
mMapView.refresh();
routeOverlay = null;
return;
}
MKPlanNode start = new MKPlanNode();
start.pt = new GeoPoint((int) (locData.latitude * 1E6), (int) (locData.longitude * 1E6));
MKPlanNode end = new MKPlanNode();
end.pt = new GeoPoint(targetLat, targetLgt);
mMKSearch.setDrivingPolicy(MKSearch.ECAR_TIME_FIRST);
mMKSearch.drivingSearch(null, start, null, end);
}
public void fenceInOut(View view) {
Log.d("ClickButton", "Click fenceInOut button");
int color = (fenceIn)? Color.BLUE : Color.RED;
circleView.setColor(color);
circleView.invalidate();
ImageButton imageButton = (ImageButton)findViewById(R.id.fence_button_fenceinout);
// imageButton.setBackground(getResources().getDrawable(R.drawable.fenceout));
int imageRrc = (fenceIn)? R.drawable.fenceout: R.drawable.fencein;
imageButton.setImageResource(imageRrc);
fenceIn = !fenceIn;
}
public void goBack(View view) {
finish();
}
@Override
protected void onDestroy() {
mMapView.destroy();
if (mBMapMan != null) {
mBMapMan.destroy();
mBMapMan = null;
}
super.onDestroy();
}
@Override
protected void onPause() {
mMapView.onPause();
if (mBMapMan != null) {
mBMapMan.stop();
}
super.onPause();
}
@Override
protected void onResume() {
mMapView.onResume();
if (mBMapMan != null) {
mBMapMan.start();
// onResume
if (mMKSearch != null) {
mMKSearch.init(mBMapMan, new MySearchListener());
}
}
super.onResume();
}
}
|
package yokohama.unit.translator;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.bcel.Constants;
import org.apache.bcel.Repository;
import org.apache.bcel.generic.ATHROW;
import org.apache.bcel.generic.AnnotationEntryGen;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.LocalVariableGen;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
import org.apache.bcel.util.ClassPath;
import org.apache.bcel.util.SyntheticRepository;
import org.apache.commons.collections4.ListUtils;
import yokohama.unit.ast.Kind;
import yokohama.unit.ast_junit.Annotation;
import yokohama.unit.ast_junit.ArrayExpr;
import yokohama.unit.ast_junit.CatchClause;
import yokohama.unit.ast_junit.ClassDecl;
import yokohama.unit.ast_junit.ClassType;
import yokohama.unit.ast_junit.CompilationUnit;
import yokohama.unit.ast_junit.InvokeStaticVoidStatement;
import yokohama.unit.ast_junit.InvokeVoidStatement;
import yokohama.unit.ast_junit.IsStatement;
import yokohama.unit.ast_junit.Method;
import yokohama.unit.ast_junit.ReturnStatement;
import yokohama.unit.ast_junit.Statement;
import yokohama.unit.ast_junit.ThrowStatement;
import yokohama.unit.util.Sym;
import yokohama.unit.ast_junit.VarDeclVisitor;
import yokohama.unit.ast_junit.VarInitStatement;
import yokohama.unit.position.ErrorMessage;
import yokohama.unit.position.Span;
import yokohama.unit.util.Pair;
public class BcelJUnitAstCompiler implements JUnitAstCompiler {
public static class CaughtExceptionVarVisitor {
public static List<Pair<yokohama.unit.ast_junit.Type, String>> sortedSet(Stream<Pair<yokohama.unit.ast_junit.Type, String>> i) {
return i.collect(Collectors.toSet())
.stream()
.sorted((o1, o2) -> o1.getSecond().compareTo(o2.getSecond()))
.collect(Collectors.toList());
}
public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitTestMethod(Method method) {
return visitStatements(method.getStatements());
}
public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitStatements(List<Statement> statements) {
return statements.stream().flatMap(this::visitStatement);
}
public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitStatement(Statement statement) {
return statement.accept(
isStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(),
varInitStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(),
tryStatement ->
Stream.concat(
visitStatements(tryStatement.getTryStatements()),
Stream.concat(
tryStatement.getCatchClauses().stream().flatMap(this::visitCatchClause),
visitStatements(tryStatement.getFinallyStatements()))),
throwStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(),
ifStatement ->
Stream.concat(
visitStatements(ifStatement.getThen()),
visitStatements(ifStatement.getOtherwise())),
returnStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(),
invokeVoidStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(),
invokeStaticVoidStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty());
}
public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitCatchClause(CatchClause catchClause) {
return Stream.concat(
Stream.of(
Pair.of(
catchClause.getClassType().toType(),
catchClause.getVar().getName())),
visitStatements(catchClause.getStatements()));
}
}
@Override
public List<ErrorMessage> compile(
Path docyPath,
CompilationUnit ast,
String className,
String packageName,
List<String> classPath,
Optional<Path> dest,
List<String> javacArgs) {
String joinedCp =
classPath.stream().collect(Collectors.joining(File.pathSeparator));
Repository.setRepository(
SyntheticRepository.getInstance(new ClassPath(joinedCp)));
for (ClassDecl classDecl : ast.getClassDecls()) {
Optional<ClassType> extended = classDecl.getExtended();
List<ClassType> implemented = classDecl.getImplemented();
ClassGen cg = new ClassGen(
packageName.equals("") ? classDecl.getName() : packageName + "." + classDecl.getName(),
extended.isPresent()
? extended.get().getClass().getCanonicalName()
: "java.lang.Object",
docyPath.getFileName().toString(), // source file name
Constants.ACC_PUBLIC | Constants.ACC_SUPER,
implemented.stream()
.map(ClassType::getClazz)
.map(Class::getCanonicalName)
.collect(Collectors.toList())
.toArray(new String[]{}));
// set class file version to Java 1.5
cg.setMajor(49);
cg.setMinor(0);
ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool
cg.addEmptyConstructor(Constants.ACC_PUBLIC);
JUnitAstVisitor visitor = new JUnitAstVisitor(
docyPath,
ast,
className,
packageName,
classPath,
dest,
javacArgs);
for (Method method : classDecl.getMethods()) {
visitor.visitTestMethod(method, cg, cp);
}
try {
Path classFilePath =
TranslatorUtils.makeClassFilePath(dest, packageName, classDecl.getName(), ".class");
cg.getJavaClass().dump(classFilePath.toFile());
Repository.getRepository().storeClass(cg.getJavaClass());
} catch(IOException e) {
System.err.println(e);
}
}
return Collections.emptyList();
}
@AllArgsConstructor
public static class JUnitAstVisitor {
Path docyPath;
CompilationUnit ast;
String className;
String packageName;
List<String> classPath;
Optional<Path> dest;
List<String> javacArgs;
private void visitTestMethod(Method method, ClassGen cg, ConstantPoolGen cp) {
InstructionList il = new InstructionList();
MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, // access flags
method.getReturnType().isPresent()
? typeOf(method.getReturnType().get())
: Type.VOID,
method.getArgs().stream()
.map(Pair::getFirst)
.map(JUnitAstVisitor::typeOf)
.collect(Collectors.toList()).toArray(new Type[]{}),
method.getArgs().stream()
.map(Pair::getSecond)
.collect(Collectors.toList()).toArray(new String[]{}),
method.getName(),
cg.getClassName(),
il, cp);
for (Annotation annotation : method.getAnnotations()) {
AnnotationEntryGen ag = new AnnotationEntryGen(
new ObjectType(annotation.getClazz().getTypeName()),
Arrays.asList(),
true,
cp);
mg.addAnnotationEntry(ag);
}
InstructionFactory factory = new InstructionFactory(cg);
Map<String, LocalVariableGen> locals = new HashMap<>();
List<Pair<yokohama.unit.ast_junit.Type, String>> args = method.getArgs();
List<Pair<yokohama.unit.ast_junit.Type, String>> varDecls =
VarDeclVisitor.sortedSet(new VarDeclVisitor().visitMethod(method));
List<Pair<yokohama.unit.ast_junit.Type, String>> caughtExVars =
CaughtExceptionVarVisitor.sortedSet(new CaughtExceptionVarVisitor().visitTestMethod(method));
for (Pair<yokohama.unit.ast_junit.Type,String> pair :
ListUtils.union(varDecls, caughtExVars)) {
yokohama.unit.ast_junit.Type type = pair.getFirst();
String name = pair.getSecond();
if (locals.containsKey(name))
throw new RuntimeException("duplicate local variable: " + name);
LocalVariableGen lv = mg.addLocalVariable(name, typeOf(type), null, null);
locals.put(name, lv);
}
// populate locals again, since method arguments are not there yet
for (LocalVariableGen lv : mg.getLocalVariables()) {
String name = lv.getName();
locals.put(name, lv);
}
for (Statement statement : method.getStatements()) {
visitStatement(statement, locals, mg, il, factory, cp);
}
if (!method.getReturnType().isPresent()) {
il.append(InstructionConstants.RETURN);
}
mg.setMaxStack();
cg.addMethod(mg.getMethod());
il.dispose();
}
private void visitStatement(
Statement statement,
Map<String, LocalVariableGen> locals,
MethodGen mg,
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
statement.<Void>accept(
isStatement -> {
visitIsStatement(isStatement, locals, mg, il, factory, cp);
return null;
},
varInitStatement -> {
visitVarInitStatement(varInitStatement, locals, mg, il, factory, cp);
return null;
},
tryStatement -> {
InstructionHandle startTry = il.append(InstructionFactory.NOP);
for (Statement s : tryStatement.getTryStatements()) {
visitStatement(s, locals, mg, il, factory, cp);
}
InstructionHandle endTry = il.append(InstructionFactory.NOP);
BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null);
il.append(goto_);
List<BranchInstruction> catchExits = new ArrayList<>();
for (CatchClause catchClause : tryStatement.getCatchClauses()) {
LocalVariableGen ex = locals.get(catchClause.getVar().getName());
InstructionHandle startCatch = il.append(
InstructionFactory.createStore(ex.getType(), ex.getIndex()));
mg.addExceptionHandler(
startTry,
endTry,
startCatch,
(ObjectType)typeOf(catchClause.getClassType().toType()));
for (Statement s : catchClause.getStatements()) {
this.visitStatement(s, locals, mg, il, factory, cp);
}
BranchInstruction exitCatch = InstructionFactory.createBranchInstruction(Constants.GOTO, null);
il.append(exitCatch);
catchExits.add(exitCatch);
}
InstructionHandle startFinally = il.append(InstructionFactory.NOP);
for (Statement s : tryStatement.getFinallyStatements()) {
visitStatement(s, locals, mg, il, factory, cp);
}
goto_.setTarget(startFinally);
for (BranchInstruction bi : catchExits) {
bi.setTarget(startFinally);
}
return null;
},
throwStatement -> {
visitThrowStatement(throwStatement, locals, mg, il, factory, cp);
return null;
},
ifStatement -> {
LocalVariableGen lv = locals.get(ifStatement.getCond().getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
BranchInstruction ifeq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
il.append(ifeq);
// then
for (Statement thenStatement : ifStatement.getThen()) {
visitStatement(thenStatement, locals, mg, il, factory, cp);
}
BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null);
il.append(goto_);
// else
InstructionHandle else_ = il.append(InstructionFactory.NOP);
for (Statement elseStatement : ifStatement.getOtherwise()) {
visitStatement(elseStatement, locals, mg, il, factory, cp);
}
InstructionHandle fi = il.append(InstructionFactory.NOP);
// tie the knot
ifeq.setTarget(else_);
goto_.setTarget(fi);
return null;
},
returnStatement -> {
visitReturnStatement(returnStatement, locals, il, factory, cp);
return null;
},
invokeVoidStatement -> {
visitInvokeVoidStatement(invokeVoidStatement, locals, mg, il, factory, cp);
return null;
},
invokeStaticVoidStatement -> {
visitInvokeStaticVoidStatement(invokeStaticVoidStatement, locals, mg, il, factory, cp);
return null;
});
}
private void visitIsStatement(
IsStatement isStatement,
Map<String, LocalVariableGen> locals,
MethodGen mg,
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
LocalVariableGen message = locals.get(isStatement.getMessage().getName());
LocalVariableGen subject = locals.get(isStatement.getSubject().getName());
LocalVariableGen complement = locals.get(isStatement.getComplement().getName());
InstructionHandle ih =
il.append(InstructionFactory.createLoad(message.getType(), message.getIndex()));
addLineNumber(mg, ih, isStatement.getSpan());
il.append(InstructionFactory.createLoad(subject.getType(), subject.getIndex()));
il.append(InstructionFactory.createLoad(complement.getType(), complement.getIndex()));
il.append(
factory.createInvoke(
"org.junit.Assert",
"assertThat",
Type.VOID,
new Type[] { Type.STRING, Type.OBJECT, new ObjectType("org.hamcrest.Matcher") },
Constants.INVOKESTATIC));
}
@SneakyThrows(ClassNotFoundException.class)
private void visitVarInitStatement(
VarInitStatement varInitStatement,
Map<String, LocalVariableGen> locals,
MethodGen mg,
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
InstructionHandle ih = il.append(InstructionFactory.NOP);
addLineNumber(mg, ih, varInitStatement.getSpan());
LocalVariableGen var = locals.get(varInitStatement.getVar().getName());
Type type = typeOf(varInitStatement.getType());
Type fromType = varInitStatement.getValue().<Type>accept(varExpr -> {
LocalVariableGen from = locals.get(varExpr.getVar().getName());
il.append(InstructionFactory.createLoad(from.getType(), from.getIndex()));
return from.getType();
},
instanceOfMatcherExpr -> {
il.append(new PUSH(cp, new ObjectType(instanceOfMatcherExpr.getClazz().getTypeName())));
il.append(factory.createInvoke(
"org.hamcrest.CoreMatchers",
"instanceOf",
new ObjectType("org.hamcrest.Matcher"),
new Type[] { new ObjectType("java.lang.Class") },
Constants.INVOKESTATIC));
return new ObjectType("org.hamcrest.Matcher");
},
nullValueMatcherExpr -> {
il.append(factory.createInvoke(
"org.hamcrest.CoreMatchers",
"nullValue",
new ObjectType("org.hamcrest.Matcher"),
Type.NO_ARGS,
Constants.INVOKESTATIC));
return new ObjectType("org.hamcrest.Matcher");
},
equalToMatcherExpr -> {
Sym operand = equalToMatcherExpr.getOperand();
LocalVariableGen lv = locals.get(operand.getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
il.append(factory.createInvoke(
"org.hamcrest.CoreMatchers",
"is",
new ObjectType("org.hamcrest.Matcher"),
new Type[] { lv.getType() },
Constants.INVOKESTATIC));
return new ObjectType("org.hamcrest.Matcher");
},
regExpMatcherExpr -> {
il.append(new PUSH(cp, regExpMatcherExpr.getPattern()));
il.append(factory.createInvoke(
"com.jcabi.matchers.RegexMatchers",
"containsPattern",
new ObjectType("org.hamcrest.Matcher"),
new Type[] { Type.STRING },
Constants.INVOKESTATIC));
return new ObjectType("org.hamcrest.Matcher");
},
newExpr -> {
il.append(factory.createNew(newExpr.getType()));
il.append(InstructionConstants.DUP);
// push arguments
for (Sym arg : newExpr.getArgs()) {
LocalVariableGen lv = locals.get(arg.getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
}
il.append(factory.createInvoke(newExpr.getType(),
"<init>",
Type.VOID,
newExpr.getArgTypes().stream()
.map(JUnitAstVisitor::typeOf)
.collect(Collectors.toList())
.toArray(new Type[]{}),
Constants.INVOKESPECIAL));
return new ObjectType(newExpr.getType());
},
strLitExpr -> {
il.append(new PUSH(cp, strLitExpr.getText()));
return Type.STRING;
},
nullExpr -> {
il.append(InstructionConstants.ACONST_NULL);
return Type.NULL;
},
invokeExpr -> {
Type returnType = typeOf(invokeExpr.getReturnType());
// first push target object
LocalVariableGen object = locals.get(invokeExpr.getObject().getName());
il.append(InstructionFactory.createLoad(object.getType(), object.getIndex()));
// push arguments
for (Sym arg : invokeExpr.getArgs()) {
LocalVariableGen lv = locals.get(arg.getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
}
// then call method
il.append(factory.createInvoke(invokeExpr.getClassType().getTypeName(),
invokeExpr.getMethodName(),
returnType,
invokeExpr.getArgTypes().stream()
.map(JUnitAstVisitor::typeOf)
.collect(Collectors.toList())
.toArray(new Type[]{}),
invokeExpr.getClassType().isInterface()
? Constants.INVOKEINTERFACE
: Constants.INVOKEVIRTUAL));
return returnType;
},
invokeStaticExpr -> {
Type returnType = typeOf(invokeStaticExpr.getReturnType());
for (Sym arg : invokeStaticExpr.getArgs()) {
LocalVariableGen lv = locals.get(arg.getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
}
il.append(factory.createInvoke(invokeStaticExpr.getClazz().getTypeName(),
invokeStaticExpr.getMethodName(),
returnType,
invokeStaticExpr.getArgTypes().stream()
.map(JUnitAstVisitor::typeOf)
.collect(Collectors.toList())
.toArray(new Type[]{}),
Constants.INVOKESTATIC));
return returnType;
},
fieldStaticExpr -> {
Type fieldType = typeOf(fieldStaticExpr.getFieldType());
il.append(factory.createGetStatic(
fieldStaticExpr.getClazz().getTypeName(),
fieldStaticExpr.getFieldName(),
fieldType));
return fieldType;
},
intLitExpr -> {
il.append(new PUSH(cp, intLitExpr.getValue()));
return Type.INT;
},
longLitExpr -> {
il.append(new PUSH(cp, longLitExpr.getValue()));
return Type.LONG;
},
floatLitExpr -> {
il.append(new PUSH(cp, floatLitExpr.getValue()));
return Type.FLOAT;
},
doubleLitExpr -> {
il.append(new PUSH(cp, doubleLitExpr.getValue()));
return Type.DOUBLE;
},
booleanLitExpr -> {
il.append(new PUSH(cp, booleanLitExpr.getValue()));
return Type.BOOLEAN;
},
charLitExpr -> {
il.append(new PUSH(cp, new Character(charLitExpr.getValue())));
return Type.CHAR;
},
classLitExpr -> {
yokohama.unit.ast_junit.Type type_ = classLitExpr.getType();
il.append(new PUSH(cp, new ObjectType(
type_.getDims() > 0
/* this is strange since BCEL has ArrayType apart from ObjectType,
but there is no PUSH constructor in BCEL which takes ArrayType. */
? type_.getFieldDescriptor()
: type_.getTypeName())));
return Type.CLASS;
},
equalOpExpr -> {
LocalVariableGen lhs = locals.get(equalOpExpr.getLhs().getName());
il.append(InstructionFactory.createLoad(lhs.getType(), lhs.getIndex()));
LocalVariableGen rhs = locals.get(equalOpExpr.getRhs().getName());
il.append(InstructionFactory.createLoad(rhs.getType(), rhs.getIndex()));
BranchInstruction if_acmpne = InstructionFactory.createBranchInstruction(Constants.IF_ACMPNE, null);
il.append(if_acmpne);
// then
il.append(new PUSH(cp, true));
BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null);
il.append(goto_);
// else
InstructionHandle else_ = il.append(new PUSH(cp, false));
InstructionHandle endIf = il.append(InstructionFactory.NOP);
// tie the knot
if_acmpne.setTarget(else_);
goto_.setTarget(endIf);
return Type.BOOLEAN;
},
arrayExpr -> this.visitArrayExpr(arrayExpr, locals, il, factory, cp),
thisClassExpr -> {
il.append(new PUSH(cp, new ObjectType(packageName + "." + className)));
return Type.CLASS;
});
if (fromType instanceof ReferenceType && type instanceof ReferenceType) {
ReferenceType fromType_ = (ReferenceType)fromType;
ReferenceType type_ = (ReferenceType)type;
if (!fromType_.isAssignmentCompatibleWith(type_)) {
il.append(factory.createCheckCast(type_));
}
}
il.append(InstructionFactory.createStore(var.getType(), var.getIndex()));
}
private Type visitArrayExpr(
ArrayExpr arrayExpr,
Map<String, LocalVariableGen> locals,
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
Type componentType = typeOf(arrayExpr.getType().getNonArrayType().toType());
List<Sym> contents = arrayExpr.getContents();
il.append(new PUSH(cp, contents.size()));
il.append(factory.createNewArray(
componentType,
(short)arrayExpr.getType().getDims()));
for (int i = 0; i < contents.size(); i++) {
il.append(InstructionConstants.DUP);
Sym content = contents.get(i);
LocalVariableGen lv = locals.get(content.getName());
il.append(new PUSH(cp, i));
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
il.append(InstructionFactory.createArrayStore(componentType));
}
return typeOf(arrayExpr.getType());
}
private void visitThrowStatement(
ThrowStatement throwStatement,
Map<String, LocalVariableGen> locals,
MethodGen mg, InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
LocalVariableGen lv = locals.get(throwStatement.getE().getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
il.append(new ATHROW());
}
private void visitReturnStatement(
ReturnStatement returnStatement,
Map<String, LocalVariableGen> locals,
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
LocalVariableGen lv = locals.get(returnStatement.getReturned().getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
il.append(InstructionFactory.createReturn(lv.getType()));
}
static Type typeOf(yokohama.unit.ast_junit.Type type) {
int dims = type.getDims();
if (dims == 0) {
return type.getNonArrayType().accept(
primitiveType -> {
Kind kind = primitiveType.getKind();
switch (kind) {
case BOOLEAN: return Type.BOOLEAN;
case BYTE: return Type.BYTE;
case SHORT: return Type.SHORT;
case INT: return Type.INT;
case LONG: return Type.LONG;
case CHAR: return Type.CHAR;
case FLOAT: return Type.FLOAT;
case DOUBLE: return Type.DOUBLE;
}
throw new RuntimeException("should not reach here");
},
classType -> new ObjectType(classType.getTypeName()));
} else {
return new ArrayType(
typeOf(new yokohama.unit.ast_junit.Type(type.getNonArrayType() , 0)),
dims);
}
}
private void visitInvokeVoidStatement(
InvokeVoidStatement invokeVoidStatement,
Map<String, LocalVariableGen> locals,
MethodGen mg,
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
// first push target object
LocalVariableGen object = locals.get(invokeVoidStatement.getObject().getName());
InstructionHandle ih =
il.append(InstructionFactory.createLoad(object.getType(), object.getIndex()));
addLineNumber(mg, ih, invokeVoidStatement.getSpan());
// push arguments
for (Sym arg : invokeVoidStatement.getArgs()) {
LocalVariableGen lv = locals.get(arg.getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
}
// then call method
il.append(factory.createInvoke(invokeVoidStatement.getClassType().getTypeName(),
invokeVoidStatement.getMethodName(),
Type.VOID,
invokeVoidStatement.getArgTypes().stream()
.map(JUnitAstVisitor::typeOf)
.collect(Collectors.toList())
.toArray(new Type[]{}),
invokeVoidStatement.getClassType().isInterface()
? Constants.INVOKEINTERFACE
: Constants.INVOKEVIRTUAL));
}
private void visitInvokeStaticVoidStatement(
InvokeStaticVoidStatement invokeStaticVoidStatement,
Map<String, LocalVariableGen> locals,
MethodGen mg,
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp) {
InstructionHandle ih = il.append(InstructionFactory.NOP);
addLineNumber(mg, ih, invokeStaticVoidStatement.getSpan());
for (Sym arg : invokeStaticVoidStatement.getArgs()) {
LocalVariableGen lv = locals.get(arg.getName());
il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex()));
}
il.append(factory.createInvoke(invokeStaticVoidStatement.getClazz().getTypeName(),
invokeStaticVoidStatement.getMethodName(),
Type.VOID,
invokeStaticVoidStatement.getArgTypes().stream()
.map(JUnitAstVisitor::typeOf)
.collect(Collectors.toList())
.toArray(new Type[]{}),
Constants.INVOKESTATIC));
}
private void addLineNumber(MethodGen mg, InstructionHandle ih, Span span) {
int line = span.getStart().getLine();
if (line > -1) {
mg.addLineNumber(ih, line);
}
}
}
}
|
package com.jme3.asset.plugins;
import com.jme3.asset.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>UrlLocator</code> is a locator that combines a root URL
* and the given path in the AssetKey to construct a new URL
* that allows locating the asset.
* @author Kirill Vainer
*/
public class UrlLocator implements AssetLocator {
private static final Logger logger = Logger.getLogger(UrlLocator.class.getName());
private URL root;
private static class UrlAssetInfo extends AssetInfo {
private InputStream in;
public UrlAssetInfo(AssetManager manager, AssetKey key, InputStream in){
super(manager, key);
this.in = in;
}
@Override
public InputStream openStream() {
return in;
}
}
public void setRootPath(String rootPath) {
try {
this.root = new URL(rootPath);
} catch (MalformedURLException ex) {
throw new IllegalArgumentException("Invalid rootUrl specified", ex);
}
}
public AssetInfo locate(AssetManager manager, AssetKey key) {
String name = key.getName();
try{
URL url = new URL(root, name);
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(false);
InputStream in;
try {
in = conn.getInputStream();
if (in == null)
return null;
} catch (FileNotFoundException ex){
return null;
}
return new UrlAssetInfo(manager, key, in);
}catch (IOException ex){
logger.log(Level.WARNING, "Error while locating " + name, ex);
return null;
}
}
}
|
package com.treasure_data.jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.simple.JSONValue;
import com.treasure_data.client.ClientException;
import com.treasure_data.jdbc.command.ClientAPI;
import com.treasure_data.jdbc.model.TDColumn;
import com.treasure_data.jdbc.model.TDDataType;
import com.treasure_data.jdbc.model.TDDatabase;
import com.treasure_data.jdbc.model.TDImportedKey;
import com.treasure_data.jdbc.model.TDTable;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.ListDatabasesRequest;
import com.treasure_data.model.Table;
import com.treasure_data.model.TableSummary;
public class TDDatabaseMetaData implements DatabaseMetaData, Constants {
private ClientAPI api;
private Database database;
public TDDatabaseMetaData(ClientAPI api) {
this.api = api;
}
public TDDatabaseMetaData(Database database, ClientAPI api) {
this.api = api;
this.database = database;
}
public boolean allProceduresAreCallable() throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#allProceduresAreCallable()"));
}
public boolean allTablesAreSelectable() throws SQLException {
return true;
}
public boolean autoCommitFailureClosesAllResultSets() throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#autoCommitFailureClosesAllResultSets()"));
}
public boolean dataDefinitionCausesTransactionCommit() throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#dataDefinitionCausesTransactionCommit()"));
}
public boolean dataDefinitionIgnoredInTransactions() throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#dataDefinitionIgnoredInTransactions()"));
}
public boolean deletesAreDetected(int type) throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#deletesAreDetected(int)"));
}
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#doesMaxRowSizeIncludeBlobs()"));
}
public ResultSet getAttributes(String catalog, String schemaPattern,
String typeNamePattern, String attributeNamePattern)
throws SQLException {
throw new SQLException(
new UnsupportedOperationException(
"TDDatabaseMetaData#getAttributes(String, String, String, String)"));
}
public ResultSet getBestRowIdentifier(String catalog, String schema,
String table, int scope, boolean nullable) throws SQLException {
throw new SQLException(
new UnsupportedOperationException(
"TDDatabaseMetaData#getBestRowIdentifier(String, String, String, int, boolean)"));
}
public String getCatalogSeparator() throws SQLException {
return ".";
}
public String getCatalogTerm() throws SQLException {
return "database";
}
public ResultSet getCatalogs() throws SQLException {
DatabaseSummary ds = null;
try {
ds = api.showDatabase();
} catch (ClientException e) {
throw new SQLException(e);
}
ArrayList<TDDatabase> databases = new ArrayList<TDDatabase>();
if (ds != null) {
TDDatabase database = new TDDatabase(ds.getName());
databases.add(database);
}
List<String> names = Arrays.asList("TABLE_CAT");
List<String> types = Arrays.asList("STRING");
try {
ResultSet result = new TDMetaDataResultSet<TDDatabase>(names,
types, databases) {
private int cnt = 0;
public boolean next() throws SQLException {
if (cnt >= data.size()) {
return false;
}
TDDatabase d = data.get(cnt);
List<Object> a = new ArrayList<Object>(1);
a.add(d.getDatabaseName()); // TABLE_CAT String => table
// catalog (may be null)
row = a;
cnt++;
return true;
}
};
return result;
} catch (Exception e) {
throw new SQLException(e);
}
}
public ResultSet getClientInfoProperties() throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#getClientInfoProperties()"));
}
public ResultSet getColumnPrivileges(String catalog, String schema,
String table, String columnNamePattern) throws SQLException {
throw new SQLException(
new UnsupportedOperationException(
"TDDatabaseMetaData#getColumnPrivileges(String, String, String, String)"));
}
/**
* Convert a pattern containing JDBC catalog search wildcards into Java
* regex patterns.
*
* @param pattern
* input which may contain '%' or '_' wildcard characters, or
* these characters escaped using
* {@link #getSearchStringEscape()}.
* @return replace %/_ with regex search characters, also handle escaped
* characters.
*/
private String convertPattern(final String pattern) {
if (pattern == null) {
return ".*";
} else {
StringBuilder result = new StringBuilder(pattern.length());
boolean escaped = false;
for (int i = 0, len = pattern.length(); i < len; i++) {
char c = pattern.charAt(i);
if (escaped) {
if (c != '\\') {
escaped = false;
}
result.append(c);
} else {
if (c == '\\') {
escaped = true;
continue;
} else if (c == '%') {
result.append(".*");
} else if (c == '_') {
result.append('.');
} else {
result.append(c);
}
}
}
return result.toString();
}
}
@SuppressWarnings("unchecked")
public ResultSet getColumns(String catalog, final String schemaPattern,
final String tableNamePattern, final String columnNamePattern)
throws SQLException {
if (catalog == null) {
catalog = "default";
}
String tableNamePattern1 = convertPattern(tableNamePattern);
String columnNamePattern1 = convertPattern(columnNamePattern);
List<TableSummary> ts = null;
try {
ts = api.showTables();
if (ts == null) {
ts = new ArrayList<TableSummary>();
}
} catch (ClientException e) {
throw new SQLException(e);
}
List<TDColumn> columns = new ArrayList<TDColumn>();
for (TableSummary t : ts) {
if (!t.getName().matches(tableNamePattern1)) {
continue;
}
List<List<String>> schemaFields = null;
try {
schemaFields = (List<List<String>>) JSONValue.parse(t
.getSchema());
} catch (Exception e) {
continue;
}
int ordinal = 1;
for (List<String> schemaField : schemaFields) {
String fname = schemaField.get(0);
String ftype = schemaField.get(1);
if (!fname.matches(columnNamePattern1)) {
continue;
}
TDColumn c = new TDColumn(fname, t.getName(), catalog, ftype,
"comment", ordinal);
columns.add(c);
ordinal++;
}
}
Collections.sort(columns, new Comparator<TDColumn>() {
/**
* We sort the output of getColumns to guarantee jdbc compliance.
* First check by table name then by ordinal position
*/
public int compare(TDColumn o1, TDColumn o2) {
int compareName = o1.getTableName()
.compareTo(o2.getTableName());
if (compareName == 0) {
if (o1.getOrdinal() > o2.getOrdinal()) {
return 1;
} else if (o1.getOrdinal() < o2.getOrdinal()) {
return -1;
}
return 0;
} else {
return compareName;
}
}
});
List<String> names = Arrays.asList("TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS",
"NUM_PREC_RADIX", "NULLABLE", "REMARKS", "COLUMN_DEF",
"SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH",
"ORDINAL_POSITION", "IS_NULLABLE", "SCOPE_CATLOG",
"SCOPE_SCHEMA", "SCOPE_TABLE", "SOURCE_DATA_TYPE",
"IS_AUTOINCREMENT");
List<String> types = Arrays.asList("STRING", // TABLE_CAT
"STRING", // TABLE_SCHEM
"STRING", // TABLE_NAME
"STRING", // COLUMN_NAME
"INT", // DATA_TYPE
"STRING", // TYPE_NAME
"INT", // COLUMN_SIZE
"INT", // BUFFER_LENGTH
"INT", // DECIMAL_DIGITS
"INT", // NUM_PREC_RADIX
"INT", // NULLABLE
"STRING", // REMARKS
"STRING", // COLUMN_DEF
"INT", // SQL_DATA_TYPE
"INT", // SQL_DATEIME_SUB
"INT", // CHAR_OCTET_LENGTH
"INT", // ORDINAL_POSITION
"STRING", // IS_NULLABLE
"STRING", // SCOPE_CATLOG
"STRING", // SCOPE_SCHEMA
"STRING", // SCOPE_TABLE
"INT", // SOURCE_DATA_TYPE
"STRING" // IS_AUTOINCREMENT
);
try {
return new TDMetaDataResultSet<TDColumn>(names, types, columns) {
private int cnt = 0;
public boolean next() throws SQLException {
if (cnt >= data.size()) {
return false;
}
TDColumn column = data.get(cnt);
List<Object> a = new ArrayList<Object>(23);
a.add(column.getTableCatalog()); // TABLE_CAT String =>
// table catalog (may be
// null)
a.add(null); // TABLE_SCHEM String => table schema (may be
// null)
a.add(column.getTableName()); // TABLE_NAME String => table
// name
a.add(column.getColumnName()); // COLUMN_NAME String =>
// column name
a.add(column.getSqlType()); // DATA_TYPE short => SQL type
// from java.sql.Types
a.add(column.getType()); // TYPE_NAME String => Data source
// dependent type name.
a.add(column.getColumnSize()); // COLUMN_SIZE int => column
// size.
a.add(null); // BUFFER_LENGTH is not used.
a.add(column.getDecimalDigits()); // DECIMAL_DIGITS int =>
// number of fractional
// digits
a.add(column.getNumPrecRadix()); // NUM_PREC_RADIX int =>
// typically either 10 or 2
a.add(DatabaseMetaData.columnNullable); // NULLABLE int =>
// is NULL allowed?
a.add(column.getComment()); // REMARKS String => comment
// describing column (may be
// null)
a.add(null); // COLUMN_DEF String => default value (may be
// null)
a.add(null); // SQL_DATA_TYPE int => unused
a.add(null); // SQL_DATETIME_SUB int => unused
a.add(null); // CHAR_OCTET_LENGTH int
a.add(column.getOrdinal()); // ORDINAL_POSITION int
a.add("YES"); // IS_NULLABLE String
a.add(null); // SCOPE_CATLOG String
a.add(null); // SCOPE_SCHEMA String
a.add(null); // SCOPE_TABLE String
a.add(null); // SOURCE_DATA_TYPE short
a.add("NO"); // IS_AUTOINCREMENT String
row = a;
cnt++;
return true;
}
};
} catch (Exception e) {
throw new SQLException(e);
}
}
public Connection getConnection() throws SQLException {
throw new SQLException(new UnsupportedOperationException(
"TDDatabaseMetaData#getConnection()"));
}
public ResultSet getCrossReference(String primaryCatalog,
String primarySchema, String primaryTable, String foreignCatalog,
String foreignSchema, String foreignTable) throws SQLException {
throw new SQLException(
new UnsupportedOperationException(
"TDDatabaseMetaData#getCrossReference(String, String, String, String, String, String)"));
}
public int getJDBCMajorVersion() throws SQLException {
return JDBC_MAJOR_VERSION;
}
public int getJDBCMinorVersion() throws SQLException {
return JDBC_MINOR_VERSION;
}
public int getDatabaseMajorVersion() throws SQLException {
return Constants.DATABASE_MAJOR_VERSION;
}
public int getDatabaseMinorVersion() throws SQLException {
return Constants.DATABASE_MINOR_VERSION;
}
public String getDatabaseProductName() throws SQLException {
return DATABASE_NAME;
}
public String getDatabaseProductVersion() throws SQLException {
return DATABASE_FULL_VERSION;
}
public int getDriverMajorVersion() {
return DRIVER_MAJOR_VERSION;
}
public int getDriverMinorVersion() {
return DRIVER_MINOR_VERSION;
}
public String getDriverName() throws SQLException {
return TreasureDataDriver.class.getName();
}
public String getDriverVersion() throws SQLException {
return DRIVER_FULL_VERSION;
}
public int getDefaultTransactionIsolation() throws SQLException {
return Connection.TRANSACTION_NONE;
}
public ResultSet getExportedKeys(String catalog, String schema, String table)
throws SQLException {
throw new SQLException("Method not supported");
}
public String getExtraNameCharacters() throws SQLException {
throw new SQLException("Method not supported");
}
public ResultSet getFunctionColumns(String arg0, String arg1, String arg2,
String arg3) throws SQLException {
throw new SQLException("Method not supported");
}
public ResultSet getFunctions(String arg0, String arg1, String arg2)
throws SQLException {
throw new SQLException("Method not supported");
}
public String getIdentifierQuoteString() throws SQLException {
return "`";
}
public ResultSet getImportedKeys(String catalog, String schema, String table)
throws SQLException {
try {
return new TDMetaDataResultSet<TDImportedKey>(null, null, null) {
public boolean next() throws SQLException {
return false;
}
};
} catch (Exception e) {
throw new SQLException(e);
}
}
public ResultSet getIndexInfo(String catalog, String schema, String table,
boolean unique, boolean approximate) throws SQLException {
throw new SQLException("Method not supported");
}
public int getMaxBinaryLiteralLength() throws SQLException {
throw new SQLException("Method not supported");
}
/**
* Retrieves the maximum number of characters that this database allows in a
* catalog name.
*/
public int getMaxCatalogNameLength() throws SQLException {
return MAX_CATALOG_NAME_LENGTH;
}
public int getMaxCharLiteralLength() throws SQLException {
throw new SQLException("Method not supported");
}
/**
* Retrieves the maximum number of characters this database allows for a
* column name.
*/
public int getMaxColumnNameLength() throws SQLException {
return MAX_COLUMN_NAME_LENGTH;
}
public int getMaxColumnsInGroupBy() throws SQLException {
throw new SQLException("Method not supported");
}
public int getMaxColumnsInIndex() throws SQLException {
throw new SQLException("Method not supported");
}
public int getMaxColumnsInOrderBy() throws SQLException {
throw new SQLException("Method not supported");
}
/**
* Retrieves the maximum number of columns this database allows in a
* <code>SELECT</code> list.
*/
public int getMaxColumnsInSelect() throws SQLException {
return MAX_COLUMNS_IN_SELECT;
}
/**
* Retrieves the maximum number of columns this database allows in a table.
*/
public int getMaxColumnsInTable() throws SQLException {
return MAX_COLUMNS_IN_TABLE;
}
public int getMaxConnections() throws SQLException {
throw new SQLException("Method not supported");
}
public int getMaxCursorNameLength() throws SQLException {
throw new SQLException("Method not supported");
}
public int getMaxIndexLength() throws SQLException {
throw new SQLException("Method not supported");
}
public int getMaxProcedureNameLength() throws SQLException {
throw new SQLException("Method not supported");
}
/**
* Retrieves the maximum number of bytes this database allows in a single
* row.
*/
public int getMaxRowSize() throws SQLException {
return MAX_ROW_SIZE;
}
public int getMaxSchemaNameLength() throws SQLException {
throw new SQLException("Method not supported");
}
/**
* Retrieves the maximum number of characters this database allows in an SQL
* statement.
*/
public int getMaxStatementLength() throws SQLException {
return MAX_STATEMENT_LENGTH;
}
public int getMaxStatements() throws SQLException {
throw new SQLException("Method not supported");
}
/**
* Retrieves the maximum number of characters this database allows in a
* table name.
*/
public int getMaxTableNameLength() throws SQLException {
return MAX_TABLE_NAME_LENGTH;
}
/**
* Retrieves the maximum number of tables this database allows in a
* <code>SELECT</code> statement.
*/
public int getMaxTablesInSelect() throws SQLException {
return MAX_TABLES_IN_SELECT;
}
/**
* Retrieves the maximum number of characters this database allows in a user
* name.
*/
public int getMaxUserNameLength() throws SQLException {
return MAX_USER_NAME_LENGTH;
}
public String getNumericFunctions() throws SQLException {
return "";
}
public ResultSet getPrimaryKeys(String catalog, String schema, String table)
throws SQLException {
throw new SQLException("TD tables don't have primary keys");
}
public ResultSet getProcedureColumns(String catalog, String schemaPattern,
String procedureNamePattern, String columnNamePattern)
throws SQLException {
throw new SQLException("Method not supported");
}
public String getProcedureTerm() throws SQLException {
return "UDF";
}
public ResultSet getProcedures(String catalog, String schemaPattern,
String procedureNamePattern) throws SQLException {
return null;
}
public int getResultSetHoldability() throws SQLException {
throw new SQLException("Method not supported");
}
public RowIdLifetime getRowIdLifetime() throws SQLException {
throw new SQLException("Method not supported");
}
public String getSQLKeywords() throws SQLException {
return "TRUE,FALSE,ALL,AND,OR,NOT,LIKE,ASC,DESC,ORDER,BY,GROUP,WHERE,"
+ "FROM,AS,SELECT,DISTINCT,INSERT,OVERWRITE,OUTER,JOIN,LEFT,RIGHT,"
+ "FULL,ON,PARTITION,PARTITIONS,TABLE,TABLES,TBLPROPERTIES,SHOW,MSCK,"
+ "DIRECTORY,LOCAL,TRANSFORM,USING,CLUSTER,DISTRIBUTE,SORT,UNION,LOAD,"
+ "DATA,INPATH,IS,NULL,CREATE,EXTERNAL,ALTER,DESCRIBE,DROP,REANME,TO,"
+ "COMMENT,BOOLEAN,TINYINT,SMALLINT,INT,BIGINT,FLOAT,DOUBLE,DATE,"
+ "DATETIME,TIMESTAMP,STRING,BINARY,ARRAY,MAP,REDUCE,PARTITIONED,"
+ "CLUSTERED,SORTED,INTO,BUCKETS,ROW,FORMAT,DELIMITED,FIELDS,TERMINATED,"
+ "COLLECTION,ITEMS,KEYS,LINES,STORED,SEQUENCEFILE,TEXTFILE,INPUTFORMAT,"
+ "OUTPUTFORMAT,LOCATION,TABLESAMPLE,BUCKET,OUT,OF,CAST,ADD,REPLACE,"
+ "COLUMNS,RLIKE,REGEXP,TEMPORARY,FUNCTION,EXPLAIN,EXTENDED,SERDE,WITH,"
+ "SERDEPROPERTIES,LIMIT,SET,TBLPROPERTIES";
}
public int getSQLStateType() throws SQLException {
return DatabaseMetaData.sqlStateSQL99;
}
public String getSchemaTerm() throws SQLException {
return "";
}
public ResultSet getSchemas() throws SQLException {
return getSchemas(null, null);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public ResultSet getSchemas(String catalog, String schemaPattern)
throws SQLException {
return new TDMetaDataResultSet(Arrays.asList("TABLE_SCHEM",
"TABLE_CATALOG"), Arrays.asList("STRING", "STRING"), null) {
public boolean next() throws SQLException {
return false;
}
};
}
public String getSearchStringEscape() throws SQLException {
return String.valueOf('\\');
}
public String getStringFunctions() throws SQLException {
return "";
}
public ResultSet getSuperTables(String catalog, String schemaPattern,
String tableNamePattern) throws SQLException {
throw new SQLException("Method not supported");
}
public ResultSet getSuperTypes(String catalog, String schemaPattern,
String typeNamePattern) throws SQLException {
throw new SQLException("Method not supported");
}
public String getSystemFunctions() throws SQLException {
return "";
}
public ResultSet getTablePrivileges(String catalog, String schemaPattern,
String tableNamePattern) throws SQLException {
throw new SQLException("Method not supported");
}
public ResultSet getTableTypes() throws SQLException {
List<String> names = Arrays.asList("TABLE_TYPE");
List<String> types = Arrays.asList("STRING");
List<TDTable.Type> data0 = Arrays.asList(TDTable.Type.values());
ResultSet result = new TDMetaDataResultSet<TDTable.Type>(names, types,
data0) {
private int cnt = 0;
public boolean next() throws SQLException {
if (cnt < data.size()) {
List<Object> a = new ArrayList<Object>(1);
a.add(toTDTableType(data.get(cnt).name()));
row = a;
cnt++;
return true;
} else {
return false;
}
}
};
return result;
}
public ResultSet getTables(String catalog, String schemaPattern,
String tableNamePattern, String[] types) throws SQLException {
/*
* finds table descriptions in the specified database.
* if catalog is not same as the specified database, it returns null.
* if catalog is null or catalog is empty, catalog is set to the specified database.
*/
if (catalog == null || catalog.isEmpty()) {
catalog = database.getName();
} else if (!catalog.equals(database.getName())) {
return null; // TODO return an empty result set
}
/*
* ignores schemaPattern for now. it is not used for searching table descriptions.
*/
List<TableSummary> ts = null;
try {
ts = api.showTables();
if (ts == null) {
ts = new ArrayList<TableSummary>();
}
} catch (ClientException e) {
throw new SQLException(e);
}
/*
* if types is null or includes 'TABLE', it searches table descriptions in the specified database.
* otherwise it returns null.
*/
if (types != null) {
boolean typeTableWanted = false;
for (String type : types) {
if (type.equals("TABLE")) {
typeTableWanted = true;
break;
}
}
if (!typeTableWanted) {
return null; // TODO return an empty result set
}
}
String tableNamePattern1 = convertPattern(tableNamePattern);
List<TDTable> tables = new ArrayList<TDTable>();
for (TableSummary t : ts) {
/*
* tableNamePattern - a table name pattern; must match the table
* name as it is stored in the database.
*
* The table name must match the tableNamePattern regexp to be
* accepted.
*/
if (!t.getName().matches(tableNamePattern1)) {
continue;
}
TDTable table = new TDTable(catalog, t.getName(), "TABLE",
"comment");
tables.add(table);
}
if (tables.isEmpty()) {
return null; // TODO return an empty result set
}
Collections.sort(tables, new Comparator<TDTable>() {
/**
* We sort the output of getTables to guarantee JDBC compliance to
* sort by TABLE_TYPE, TABLE_CAT, TABLE_SCHEM, and TABLE_NAME.
*
* In our specific case: Sorting by catalog (only one available) and
* schema (empty) is not necessary so we sort by type, then table
* name.
*/
public int compare(TDTable o1, TDTable o2) {
int compareType = o1.getType().compareTo(o2.getType());
if (compareType == 0) {
return o1.getTableName().compareTo(o2.getTableName());
} else {
return compareType;
}
}
});
List<String> nameList = Arrays.asList("TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "TABLE_TYPE", "REMARKS", "TYPE_CAT",
"TYPE_SCHEM", "TYPE_NAME", "SELF_REFERENCING_COL_NAME",
"REF_GENERATION");
List<String> typeList = Arrays.asList("STRING", // "TABLE_CAT"
"STRING", // "TABLE_SCHEM"
"STRING", // "TABLE_NAME"
"STRING", // "TABLE_TYPE"
"STRING", // "REMARKS"
"STRING", // "TYPE_CAT"
"STRING", // "TYPE_SCHEM"
"STRING", // "TYPE_NAME"
"STRING", // "SELF_REFERENCING_COL_NAME"
"STRING" // "REF_GENERATION"
);
try {
ResultSet result = new TDMetaDataResultSet<TDTable>(nameList,
typeList, tables) {
private int cnt = 0;
public boolean next() throws SQLException {
if (cnt >= data.size()) {
return false;
}
TDTable t = data.get(cnt);
List<Object> a = new ArrayList<Object>(10);
a.add(t.getTableCatalog()); // TABLE_CAT String => table
// catalog (may be null)
a.add(null); // TABLE_SCHEM String => table schema (may be
// null)
a.add(t.getTableName()); // TABLE_NAME String => table name
try {
a.add(t.getSqlTableType()); // TABLE_TYPE String =>
// "TABLE","VIEW"
} catch (Exception e) {
throw new SQLException(e);
}
a.add(t.getComment()); // REMARKS String => explanatory
// comment on the table
a.add(null); // TYPE_CAT String => the types catalog (may be
// null)
a.add(null); // TYPE_SCHEM String => the types schema (may
// be null)
a.add(null); // TYPE_NAME String => type name (may be null)
a.add(null); // SELF_REFERENCING_COL_NAME String => ... (may
// be null)
a.add(null); // REF_GENERATION String => ... (may be null)
row = a;
cnt++;
return true;
}
};
return result;
} catch (Exception e) {
throw new SQLException(e);
}
}
/**
* Translate hive table types into jdbc table types.
*
* @param type
* @return
*/
public static String toTDTableType(String type) {
if (type == null) {
return null;
} else if (type.equals(TDTable.Type.TABLE.toString())) {
return "TABLE";
} else if (type.equals(TDTable.Type.VIEW.toString())) {
return "VIEW";
} else if (type.equals(TDTable.Type.EXTERNAL_TABLE.toString())) {
return "EXTERNAL TABLE";
} else {
return type;
}
}
public String getTimeDateFunctions() throws SQLException {
return "";
}
public ResultSet getTypeInfo() throws SQLException {
List<TDDataType> types = new ArrayList<TDDataType>();
try {
ResultSet result = new TDMetaDataResultSet<TDDataType>(null, null,
types) {
private int cnt = 0;
public boolean next() throws SQLException {
if (cnt >= data.size()) {
return false;
}
TDDataType t = data.get(cnt);
List<Object> a = new ArrayList<Object>(18);
a.add(t.typeName()); // TYPE_NAME String
a.add(t.dataType()); // DATA_TYPE Integer
a.add(t.precision()); // PRECISION Integer
a.add(t.literalPrefix()); // LITERAL_PREFIX String
a.add(t.literalSuffix()); // LITERAL_SUFFIX String
a.add(t.createParams()); // CREATE_PARAMS String
a.add(t.nullable()); // NULLABLE Short
a.add(t.caseSensitive()); // CASE_SENSITIVE Boolean
a.add(t.searchable()); // SEARCHABLE Short
a.add(t.unsignedAttribute()); // UNSIGNED_ATTRIBUTE Boolean
a.add(t.fixedPrecScale()); // FIXED_PREC_SCALE Boolean
a.add(t.autoIncrement()); // AUTO_INCREMENT Boolean
a.add(t.localTypeName()); // LOCAL_TYPE_NAME String
a.add(t.minimunScale()); // MINIMUM_SCALE Short
a.add(t.maximumScale()); // MAXIMUM_SCALE Short
a.add(t.sqlDataType()); // SQL_DATA_TYPE Integer
a.add(t.sqlDatetimeSub()); // SQL_DATETIME_SUB Integer
a.add(t.numPrecRadix()); // NUM_PREC_RADIX Integer
row = a;
cnt++;
return true;
}
};
return result;
} catch (Exception e) {
throw new SQLException(e);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public ResultSet getUDTs(String catalog, String schemaPattern,
String typeNamePattern, int[] types) throws SQLException {
return new TDMetaDataResultSet(
Arrays.asList("TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME",
"CLASS_NAME", "DATA_TYPE", "REMARKS", "BASE_TYPE"),
Arrays.asList("STRING", "STRING", "STRING", "STRING", "INT",
"STRING", "INT"), null) {
public boolean next() throws SQLException {
return false;
}
};
}
public String getURL() throws SQLException {
throw new SQLException("Method not supported");
}
public String getUserName() throws SQLException {
throw new SQLException("Method not supported");
}
public ResultSet getVersionColumns(String catalog, String schema,
String table) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean insertsAreDetected(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean isCatalogAtStart() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean isReadOnly() throws SQLException {
return true;
}
public boolean locatorsUpdateCopy() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean nullPlusNonNullIsNull() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean nullsAreSortedAtEnd() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean nullsAreSortedAtStart() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean nullsAreSortedHigh() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean nullsAreSortedLow() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean othersDeletesAreVisible(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean othersInsertsAreVisible(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean othersUpdatesAreVisible(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean ownDeletesAreVisible(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean ownInsertsAreVisible(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean ownUpdatesAreVisible(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean storesLowerCaseIdentifiers() throws SQLException {
return false;
}
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean storesMixedCaseIdentifiers() throws SQLException {
return false;
}
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean storesUpperCaseIdentifiers() throws SQLException {
return true;
}
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsANSI92EntryLevelSQL() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsANSI92FullSQL() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsANSI92IntermediateSQL() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsAlterTableWithAddColumn() throws SQLException {
return true;
}
public boolean supportsAlterTableWithDropColumn() throws SQLException {
return false;
}
public boolean supportsBatchUpdates() throws SQLException {
return false;
}
public boolean supportsCatalogsInDataManipulation() throws SQLException {
return false;
}
public boolean supportsCatalogsInIndexDefinitions() throws SQLException {
return false;
}
public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException {
return false;
}
public boolean supportsCatalogsInProcedureCalls() throws SQLException {
return false;
}
public boolean supportsCatalogsInTableDefinitions() throws SQLException {
return false;
}
public boolean supportsColumnAliasing() throws SQLException {
return true;
}
public boolean supportsConvert() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsConvert(int fromType, int toType)
throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsCoreSQLGrammar() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsCorrelatedSubqueries() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsDataDefinitionAndDataManipulationTransactions()
throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsDataManipulationTransactionsOnly()
throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsDifferentTableCorrelationNames() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsExpressionsInOrderBy() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsExtendedSQLGrammar() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsFullOuterJoins() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsGetGeneratedKeys() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsGroupBy() throws SQLException {
return true;
}
public boolean supportsGroupByBeyondSelect() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsGroupByUnrelated() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsIntegrityEnhancementFacility() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsLikeEscapeClause() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsLimitedOuterJoins() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsMinimumSQLGrammar() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsMixedCaseIdentifiers() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsMultipleOpenResults() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsMultipleResultSets() throws SQLException {
return false;
}
public boolean supportsMultipleTransactions() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsNamedParameters() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsNonNullableColumns() throws SQLException {
return false;
}
public boolean supportsOpenCursorsAcrossCommit() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsOpenCursorsAcrossRollback() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsOpenStatementsAcrossCommit() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsOpenStatementsAcrossRollback() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsOrderByUnrelated() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsOuterJoins() throws SQLException {
return true;
}
public boolean supportsPositionedDelete() throws SQLException {
return false;
}
public boolean supportsPositionedUpdate() throws SQLException {
return false;
}
public boolean supportsResultSetConcurrency(int type, int concurrency)
throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsResultSetHoldability(int holdability)
throws SQLException {
return false;
}
public boolean supportsResultSetType(int type) throws SQLException {
return true;
}
public boolean supportsSavepoints() throws SQLException {
return false;
}
public boolean supportsSchemasInDataManipulation() throws SQLException {
return false;
}
public boolean supportsSchemasInIndexDefinitions() throws SQLException {
return false;
}
public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException {
return false;
}
public boolean supportsSchemasInProcedureCalls() throws SQLException {
return false;
}
public boolean supportsSchemasInTableDefinitions() throws SQLException {
return false;
}
public boolean supportsSelectForUpdate() throws SQLException {
return false;
}
public boolean supportsStatementPooling() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsStoredProcedures() throws SQLException {
return false;
}
public boolean supportsSubqueriesInComparisons() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsSubqueriesInExists() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsSubqueriesInIns() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsSubqueriesInQuantifieds() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsTableCorrelationNames() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsTransactionIsolationLevel(int level)
throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsTransactions() throws SQLException {
return false;
}
public boolean supportsUnion() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean supportsUnionAll() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean updatesAreDetected(int type) throws SQLException {
throw new SQLException("Method not supported");
}
public boolean usesLocalFilePerTable() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean usesLocalFiles() throws SQLException {
throw new SQLException("Method not supported");
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
throw new SQLException("Method not supported");
}
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException("Method not supported");
}
}
|
package zhongqiu.common.base.collections;
|
package SPHY;
/**
*
* @author bowen
*/
public class PhysObject {
private Vector2 position, velocity, momentum, acceleration; //meters, meters/s, meters*kg/s, meters/s^2
private VectorR rotation, angspeed, angaccel;
private Vector2[] forces; //in N
private double[] torques;
private double mass; //in KG
private double moment;
private boolean immovable; //can give out infinite normal force
public PhysObject() {
}
}
|
package org.ethereum.db;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.AccountState;
import org.ethereum.core.Block;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.Repository;
import org.ethereum.datasource.CachingDataSource;
import org.ethereum.datasource.KeyValueDataSource;
import org.ethereum.json.EtherObjectMapper;
import org.ethereum.json.JSONHelper;
import org.ethereum.trie.JournalPruneDataSource;
import org.ethereum.trie.SecureTrie;
import org.ethereum.trie.Trie;
import org.ethereum.trie.TrieImpl;
import org.ethereum.util.Value;
import org.ethereum.vm.DataWord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileSystemUtils;
import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.crypto.HashUtil.EMPTY_TRIE_HASH;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
import static org.ethereum.util.ByteUtil.wrap;
/**
* @author Roman Mandeleil
* @since 17.11.2014
*/
public class RepositoryImpl implements Repository , org.ethereum.facade.Repository{
public final static String DETAILS_DB = "details";
public final static String STATE_DB = "state";
private static final Logger logger = LoggerFactory.getLogger("repository");
private static final Logger gLogger = LoggerFactory.getLogger("general");
@Autowired
CommonConfig commonConfig = new CommonConfig();
@Autowired
SystemProperties config = SystemProperties.getDefault();
@Autowired
private DetailsDataStore dds = new DetailsDataStore();
@Autowired
private BlockStore blockStore;
private Trie worldState;
private DatabaseImpl detailsDB = null;
@Autowired
private KeyValueDataSource detailsDS;
@Autowired
private KeyValueDataSource stateDS;
private CachingDataSource stateDSCache;
private JournalPruneDataSource stateDSPrune;
ReadWriteLock rwLock = new ReentrantReadWriteLock();
private boolean isSnapshot = false;
private long bestBlockNumber = 0;
private long pruneBlockCount;
private boolean pruneEnabled = true;
public RepositoryImpl() {
}
public RepositoryImpl(KeyValueDataSource detailsDS, KeyValueDataSource stateDS) {
this(detailsDS, stateDS, false);
}
public RepositoryImpl(KeyValueDataSource detailsDS, KeyValueDataSource stateDS, boolean pruneEnabled) {
this.detailsDS = detailsDS;
this.stateDS = stateDS;
this.pruneEnabled = pruneEnabled;
init();
}
public RepositoryImpl withBlockStore(BlockStore blockStore) {
this.blockStore = blockStore;
return this;
}
@PostConstruct
void init() {
detailsDS.setName(DETAILS_DB);
detailsDS.init();
stateDS.setName(STATE_DB);
stateDS.init();
stateDSCache = new CachingDataSource(stateDS);
stateDSPrune = new JournalPruneDataSource(stateDSCache);
detailsDB = new DatabaseImpl(detailsDS);
dds.setDB(detailsDB);
pruneBlockCount = pruneEnabled ? config.databasePruneDepth() : -1;
worldState = createStateTrie();
}
private Trie createStateTrie() {
return new SecureTrie(stateDSPrune).withPruningEnabled(pruneBlockCount >= 0);
}
@Override
public void reset() {
throw new UnsupportedOperationException();
}
@Override
public void close() {
rwLock.writeLock().lock();
try {
if (detailsDB != null) {
detailsDB.close();
detailsDB = null;
}
if (stateDS != null) {
stateDS.close();
stateDS = null;
}
} finally {
rwLock.writeLock().unlock();
}
}
@Override
public boolean isClosed() {
return stateDS == null;
}
@Override
public synchronized void updateBatch(HashMap<ByteArrayWrapper, AccountState> stateCache,
HashMap<ByteArrayWrapper, ContractDetails> detailsCache) {
logger.trace("updatingBatch: detailsCache.size: {}", detailsCache.size());
for (ByteArrayWrapper hash : stateCache.keySet()) {
AccountState accountState = stateCache.get(hash);
ContractDetails contractDetails = detailsCache.get(hash);
if (accountState.isDeleted()) {
delete(hash.getData());
logger.debug("delete: [{}]",
Hex.toHexString(hash.getData()));
} else {
if (!contractDetails.isDirty()) continue;
ContractDetailsCacheImpl contractDetailsCache = (ContractDetailsCacheImpl) contractDetails;
if (contractDetailsCache.origContract == null) {
contractDetailsCache.origContract = commonConfig.contractDetailsImpl();
contractDetailsCache.origContract.setAddress(hash.getData());
contractDetailsCache.commit();
}
contractDetails = contractDetailsCache.origContract;
byte[] data = hash.getData();
updateContractDetails(data, contractDetails);
if ( !Arrays.equals(accountState.getCodeHash(), EMPTY_TRIE_HASH) )
accountState.setStateRoot(contractDetails.getStorageHash());
updateAccountState(hash.getData(), accountState);
if (logger.isTraceEnabled()) {
logger.trace("update: [{}],nonce: [{}] balance: [{}] [{}]",
Hex.toHexString(hash.getData()),
accountState.getNonce(),
accountState.getBalance(),
contractDetails.getStorage());
}
}
}
logger.debug("updated: detailsCache.size: {}", detailsCache.size());
stateCache.clear();
detailsCache.clear();
}
private synchronized void updateContractDetails(final byte[] address, final ContractDetails contractDetails) {
rwLock.readLock().lock();
try {
dds.update(address, contractDetails);
} finally {
rwLock.readLock().unlock();
}
}
@Override
public void flushNoReconnect() {
rwLock.writeLock().lock();
try {
gLogger.debug("flushing to disk");
long s = System.currentTimeMillis();
dds.flush();
worldState.sync();
gLogger.info("RepositoryImpl.flushNoReconnect took " + (System.currentTimeMillis() - s) + " ms");
} finally {
rwLock.writeLock().unlock();
}
}
@Override
public synchronized void flush() {
rwLock.writeLock().lock();
try {
gLogger.debug("flushing to disk");
long s = System.currentTimeMillis();
dds.flush();
worldState.sync();
stateDSCache.flush();
gLogger.info("RepositoryImpl.flush took " + (System.currentTimeMillis() - s) + " ms");
} finally {
rwLock.writeLock().unlock();
}
}
@Override
public void rollback() {
throw new UnsupportedOperationException();
}
@Override
public void commit() {
throw new UnsupportedOperationException();
}
@Override
public synchronized void syncToRoot(final byte[] root) {
rwLock.readLock().lock();
try {
worldState.setRoot(root);
} finally {
rwLock.readLock().unlock();
}
}
@Override
public synchronized Repository startTracking() {
return commonConfig.repositoryTrack(this);
}
protected SystemProperties config() {
return config;
}
@Override
public synchronized void dumpState(Block block, long gasUsed, int txNumber, byte[] txHash) {
dumpTrie(block);
if (!(config().dumpFull() || config().dumpBlock() == block.getNumber()))
return;
// todo: dump block header and the relevant tx
if (block.getNumber() == 0 && txNumber == 0)
if (config().dumpCleanOnRestart()) {
FileSystemUtils.deleteRecursively(new File(config().dumpDir()));
}
String dir = config().dumpDir() + "/";
String fileName = "";
if (txHash != null)
fileName = String.format("%07d_%d_%s.dmp", block.getNumber(), txNumber,
Hex.toHexString(txHash).substring(0, 8));
else {
fileName = String.format("%07d_c.dmp", block.getNumber());
}
File dumpFile = new File(System.getProperty("user.dir") + "/" + dir + fileName);
FileWriter fw = null;
BufferedWriter bw = null;
try {
dumpFile.getParentFile().mkdirs();
dumpFile.createNewFile();
fw = new FileWriter(dumpFile.getAbsoluteFile());
bw = new BufferedWriter(fw);
List<ByteArrayWrapper> keys = this.detailsDB.dumpKeys();
JsonNodeFactory jsonFactory = new JsonNodeFactory(false);
ObjectNode blockNode = jsonFactory.objectNode();
JSONHelper.dumpBlock(blockNode, block, gasUsed,
this.getRoot(),
keys, this);
EtherObjectMapper mapper = new EtherObjectMapper();
bw.write(mapper.writeValueAsString(blockNode));
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (bw != null) bw.close();
if (fw != null) fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public synchronized String getTrieDump() {
rwLock.readLock().lock();
try {
return worldState.getTrieDump();
} finally {
rwLock.readLock().unlock();
}
}
public synchronized void dumpTrie(Block block) {
if (!(config().dumpFull() || config().dumpBlock() == block.getNumber()))
return;
String fileName = String.format("%07d_trie.dmp", block.getNumber());
String dir = config().dumpDir() + "/";
File dumpFile = new File(System.getProperty("user.dir") + "/" + dir + fileName);
FileWriter fw = null;
BufferedWriter bw = null;
String dump = getTrieDump();
try {
dumpFile.getParentFile().mkdirs();
dumpFile.createNewFile();
fw = new FileWriter(dumpFile.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(dump);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (bw != null) bw.close();
if (fw != null) fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public synchronized Set<byte[]> getAccountsKeys() {
rwLock.readLock().lock();
try {
Set<byte[]> result = new HashSet<>();
for (ByteArrayWrapper key : dds.keys()) {
if (isExist(key.getData()))
result.add(key.getData());
}
return result;
} finally {
rwLock.readLock().unlock();
}
}
@Override
public synchronized BigInteger addBalance(byte[] addr, BigInteger value) {
AccountState account = getAccountStateOrCreateNew(addr);
BigInteger result = account.addToBalance(value);
updateAccountState(addr, account);
return result;
}
@Override
public synchronized BigInteger getBalance(byte[] addr) {
if (!isExist(addr)) return BigInteger.ZERO;
AccountState account = getAccountState(addr);
return (account == null) ? BigInteger.ZERO : account.getBalance();
}
@Override
public synchronized DataWord getStorageValue(byte[] addr, DataWord key) {
ContractDetails details = getContractDetails(addr);
return (details == null) ? null : details.get(key);
}
@Override
public synchronized int getStorageSize(byte[] addr) {
ContractDetails details = getContractDetails(addr);
return (details == null) ? 0 : details.getStorageSize();
}
@Override
public synchronized Set<DataWord> getStorageKeys(byte[] addr) {
ContractDetails details = getContractDetails(addr);
return (details == null) ? Collections.EMPTY_SET : details.getStorageKeys();
}
@Override
public synchronized Map<DataWord, DataWord> getStorage(byte[] addr, Collection<DataWord> keys) {
ContractDetails details = getContractDetails(addr);
return (details == null) ? Collections.EMPTY_MAP : details.getStorage(keys);
}
@Override
public synchronized void addStorageRow(byte[] addr, DataWord key, DataWord value) {
ContractDetails details = getContractDetails(addr);
if (details == null) {
createAccount(addr);
details = getContractDetails(addr);
}
details.put(key, value);
updateContractDetails(addr, details);
}
@Override
public synchronized byte[] getCode(byte[] addr) {
if (!isExist(addr))
return EMPTY_BYTE_ARRAY;
byte[] codeHash = getAccountState(addr).getCodeHash();
ContractDetails details = getContractDetails(addr);
return (details == null) ? null : details.getCode(codeHash);
}
@Override
public synchronized void saveCode(byte[] addr, byte[] code) {
ContractDetails details = getContractDetails(addr);
if (details == null) {
createAccount(addr);
details = getContractDetails(addr);
}
details.setCode(code);
AccountState accountState = getAccountState(addr);
accountState.setCodeHash(sha3(code));
updateContractDetails(addr, details);
updateAccountState(addr, accountState);
}
@Override
public synchronized BigInteger getNonce(byte[] addr) {
AccountState accountState = getAccountState(addr);
return accountState == null ? config().getBlockchainConfig().getCommonConstants().getInitialNonce() :
accountState.getNonce();
}
@Nonnull
private synchronized AccountState getAccountStateOrCreateNew(byte[] addr) {
AccountState account = getAccountState(addr);
return (account == null) ? createAccount(addr) : account;
}
@Override
public synchronized BigInteger increaseNonce(byte[] addr) {
AccountState account = getAccountStateOrCreateNew(addr);
account.incrementNonce();
updateAccountState(addr, account);
return account.getNonce();
}
private synchronized void updateAccountState(final byte[] addr, final AccountState accountState) {
rwLock.readLock().lock();
try {
worldState.update(addr, accountState.getEncoded());
} finally {
rwLock.readLock().unlock();
}
}
public synchronized BigInteger setNonce(final byte[] addr, final BigInteger nonce) {
AccountState account = getAccountStateOrCreateNew(addr);
account.setNonce(nonce);
updateAccountState(addr, account);
return account.getNonce();
}
@Override
public synchronized void delete(final byte[] addr) {
rwLock.readLock().lock();
try {
worldState.delete(addr);
} finally {
rwLock.readLock().unlock();
}
}
@Override
public synchronized ContractDetails getContractDetails(final byte[] addr) {
rwLock.readLock().lock();
try {
// That part is important cause if we have
// to sync details storage according the trie root
// saved in the account
AccountState accountState = getAccountState(addr);
byte[] storageRoot = EMPTY_TRIE_HASH;
if (accountState != null)
storageRoot = getAccountState(addr).getStateRoot();
ContractDetails details = dds.get(addr);
if (details != null)
details = details.getSnapshotTo(storageRoot);
return details;
} finally {
rwLock.readLock().unlock();
}
}
@Override
public boolean hasContractDetails(byte[] addr) {
return dds.get(addr) != null;
}
@Override
public synchronized AccountState getAccountState(final byte[] addr) {
rwLock.readLock().lock();
try {
AccountState result = null;
byte[] accountData = worldState.get(addr);
if (accountData.length != 0)
result = new AccountState(accountData);
return result;
} finally {
rwLock.readLock().unlock();
}
}
@Override
public synchronized AccountState createAccount(final byte[] addr) {
AccountState accountState = new AccountState(
config().getBlockchainConfig().getCommonConstants().getInitialNonce(), BigInteger.ZERO);
updateAccountState(addr, accountState);
updateContractDetails(addr, commonConfig.contractDetailsImpl());
return accountState;
}
@Override
public boolean isExist(byte[] addr) {
return getAccountState(addr) != null;
}
@Override
public synchronized void loadAccount(byte[] addr,
HashMap<ByteArrayWrapper, AccountState> cacheAccounts,
HashMap<ByteArrayWrapper, ContractDetails> cacheDetails) {
AccountState account = getAccountState(addr);
ContractDetails details = getContractDetails(addr);
account = (account == null) ? new AccountState(config().getBlockchainConfig().getCommonConstants().
getInitialNonce(), BigInteger.ZERO) : account.clone();
details = new ContractDetailsCacheImpl(details);
// details.setAddress(addr);
ByteArrayWrapper wrappedAddress = wrap(addr);
cacheAccounts.put(wrappedAddress, account);
cacheDetails.put(wrappedAddress, details);
}
@Override
public synchronized byte[] getRoot() {
return worldState.getRootHash();
}
public synchronized void setRoot(byte[] root) {
worldState.setRoot(root);
}
public void setPruneBlockCount(long pruneBlockCount) {
this.pruneBlockCount = pruneBlockCount;
}
public synchronized void commitBlock(BlockHeader blockHeader) {
worldState.sync();
if (pruneBlockCount >= 0) {
stateDSPrune.storeBlockChanges(blockHeader);
pruneBlocks(blockHeader);
}
}
private void pruneBlocks(BlockHeader curBlock) {
if (curBlock.getNumber() > bestBlockNumber) { // pruning only on increasing blocks
long pruneBlockNumber = curBlock.getNumber() - pruneBlockCount;
if (pruneBlockNumber >= 0) {
byte[] pruneBlockHash = blockStore.getBlockHashByNumber(pruneBlockNumber);
if (pruneBlockHash != null) {
stateDSPrune.prune(blockStore.getBlockByHash(pruneBlockHash).getHeader());
}
}
}
bestBlockNumber = curBlock.getNumber();
}
public Trie getWorldState() {
return worldState;
}
@Override
public synchronized Repository getSnapshotTo(byte[] root){
RepositoryImpl repo = new RepositoryImpl();
repo.commonConfig = commonConfig;
repo.blockStore = blockStore;
repo.config = config;
repo.stateDS = this.stateDS;
repo.stateDSCache = this.stateDSCache;
repo.stateDSPrune = this.stateDSPrune;
repo.pruneBlockCount = this.pruneBlockCount;
repo.detailsDB = this.detailsDB;
repo.detailsDS = this.detailsDS;
repo.dds = this.dds;
repo.isSnapshot = true;
repo.worldState = repo.createStateTrie();
repo.worldState.setRoot(root);
return repo;
}
}
|
package org.apache.velocity.util.introspection;
import java.util.Map;
import java.util.List;
import java.util.Hashtable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* A cache of introspection information for a specific class instance.
* Keys {@link java.lang.Method} objects by a concatenation of the
* method name and the names of classes that make up the parameters.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:bob@werken.com">Bob McWhirter</a>
* @author <a href="mailto:szegedia@freemail.hu">Attila Szegedi</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ClassMap.java,v 1.15 2001/11/02 05:09:37 dlr Exp $
*/
public class ClassMap
{
private static final class CacheMiss { }
private static final CacheMiss CACHE_MISS = new CacheMiss();
private static final Object OBJECT = new Object();
/**
* Class passed into the constructor used to as
* the basis for the Method map.
*/
private Class clazz;
/**
* Cache of Methods, or CACHE_MISS, keyed by method
* name and actual arguments used to find it.
*/
private Map methodCache = new Hashtable();
private MethodMap methodMap = new MethodMap();
/**
* Standard constructor
*/
public ClassMap(Class clazz)
{
this.clazz = clazz;
populateMethodCache();
}
/**
* @return the class object whose methods are cached by this map.
*/
Class getCachedClass()
{
return clazz;
}
/**
* Find a Method using the methodKey
* provided.
*
* Look in the methodMap for an entry. If found,
* it'll either be a CACHE_MISS, in which case we
* simply give up, or it'll be a Method, in which
* case, we return it.
*
* If nothing is found, then we must actually go
* and introspect the method from the MethodMap.
*/
public Method findMethod(String name, Object[] params)
{
String methodKey = makeMethodKey(name, params);
Object cacheEntry = methodCache.get( methodKey );
if (cacheEntry == CACHE_MISS)
{
return null;
}
if (cacheEntry == null)
{
cacheEntry = methodMap.find( name,
params );
if ( cacheEntry == null )
{
methodCache.put( methodKey,
CACHE_MISS );
}
else
{
methodCache.put( methodKey,
cacheEntry );
}
}
// Yes, this might just be null.
return (Method) cacheEntry;
}
/**
* Populate the Map of direct hits. These
* are taken from all the public methods
* that our class provides.
*/
private void populateMethodCache()
{
StringBuffer methodKey;
/*
* get all publicly accessible methods
*/
Method[] methods = getAccessibleMethods(clazz);
/*
* map and cache them
*/
for (int i = 0; i < methods.length; i++)
{
Method method = methods[i];
/*
* now get the 'public method', the method declared by a
* public interface or class. (because the actual implementing
* class may be a facade...
*/
Method publicMethod = getPublicMethod( method );
/*
* it is entirely possible that there is no public method for
* the methods of this class (i.e. in the facade, a method
* that isn't on any of the interfaces or superclass
* in which case, ignore it. Otherwise, map and cache
*/
if ( publicMethod != null)
{
methodMap.add( publicMethod );
methodCache.put( makeMethodKey( publicMethod), publicMethod);
}
}
}
/**
* Make a methodKey for the given method using
* the concatenation of the name and the
* types of the method parameters.
*/
private String makeMethodKey(Method method)
{
Class[] parameterTypes = method.getParameterTypes();
StringBuffer methodKey = new StringBuffer(method.getName());
for (int j = 0; j < parameterTypes.length; j++)
{
/*
* If the argument type is primitive then we want
* to convert our primitive type signature to the
* corresponding Object type so introspection for
* methods with primitive types will work correctly.
*/
if (parameterTypes[j].isPrimitive())
{
if (parameterTypes[j].equals(Boolean.TYPE))
methodKey.append("java.lang.Boolean");
else if (parameterTypes[j].equals(Byte.TYPE))
methodKey.append("java.lang.Byte");
else if (parameterTypes[j].equals(Character.TYPE))
methodKey.append("java.lang.Character");
else if (parameterTypes[j].equals(Double.TYPE))
methodKey.append("java.lang.Double");
else if (parameterTypes[j].equals(Float.TYPE))
methodKey.append("java.lang.Float");
else if (parameterTypes[j].equals(Integer.TYPE))
methodKey.append("java.lang.Integer");
else if (parameterTypes[j].equals(Long.TYPE))
methodKey.append("java.lang.Long");
else if (parameterTypes[j].equals(Short.TYPE))
methodKey.append("java.lang.Short");
}
else
{
methodKey.append(parameterTypes[j].getName());
}
}
return methodKey.toString();
}
private static String makeMethodKey(String method, Object[] params)
{
StringBuffer methodKey = new StringBuffer().append(method);
for (int j = 0; j < params.length; j++)
{
if (params[j] == null)
params[j] = OBJECT;
methodKey.append(params[j].getClass().getName());
}
return methodKey.toString();
}
/**
* Retrieves public methods for a class. In case the class is not
* public, retrieves methods with same signature as its public methods
* from public superclasses and interfaces (if they exist). Basically
* upcasts every method to the nearest acccessible method.
*/
private static Method[] getAccessibleMethods(Class clazz)
{
Method[] methods = clazz.getMethods();
/*
* Short circuit for the (hopefully) majority of cases where the
* clazz is public
*/
if (Modifier.isPublic(clazz.getModifiers()))
{
return methods;
}
/*
* No luck - the class is not public, so we're going the longer way.
*/
MethodInfo[] methodInfos = new MethodInfo[methods.length];
for(int i = methods.length; i
{
methodInfos[i] = new MethodInfo(methods[i]);
}
int upcastCount = getAccessibleMethods(clazz, methodInfos, 0);
/*
* Reallocate array in case some method had no accessible counterpart.
*/
if(upcastCount < methods.length)
{
methods = new Method[upcastCount];
}
int j = 0;
for(int i = 0; i < methodInfos.length; ++i)
{
MethodInfo methodInfo = methodInfos[i];
if(methodInfo.upcast)
{
methods[j++] = methodInfo.method;
}
}
return methods;
}
/**
* Recursively finds a match for each method, starting with the class, and then
* searching the superclass and interfaces.
*
* @param clazz Class to check
* @param methodInfos array of methods we are searching to match
* @param upcastCount current number of methods we have matched
* @return count of matched methods
*/
private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfos, int upcastCount)
{
int l = methodInfos.length;
/*
* if this class is public, then check each of the currently
* 'non-upcasted' methods to see if we have a match
*/
if( Modifier.isPublic(clazz.getModifiers()) )
{
for(int i = 0; i < l && upcastCount < l; ++i)
{
try
{
MethodInfo methodInfo = methodInfos[i];
if(!methodInfo.upcast)
{
methodInfo.tryUpcasting(clazz);
}
upcastCount++;
}
catch(NoSuchMethodException e)
{
/*
* Intentionally ignored - it means
* it wasn't found in the current class
*/
}
}
/*
* Short circuit if all methods were upcast
*/
if(upcastCount == l)
{
return upcastCount;
}
}
/*
* Examine superclass
*/
Class superclazz = clazz.getSuperclass();
if(superclazz != null)
{
upcastCount = getAccessibleMethods(superclazz , methodInfos, upcastCount);
/*
* Short circuit if all methods were upcast
*/
if(upcastCount == l)
{
return upcastCount;
}
}
/*
* Examine interfaces. Note we do it even if superclazz == null.
* This is redundant as currently java.lang.Object does not implement
* any interfaces, however nothing guarantees it will not in future.
*/
Class[] interfaces = clazz.getInterfaces();
for(int i = interfaces.length; i
{
upcastCount = getAccessibleMethods(interfaces[i], methodInfos, upcastCount);
/*
* Short circuit if all methods were upcast
*/
if(upcastCount == l)
{
return upcastCount;
}
}
return upcastCount;
}
/**
* For a given method, retrieves its publicly accessible counterpart.
* This method will look for a method with same name
* and signature declared in a public superclass or implemented interface of this
* method's declaring class. This counterpart method is publicly callable.
*
* @param method a method whose publicly callable counterpart is requested.
* @return the publicly callable counterpart method. Note that if the parameter
* method is itself declared by a public class, this method is an identity
* function.
*/
public static Method getPublicMethod(Method method)
{
Class clazz = method.getDeclaringClass();
/*
* Short circuit for (hopefully the majority of) cases where the declaring
* class is public.
*/
if((clazz.getModifiers() & Modifier.PUBLIC) != 0)
{
return method;
}
return getPublicMethod(clazz, method.getName(), method.getParameterTypes());
}
/**
* Looks up the method with specified name and signature in the first public
* superclass or implemented interface of the class.
*
* @param class the class whose method is sought
* @param name the name of the method
* @param paramTypes the classes of method parameters
*/
private static Method getPublicMethod(Class clazz, String name, Class[] paramTypes)
{
/*
* if this class is public, then try to get it
*/
if((clazz.getModifiers() & Modifier.PUBLIC) != 0)
{
try
{
return clazz.getMethod(name, paramTypes);
}
catch(NoSuchMethodException e)
{
/*
* If the class does not have the method, then neither its
* superclass nor any of its interfaces has it so quickly return
* null.
*/
return null;
}
}
/*
* try the superclass
*/
Class superclazz = clazz.getSuperclass();
if ( superclazz != null )
{
Method superclazzMethod = getPublicMethod(superclazz, name, paramTypes);
if(superclazzMethod != null)
{
return superclazzMethod;
}
}
/*
* and interfaces
*/
Class[] interfaces = clazz.getInterfaces();
for(int i = 0; i < interfaces.length; ++i)
{
Method interfaceMethod = getPublicMethod(interfaces[i], name, paramTypes);
if(interfaceMethod != null)
{
return interfaceMethod;
}
}
return null;
}
/**
* Used for the iterative discovery process for public methods.
*/
private static final class MethodInfo
{
Method method;
String name;
Class[] parameterTypes;
boolean upcast;
MethodInfo(Method method)
{
this.method = null;
name = method.getName();
parameterTypes = method.getParameterTypes();
upcast = false;
}
void tryUpcasting(Class clazz)
throws NoSuchMethodException
{
method = clazz.getMethod(name, parameterTypes);
name = null;
parameterTypes = null;
upcast = true;
}
}
}
|
package etomica.space3d;
import etomica.space.Vector;
public class RotationTensor3D extends Tensor3D implements etomica.space.RotationTensor {
protected final Vector3D work;
public RotationTensor3D() {
super();
work = new Vector3D();
reset();
}
public void reset() {
xx = 1.0; xy = 0.0; xz = 0.0;
yx = 0.0; yy = 1.0; yz = 0.0;
zx = 0.0; zy = 0.0; zz = 1.0;
}
/**
* Sets tensor for rotation about the indicated axis (0=x,1=y,2=z) by
* the given angle.
*/
public void setAxial(int i, double theta) {
double st = Math.sin(theta);
double ct = Math.cos(theta);
switch(i) {
case 0: xx = 1.; xy = 0.; xz = 0.;
yx = 0.; yy = ct; yz = -st;
zx = 0.; zy = st; zz = ct;
return;
case 1: xx = ct; xy = 0.; xz = -st;
yx = 0.; yy = 1.; yz = 0.;
zx = st; zy = 0.; zz = ct;
return;
case 2: xx = ct; xy = -st; xz = 0.;
yx = st; yy = ct; yz = 0.;
zx = 0.; zy = 0.; zz = 1.;
return;
default: throw new IllegalArgumentException("Improper axis specified for Space3D.RotationTensor.setAxial");
}
}
/**
* Sets the tensor for rotation about the axis v by an angle theta.
*/
public void setRotationAxis(Vector v, double theta) {
double st = Math.sin(theta);
double ct = Math.cos(theta);
double vx = v.getX(0);
double vy = v.getX(1);
double vz = v.getX(2);
xx = ct + (1 - ct) * vx*vx;
yy = ct + (1 - ct) * vy*vy;
zz = ct + (1 - ct) * vz*vz;
xy = (1 - ct) * vx*vy;
yx = xy + st*vz;
xy -= st*vz;
xz = (1 - ct) * vx*vz;
zx = xz - st*vy;
xz += st*vy;
yz = (1 - ct) * vy*vz;
zy = yz + st*vx;
yz -= st*vx;
}
public void invert() {
transpose();
}
public void setQuaternions(double[] q) {
double q0 = q[0];
double q1 = q[1];
double q2 = q[2];
double q3 = q[3];
xx = q0*q0 + q1*q1 - q2*q2 - q3*q3;
xy = 2*(q1*q2 + q0*q3);
xz = 2*(q1*q3 - q0*q2);
yx = 2*(q1*q2 - q0*q3);
yy = q0*q0 - q1*q1 + q2*q2 - q3*q3;
yz = 2*(q2*q3 + q0*q1);
zx = 2*(q1*q3 + q0*q2);
zy = 2*(q2*q3 - q0*q1);
zz = q0*q0 - q1*q1 - q2*q2 + q3*q3;
}
public void setOrientation(IOrientationFull3D orientation3D) {
Vector direction = orientation3D.getDirection();
work.E(direction);
Vector secondaryDirection = orientation3D.getSecondaryDirection();
xx = direction.getX(0);
xy = direction.getX(1);
xz = direction.getX(2);
yx = secondaryDirection.getX(0);
yy = secondaryDirection.getX(1);
yz = secondaryDirection.getX(2);
work.XE(secondaryDirection);
zx = work.getX(0);
zy = work.getX(1);
zz = work.getX(2);
}
/**
* Method to test rotation tensor.
*/
public static void main (String[] args) {
Vector3D r1 = new Vector3D(2,2,3);
System.out.println("r1_before" + r1.toString());
Tensor3D tensor = new Tensor3D(new double[][] {{1,2,0},{1,1,2},{0,0,1}});
RotationTensor3D tensor2 = new RotationTensor3D();
tensor2.E(tensor);
System.out.println("tensor2_before " + tensor2.xx + " " +tensor2.xy +" "+tensor2.xz +" "+tensor2.yx +" "+tensor2.yy +" "+tensor2.yz +" "+tensor2.zx +" "+tensor2.zy +" "+tensor2.zz);
System.out.println();
tensor2.transform(r1);
System.out.println("r1_transform(tensor2)" + r1.toString());
tensor2.invert();
System.out.println("tensor2_invert " + tensor2.xx + " " +tensor2.xy +" "+tensor2.xz +" "+tensor2.yx +" "+tensor2.yy +" "+tensor2.yz +" "+tensor2.zx +" "+tensor2.zy +" "+tensor2.zz);
//tensor2.setAxial(1, 2*Math.PI);
//System.out.println("tensor2_rotate_360 " + tensor2.xx + " " +tensor2.xy +" "+tensor2.xz +" "+tensor2.yx +" "+tensor2.yy +" "+tensor2.yz +" "+tensor2.zx +" "+tensor2.zy +" "+tensor2.zz);
//System.out.println();
//r1.transform(tensor2);
//System.out.println("r1_afterInvert_andRotate360 " + r1.toString());
}//end of main
}
|
package ucar.nc2.iosp.grib;
import ucar.nc2.iosp.grid.GridServiceProvider;
import ucar.nc2.iosp.grid.GridIndexToNC;
import ucar.nc2.util.CancelTask;
import ucar.nc2.util.DiskCache;
import ucar.nc2.NetcdfFile;
import ucar.grib.*;
import ucar.grib.grib1.*;
import ucar.grib.grib2.*;
import ucar.grid.GridRecord;
import ucar.grid.GridIndex;
import ucar.grid.GridTableLookup;
import ucar.unidata.io.RandomAccessFile;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.net.URL;
public class GribGridServiceProvider extends GridServiceProvider {
private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GribGridServiceProvider.class);
private long rafLength; // length of the file when opened - used for syncing
private int saveEdition = 0;
private String saveLocation;
/**
* returns Grib data
*/
private Grib1Data dataReaderGrib1;
private Grib2Data dataReaderGrib2;
public boolean isValidFile(RandomAccessFile raf) {
try {
raf.seek(0);
raf.order(RandomAccessFile.BIG_ENDIAN);
Grib2Input g2i = new Grib2Input(raf);
int edition = g2i.getEdition();
return (edition == 1 || edition == 2);
} catch (Exception e) {
return false;
}
}
public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException {
this.raf = raf;
this.ncfile = ncfile;
this.rafLength = raf.length();
long start = System.currentTimeMillis();
if (GridServiceProvider.debugOpen)
System.out.println("GribGridServiceProvider open = " + ncfile.getLocation());
GridIndex index = getIndex( 0, raf.getLocation());
Map<String, String> attr = index.getGlobalAttributes();
saveEdition = attr.get("grid_edition").equals("2") ? 2 : 1;
GridTableLookup lookup;
if (saveEdition == 2) {
lookup = getLookup2();
} else {
lookup = getLookup1();
}
// make it into netcdf objects
new GridIndexToNC().open(index, lookup, saveEdition, ncfile, fmrcCoordSys, cancelTask);
ncfile.finish();
if (debugTiming) {
long took = System.currentTimeMillis() - start;
System.out.println(" open " + ncfile.getLocation() + " took=" + took + " msec ");
}
log.debug("GribGridServiceProvider.open " + ncfile.getLocation() + " took " + (System.currentTimeMillis() - start));
}
protected void open(GridIndex index, CancelTask cancelTask) throws IOException {
long start = System.currentTimeMillis();
GridTableLookup lookup = (saveEdition == 2) ? getLookup2() : getLookup1();
// make it into netcdf objects
new GridIndexToNC().open(index, lookup, saveEdition, ncfile, fmrcCoordSys, cancelTask);
ncfile.finish();
if (debugTiming) {
long took = System.currentTimeMillis() - start;
System.out.println(" open " + ncfile.getLocation() + " took=" + took + " msec ");
}
log.debug("GribGridServiceProvider.open from sync" + ncfile.getLocation() + " took " + (System.currentTimeMillis() - start));
}
protected GridTableLookup getLookup2() throws IOException {
Grib2Record firstRecord = null;
try {
Grib2Input g2i = new Grib2Input(raf);
long start2 = System.currentTimeMillis();
// params getProducts (implies unique GDSs too), oneRecord
// open it up and get the first product
raf.seek(0);
g2i.scan(false, true);
List records = g2i.getRecords();
firstRecord = (Grib2Record) records.get(0);
if (debugTiming) {
long took = System.currentTimeMillis() - start2;
System.out.println(" read one record took=" + took + " msec ");
}
} catch (NotSupportedException noSupport) {
System.err.println("NotSupportedException : " + noSupport);
}
Grib2GridTableLookup lookup = new Grib2GridTableLookup(firstRecord);
dataReaderGrib2 = new Grib2Data(raf);
return lookup;
}
protected GridTableLookup getLookup1() throws IOException {
Grib1Record firstRecord = null;
try {
Grib1Input g1i = new Grib1Input(raf);
long start2 = System.currentTimeMillis();
// params getProducts (implies unique GDSs too), oneRecord
// open it up and get the first product
raf.seek(0);
g1i.scan(false, true);
List records = g1i.getRecords();
firstRecord = (Grib1Record) records.get(0);
if (debugTiming) {
long took = System.currentTimeMillis() - start2;
System.out.println(" read one record took=" + took + " msec ");
}
} catch (NotSupportedException noSupport) {
System.err.println("NotSupportedException : " + noSupport);
} catch (NoValidGribException noValid) {
System.err.println("NoValidGribException : " + noValid);
}
Grib1GridTableLookup lookup = new Grib1GridTableLookup(firstRecord);
dataReaderGrib1 = new Grib1Data(raf);
return lookup;
}
/**
* Open the index file. If not exists, create it.
* When writing use DiskCache, to make sure location is writeable.
*
* @param edition which grib edition
* @param location location of the file. The index file has ".gbx" appended.
* @return ucar.grib.Index
* @throws IOException on io error
*/
protected GridIndex getIndex(int edition, String location) throws IOException {
// get an Index
//saveEdition = edition; //this is done after this method
saveLocation = location;
String indexLocation = location + ".gbx";
GridIndex index = null;
File indexFile;
if (indexLocation.startsWith("http:")) { // direct access through http
InputStream ios = indexExistsAsURL(indexLocation);
if (ios != null) {
//index = new Index();
//index.open(indexLocation, ios);
index = new GribReadIndex().open(indexLocation, ios);
log.debug("opened HTTP index = " + indexLocation);
return index;
} else { // otherwise write it to / get it from the cache
indexFile = DiskCache.getCacheFile(indexLocation);
log.debug("HTTP index = " + indexFile.getPath());
}
} else {
// always check first if the index file lives in the same dir as the regular file, and use it
indexFile = new File(indexLocation);
if (!indexFile.exists()) { // look in cache if need be
log.debug("saveIndexFile not exist " + indexFile.getPath() + " ++ " + indexLocation);
indexFile = DiskCache.getFile(indexLocation, alwaysInCache);
log.debug("GribGridServiceProvider: use " + indexFile.getPath());
}
}
// if index exist already, read it
if (!forceNewIndex && indexFile.exists()) {
//index = new Index();
boolean ok = true;
try {
//ok = index.open(indexFile.getPath());
index = new GribReadIndex().open(indexFile.getPath());
} catch (Exception e) {
ok = false;
}
if (ok && index != null ) {
log.debug(" opened index = " + indexFile.getPath());
// deal with possiblity that the grib file has changed, and the index should be extended or rewritten.
// action depends on extendMode
//String lengthS = index.getGlobalAttribute("length");
String lengthS = index.getGlobalAttributes().get("length");
long indexRafLength = (lengthS == null) ? 0 : Long.parseLong(lengthS);
if (indexRafLength != rafLength) {
if ((extendMode == IndexExtendMode.extend) && (indexRafLength < rafLength)) {
log.debug(" extend Index = " + indexFile.getPath());
//index = extendIndex(edition, raf, indexFile, index);
File gribFile = new File(raf.getLocation());
index = extendIndex(gribFile, indexFile, raf);
} else if (extendMode == IndexExtendMode.rewrite) {
// write new index
log.debug(" rewrite index = " + indexFile.getPath());
//index = writeIndex(edition, indexFile, raf);
index = writeIndex(indexFile, raf);
} else {
log.debug(" index had new length, ignore ");
}
}
} else { // rewrite if fail to open
log.debug(" write index = " + indexFile.getPath());
//index = writeIndex(edition, indexFile, raf);
index = writeIndex(indexFile, raf);
}
} else {
// doesnt exist (or is being forced), create it and write it
log.debug(" write index = " + indexFile.getPath());
//index = writeIndex(edition, indexFile, raf);
index = writeIndex(indexFile, raf);
}
return index;
}
private File getIndexFile(String location) throws IOException {
String indexLocation = location + ".gbx";
File indexFile = null;
if (indexLocation.startsWith("http:")) { // LOOK direct access through http maybe should disallow ??
indexFile = DiskCache.getCacheFile(indexLocation);
log.debug(" HTTP index = " + indexFile.getPath());
} else {
// always check first if the index file lives in the same dir as the regular file, and use it
indexFile = new File(indexLocation);
if (!indexFile.exists()) { // look in cache if need be
log.debug("GribGridServiceProvider: saveIndexFile not exist " + indexFile.getPath() + " ++ " + indexLocation);
indexFile = DiskCache.getFile(indexLocation, alwaysInCache);
log.debug("GribGridServiceProvider: use " + indexFile.getPath());
}
}
return indexFile;
}
private GridIndex writeIndex(File indexFile, RandomAccessFile raf) throws IOException {
GridIndex index = null;
try {
if (indexFile.exists()) {
indexFile.delete();
log.debug("Deleting old index " + indexFile.getPath());
}
if (saveEdition == 0) {
raf.seek(0);
Grib2Input g2i = new Grib2Input(raf);
saveEdition = g2i.getEdition();
}
File gribFile = new File(raf.getLocation());
if (saveEdition == 1) {
index = new Grib1WriteIndex().writeGribIndex(gribFile, indexFile.getPath(), raf, true);
} else if (saveEdition == 2) {
index = new Grib2WriteIndex().writeGribIndex(gribFile, indexFile.getPath(), raf, true);
}
return index;
} catch (NotSupportedException noSupport) {
System.err.println("NotSupportedException : " + noSupport);
}
return index;
}
public boolean sync() throws IOException {
if (syncMode == IndexExtendMode.none) return false;
// has the file chenged?
if (rafLength != raf.length()) {
File indexFile = getIndexFile(saveLocation);
//Index index;
GridIndex index;
if (syncMode == IndexExtendMode.read) {
log.debug(" sync read Index = " + indexFile.getPath());
try {
index = new GribReadIndex().open(indexFile.getPath());
} catch (Exception e) {
log.error(" sync read Index failed = " + indexFile.getPath());
return false;
}
} else if ((syncMode == IndexExtendMode.extend) && (rafLength < raf.length())) {
log.debug(" sync extend Index = " + indexFile.getPath());
//extendIndex(saveEdition, raf, indexFile, null);
//index = new Index();
//index.open(indexFile.getPath());
// i think the above was done because of bug on first making index had problems
File gribFile = new File(raf.getLocation());
index = extendIndex(gribFile, indexFile, raf);
} else {
// write new index
log.debug(" sync rewrite index = " + indexFile.getPath());
//index = writeIndex(saveEdition, indexFile, raf);
index = writeIndex(indexFile, raf);
}
// update so next sync call doesn't reread unnecessary
rafLength = raf.length();
// reconstruct the ncfile objects
ncfile.empty();
open(index, null);
return true;
}
return false;
}
private GridIndex extendIndex(File gribFile, File indexFile, RandomAccessFile raf) throws IOException {
GridIndex index = null;
try {
if (saveEdition == 0) {
raf.seek(0);
Grib2Input g2i = new Grib2Input(raf);
saveEdition = g2i.getEdition();
}
if (saveEdition == 1) {
index = new Grib1WriteIndex().extendGribIndex(gribFile, indexFile, indexFile.getPath(), raf, true);
} else if (saveEdition == 2) {
index = new Grib2WriteIndex().extendGribIndex(gribFile, indexFile, indexFile.getPath(), raf, true);
}
return index;
} catch (NotSupportedException noSupport) {
System.err.println("NotSupportedException : " + noSupport);
}
return index;
}
// if exists, return input stream, otherwise null
private InputStream indexExistsAsURL(String indexLocation) {
try {
URL url = new URL(indexLocation);
return url.openStream();
} catch (IOException e) {
return null;
}
}
protected float[] _readData(GridRecord gr) throws IOException {
GribGridRecord ggr = (GribGridRecord) gr;
if (saveEdition == 2) {
return dataReaderGrib2.getData(ggr.offset1, ggr.offset2);
} else {
return dataReaderGrib1.getData(ggr.offset1, ggr.decimalScale, ggr.bmsExists);
}
}
}
|
package org.jdesktop.swingx.color;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import org.jdesktop.swingx.JXMultiThumbSlider;
import org.jdesktop.swingx.multislider.ThumbRenderer;
public class GradientThumbRenderer extends JComponent implements ThumbRenderer {
private Image thumb_black;
private Image thumb_gray;
public GradientThumbRenderer() {
super();
try {
thumb_black = ImageIO.read(GradientThumbRenderer.class.getResourceAsStream("/icons/thumb_black.png"));
thumb_gray = ImageIO.read(GradientThumbRenderer.class.getResourceAsStream("/icons/thumb_gray.png"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean selected;
@Override
protected void paintComponent(Graphics g) {
JComponent thumb = this;
int w = thumb.getWidth();
g.setColor(getForeground());
g.fillRect(0, 0, w - 1, w - 1);
if (selected) {
g.drawImage(thumb_black, 0, 0, null);
} else {
g.drawImage(thumb_gray, 0, 0, null);
}
}
public JComponent getThumbRendererComponent(JXMultiThumbSlider slider, int index, boolean selected) {
Color c = (Color)slider.getModel().getThumbAt(index).getObject();
c = ColorUtil.removeAlpha(c);
this.setForeground(c);
this.selected = selected;
return this;
}
}
|
package jme3test.bullet;
import com.jme3.animation.AnimChannel;
import com.jme3.animation.AnimControl;
import com.jme3.animation.AnimEventListener;
import com.jme3.animation.Bone;
import com.jme3.animation.LoopMode;
import com.jme3.bullet.BulletAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.TextureKey;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.RagdollCollisionListener;
import com.jme3.bullet.control.KinematicRagdollControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;
import com.jme3.texture.Texture;
/**
* @author normenhansen
*/
public class TestRagdollCharacter extends SimpleApplication implements RagdollCollisionListener, AnimEventListener, ActionListener {
BulletAppState bulletAppState;
Node model;
KinematicRagdollControl ragdoll;
boolean leftStrafe = false, rightStrafe = false, forward = false, backward = false,
leftRotate = false, rightRotate = false;
AnimControl animControl;
AnimChannel animChannel;
public static void main(String[] args) {
TestRagdollCharacter app = new TestRagdollCharacter();
app.start();
}
public void simpleInitApp() {
setupKeys();
bulletAppState = new BulletAppState();
bulletAppState.setEnabled(true);
stateManager.attach(bulletAppState);
initWall(2,1,1);
cam.setLocation(new Vector3f(-8,0,-4));
cam.lookAt(new Vector3f(4,0,-7), Vector3f.UNIT_Y);
// bulletAppState.getPhysicsSpace().enableDebug(assetManager);
PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());
setupLight();
model = (Node) assetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
model.lookAt(new Vector3f(0,0,-1), Vector3f.UNIT_Y);
model.setLocalTranslation(4, 0, -7f);
ragdoll = new KinematicRagdollControl(0.5f);
setupSinbad(ragdoll);
ragdoll.addCollisionListener(this);
model.addControl(ragdoll);
getPhysicsSpace().add(ragdoll);
speed = 1.3f;
rootNode.attachChild(model);
AnimControl control = model.getControl(AnimControl.class);
animChannel = control.createChannel();
animChannel.setAnim("IdleTop");
control.addListener(this);
}
private void setupLight() {
DirectionalLight dl = new DirectionalLight();
dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal());
dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
rootNode.addLight(dl);
}
private PhysicsSpace getPhysicsSpace() {
return bulletAppState.getPhysicsSpace();
}
public void collide(Bone bone, PhysicsCollisionObject object, PhysicsCollisionEvent event) {
}
private void setupKeys() {
inputManager.addMapping("Rotate Left",
new KeyTrigger(KeyInput.KEY_H));
inputManager.addMapping("Rotate Right",
new KeyTrigger(KeyInput.KEY_K));
inputManager.addMapping("Walk Forward",
new KeyTrigger(KeyInput.KEY_U));
inputManager.addMapping("Walk Backward",
new KeyTrigger(KeyInput.KEY_J));
inputManager.addMapping("Slice",
new KeyTrigger(KeyInput.KEY_SPACE),
new KeyTrigger(KeyInput.KEY_RETURN));
inputManager.addListener(this, "Strafe Left", "Strafe Right");
inputManager.addListener(this, "Rotate Left", "Rotate Right");
inputManager.addListener(this, "Walk Forward", "Walk Backward");
inputManager.addListener(this, "Slice");
}
private void setupSinbad(KinematicRagdollControl ragdoll) {
ragdoll.addBoneName("Ulna.L");
ragdoll.addBoneName("Ulna.R");
ragdoll.addBoneName("Chest");
ragdoll.addBoneName("Foot.L");
ragdoll.addBoneName("Foot.R");
ragdoll.addBoneName("Hand.R");
ragdoll.addBoneName("Hand.L");
ragdoll.addBoneName("Neck");
ragdoll.addBoneName("Root");
ragdoll.addBoneName("Stomach");
ragdoll.addBoneName("Waist");
ragdoll.addBoneName("Humerus.L");
ragdoll.addBoneName("Humerus.R");
ragdoll.addBoneName("Thigh.L");
ragdoll.addBoneName("Thigh.R");
ragdoll.addBoneName("Calf.L");
ragdoll.addBoneName("Calf.R");
ragdoll.addBoneName("Clavicle.L");
ragdoll.addBoneName("Clavicle.R");
float eighth_pi = FastMath.PI * 0.125f;
ragdoll.setJointLimit("Waist", eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi);
ragdoll.setJointLimit("Chest", eighth_pi, eighth_pi, 0, 0, eighth_pi, eighth_pi);
}
public void initWall(float bLength, float bWidth, float bHeight) {
Box brick = new Box(Vector3f.ZERO, bLength, bHeight, bWidth);
brick.scaleTextureCoordinates(new Vector2f(1f, .5f));
Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
TextureKey key = new TextureKey("Textures/Terrain/BrickWall/BrickWall.jpg");
key.setGenerateMips(true);
Texture tex = assetManager.loadTexture(key);
mat2.setTexture("ColorMap", tex);
float startpt = bLength / 4;
float height = -5;
for (int j = 0; j < 15; j++) {
for (int i = 0; i < 4; i++) {
Vector3f ori = new Vector3f(i * bLength * 2 + startpt, bHeight + height, -10);
Geometry reBoxg = new Geometry("brick", brick);
reBoxg.setMaterial(mat2);
reBoxg.setLocalTranslation(ori);
//for geometry with sphere mesh the physics system automatically uses a sphere collision shape
reBoxg.addControl(new RigidBodyControl(1.5f));
reBoxg.setShadowMode(ShadowMode.CastAndReceive);
reBoxg.getControl(RigidBodyControl.class).setFriction(0.6f);
this.rootNode.attachChild(reBoxg);
this.getPhysicsSpace().add(reBoxg);
}
startpt = -startpt;
height += 2 * bHeight;
}
}
public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {
if (channel.getAnimationName().equals("SliceHorizontal")) {
channel.setLoopMode(LoopMode.DontLoop);
channel.setAnim("IdleTop", 5);
channel.setLoopMode(LoopMode.Loop);
}
}
public void onAnimChange(AnimControl control, AnimChannel channel, String animName) {
}
public void onAction(String binding, boolean value, float tpf) {
if (binding.equals("Rotate Left")) {
if (value) {
leftRotate = true;
} else {
leftRotate = false;
}
} else if (binding.equals("Rotate Right")) {
if (value) {
rightRotate = true;
} else {
rightRotate = false;
}
} else if (binding.equals("Walk Forward")) {
if (value) {
forward = true;
} else {
forward = false;
}
} else if (binding.equals("Walk Backward")) {
if (value) {
backward = true;
} else {
backward = false;
}
} else if (binding.equals("Slice")) {
if (value) {
animChannel.setAnim("SliceHorizontal");
animChannel.setSpeed(0.3f);
}
}
}
@Override
public void simpleUpdate(float tpf) {
if(forward){
model.move(model.getLocalRotation().multLocal(new Vector3f(0,0,1)).multLocal(tpf));
}else if(backward){
model.move(model.getLocalRotation().multLocal(new Vector3f(0,0,1)).multLocal(-tpf));
}else if(leftRotate){
model.rotate(0, tpf, 0);
}else if(rightRotate){
model.rotate(0, -tpf, 0);
}
fpsText.setText(cam.getLocation() + "/" + cam.getRotation());
}
}
|
package ca.ualberta.lard.model;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
import android.provider.Settings.Secure;
/**
* The User model deals with the unique username of the user. Username is
* decided by a component chosen by the user, which can be changed at any time,
* and a hash determined by the device id.
*/
public class User {
private String username;
private String androidId;
/**
* Constructor for User. Username is based off a name the user chooses and
* the id is set based on the users device.
* @param username
* @param context
*/
public User(String username, Context context) {
this.username = username;
// TODO: Make user Android_id a singleton
this.androidId = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
}
private String removeOctothorpe(String name) {
if (name.contains("
String cleanedName = name.replaceAll("
return cleanedName;
}
return name;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
String usernameWithSalt = (this.username + this.androidId);
md.update(usernameWithSalt.getBytes(), 0, usernameWithSalt.length());
//Converts message digest value in base 16 (hex)
String hash = new BigInteger(1, md.digest()).toString(16);
return this.username + "#" + hash;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm");
// todo this should probably explode?
}
// We've gotten to an unsalvageable state. They're anonymous with their androidID now.
return "Anonymous#" + androidId;
}
public String getAndroidId() {
return this.androidId;
}
}
|
package com.williamfiset.algorithms.dp;
public class CoinChange {
private static final int INF = 987654321;
public static int coinChange(int[] coins, int amount) {
if (coins == null) throw new IllegalArgumentException("Coins array is null");
if (coins.length == 0) throw new IllegalArgumentException("No coin values :/");
final int N = coins.length;
// Initialize table and set first row to be infinity
int[][] dp = new int[N + 1][amount + 1];
java.util.Arrays.fill(dp[0], INF);
dp[1][0] = 0;
// Iterate through all the coins
for (int i = 1; i <= N; i++) {
int coinValue = coins[i - 1];
for (int j = 1; j <= amount; j++) {
// Consider not selecting this coin
dp[i][j] = dp[i - 1][j];
// Try selecting this coin if it's better
if (j - coinValue >= 0 && dp[i][j - coinValue] + 1 < dp[i][j])
dp[i][j] = dp[i][j - coinValue] + 1;
}
}
// The amount we wanted to make cannot be made :/
if (dp[N][amount] == INF) return -1;
// Return the minimum number of coins needed
return dp[N][amount];
}
public static int coinChangeSpaceEfficient(int[] coins, int amount) {
if (coins == null) throw new IllegalArgumentException("Coins array is null");
// Initialize table and set everything to infinity except first cell
int[] dp = new int[amount + 1];
java.util.Arrays.fill(dp, INF);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coinValue : coins) {
if (i - coinValue >= 0 && dp[i - coinValue] + 1 < dp[i]) {
dp[i] = dp[i - coinValue] + 1;
}
}
}
// The amount we wanted to make cannot be made :/
if (dp[amount] == INF) return -1;
// Return the minimum number of coins needed
return dp[amount];
}
// The recursive approach has the advantage that it does not have to visit
// all possible states like the tabular approach does. This can speedup
// things especially if the coin denominations are large.
public static int coinChangeRecursive(int[] coins, int amount) {
if (coins == null) throw new IllegalArgumentException("Coins array is null");
if (amount < 0) return -1;
int[] dp = new int[amount + 1];
return coinChangeRecursive(amount, coins, dp);
}
// Private helper method to actually go the recursion
private static int coinChangeRecursive(int amount, int[] coins, int[] dp) {
// Base cases.
if (amount < 0) return -1;
if (amount == 0) return 0;
if (dp[amount] != 0) return dp[amount];
int minCoins = INF;
for (int coinValue : coins) {
int newAmount = amount - coinValue;
int value = coinChangeRecursive(newAmount, coins, dp);
if (value != -1 && value < minCoins) minCoins = value + 1;
}
// If we weren't able to find some coins to make our
// amount then cache -1 as the answer.
return dp[amount] = (minCoins == INF) ? -1 : minCoins;
}
public static void main(String[] args) {
int[] coins = {2, 6, 1};
System.out.println(coinChange(coins, 17));
System.out.println(coinChangeSpaceEfficient(coins, 17));
System.out.println(coinChangeRecursive(coins, 17));
}
}
|
package pro.consultit.userside.api;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import pro.consultit.userside.api.items.TaskCatalogStatus;
import pro.consultit.userside.api.items.TaskItem;
import pro.consultit.userside.api.items.task.TaskCatalogState;
import pro.consultit.userside.api.items.task.TaskCatalogType;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class UserSideTaskApi extends AbstractUserSideClient {
public UserSideTaskApi(ObjectMapper objectMapper, String url, String key) {
super(objectMapper, url, key);
}
public UserSideTaskApi(ObjectMapper objectMapper, String url, String key, int timeout) {
super(objectMapper, url, key, timeout);
}
public Integer addCustomerTask(int taskType, @NotNull Date dateToDo, @NotNull Integer customerId, String description,
Integer parentTask) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("subcat", "add"));
params.add(new BasicNameValuePair("work_typer", String.valueOf(taskType)));
params.add(new BasicNameValuePair("work_datedo", dateFormat.format(dateToDo)));
if (customerId != null) {
params.add(new BasicNameValuePair("usercode", String.valueOf(customerId)));
}
if (description != null) {
params.add(new BasicNameValuePair("opis", description));
}
if (parentTask != null) {
params.add(new BasicNameValuePair("parent_task_id", String.valueOf(parentTask)));
}
return executeIdRequest(params);
}
public Integer[] findCustomerTasks(@NotNull Integer customerId, @Nullable List<Integer> stateId) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "get_list"));
params.add(new BasicNameValuePair("customer_id", String.valueOf(customerId)));
if (stateId != null) {
params.add(new BasicNameValuePair("state_id", String.join(",", stateId.stream().map(Object::toString).collect(Collectors.toSet()))));
}
return executeListRequest(params).toArray(new Integer[0]);
}
@Deprecated
public Integer addTask(int taskType, @NotNull Date dateToDo, Integer houseCodeId, String description) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("subcat", "add"));
params.add(new BasicNameValuePair("work_typer", String.valueOf(taskType)));
params.add(new BasicNameValuePair("work_datedo", dateFormat.format(dateToDo)));
if (houseCodeId != null) {
params.add(new BasicNameValuePair("housecode", String.valueOf(houseCodeId)));
}
if (description != null) {
params.add(new BasicNameValuePair("opis", description));
}
return executeIdRequest(params);
}
public Integer addTask(int taskType, @NotNull Date dateToDo, String clientFullname, Integer nodeId, Integer cityCodeId, Integer houseCodeId, Integer apartmentNumber,
String description) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("subcat", "add"));
params.add(new BasicNameValuePair("work_typer", String.valueOf(taskType)));
params.add(new BasicNameValuePair("work_datedo", dateFormat.format(dateToDo)));
if (cityCodeId != null) {
params.add(new BasicNameValuePair("citycode", String.valueOf(cityCodeId)));
}
if (houseCodeId != null) {
params.add(new BasicNameValuePair("housecode", String.valueOf(houseCodeId)));
}
if (nodeId != null) {
params.add(new BasicNameValuePair("uzelcode", String.valueOf(nodeId)));
}
if (apartmentNumber != null) {
params.add(new BasicNameValuePair("apart", String.valueOf(apartmentNumber)));
}
if (clientFullname != null) {
params.add(new BasicNameValuePair("fio", clientFullname));
}
if (description != null) {
params.add(new BasicNameValuePair("opis", description));
}
return executeIdRequest(params);
}
public Integer addTaskComment(int taskId, String description) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("subcat", "comment_add"));
params.add(new BasicNameValuePair("id", String.valueOf(taskId)));
if (description != null) {
params.add(new BasicNameValuePair("comment", description));
}
return executeIdRequest(params);
}
public boolean checkTaskVerifyCode(int taskId, String code) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "check_verify_code"));
params.add(new BasicNameValuePair("id", String.valueOf(taskId)));
params.add(new BasicNameValuePair("verify_code", code));
return executeBooleanRequest(params);
}
public List<TaskCatalogStatus> getTaskStateList() throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "get_catalog_state"));
return executeIndexEncapsulatedRequest(TaskCatalogStatus.class, params);
}
public TaskItem getTask(int taskId) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "show"));
params.add(new BasicNameValuePair("id", String.valueOf(taskId)));
return executeEncapsulatedRequest(TaskItem.class, params);
}
public List<TaskItem> getTask(Integer[] taskList) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "show"));
params.add(new BasicNameValuePair("id", String.join(",", Arrays.stream(taskList).map(Object::toString).collect(Collectors.toSet()))));
if (taskList.length > 1) {
return Collections.singletonList(executeEncapsulatedRequest(TaskItem.class, params));
} else {
return executeIndexEncapsulatedRequest(TaskItem.class, params);
}
}
public List<TaskCatalogType> getTaskCatalogType(Integer type_id) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "get_catalog_type"));
if (type_id != null) {
params.add(new BasicNameValuePair("id", String.valueOf(type_id)));
}
return executeIndexEncapsulatedRequest(TaskCatalogType.class, params);
}
public List<TaskCatalogState> getTaskCatalogState(Integer state_id) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "get_catalog_state"));
if (state_id != null) {
params.add(new BasicNameValuePair("id", String.valueOf(state_id)));
}
return executeIndexEncapsulatedRequest(TaskCatalogState.class, params);
}
public boolean changeTaskState(@NotNull Integer id, @NotNull Integer state_id, Integer operator_id) throws IOException, UserSideApiErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("cat", "task"));
params.add(new BasicNameValuePair("action", "change_state"));
params.add(new BasicNameValuePair("id", String.valueOf(id)));
params.add(new BasicNameValuePair("state_id", String.valueOf(state_id)));
if (operator_id != null) {
params.add(new BasicNameValuePair("operator_id", String.valueOf(operator_id)));
}
return executeBooleanRequest(params);
}
}
|
package com.wizecore.graylog2.plugin;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.logging.Logger;
import javax.inject.Inject;
import org.graylog2.plugin.Message;
import org.graylog2.plugin.configuration.Configuration;
import org.graylog2.plugin.configuration.ConfigurationRequest;
import org.graylog2.plugin.configuration.fields.ConfigurationField;
import org.graylog2.plugin.configuration.fields.DropdownField;
import org.graylog2.plugin.configuration.fields.TextField;
import org.graylog2.plugin.configuration.fields.BooleanField;
import org.graylog2.plugin.outputs.MessageOutput;
import org.graylog2.plugin.streams.Stream;
import org.graylog2.syslog4j.Syslog;
import org.graylog2.syslog4j.SyslogConfigIF;
import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.impl.net.tcp.TCPNetSyslogConfig;
import org.graylog2.syslog4j.impl.net.tcp.ssl.SSLTCPNetSyslogConfig;
import org.graylog2.syslog4j.impl.net.udp.UDPNetSyslogConfig;
import org.graylog2.syslog4j.server.impl.net.tcp.ssl.SSLTCPNetSyslogServerConfig;
import com.google.common.collect.ImmutableMap;
import com.google.inject.assistedinject.Assisted;
/**
* Implementation of plugin to Graylog 2.0+ to send stream via Syslog
*
* @author Huksley <huksley@sdot.ru>
* extended for Graylog 2.0+ by TCollins
*/
public class SyslogOutput implements MessageOutput {
public final static int PORT_MIN = 9000;
public final static int PORT_MAX = 9099;
private Logger log = Logger.getLogger(SyslogOutput.class.getName());
private String host;
private int port;
private String protocol;
private SyslogIF syslog;
private String format;
private MessageSender sender;
public static MessageSender createSender(String fmt, Configuration conf) {
try {
if (fmt == null || fmt.equalsIgnoreCase("plain")) {
return new PlainSender();
} else
if (fmt == null || fmt.equalsIgnoreCase("transparent")) {
return new TrasparentSyslogSender(conf);
} else
if (fmt == null || fmt.equalsIgnoreCase("snare")) {
return new SnareWindowsSender();
} else
if (fmt == null || fmt.equalsIgnoreCase("structured")) {
return new StructuredSender();
} else
if (fmt == null || fmt.equalsIgnoreCase("full")) {
return new FullSender();
} else
if (fmt == null || fmt.equalsIgnoreCase("cef")) {
return new CEFSender();
} else
if (fmt == null || fmt.toLowerCase().startsWith("custom:")) {
String clazz = fmt.substring(fmt.indexOf(":") + 1);
return (MessageSender) Class.forName(clazz).newInstance();
} else {
throw new IllegalArgumentException("Unknown format: " + fmt);
}
} catch (Exception e) {
throw new IllegalArgumentException("Unable to accept format: " + fmt, e);
}
}
@Inject
public SyslogOutput(@Assisted Stream stream, @Assisted Configuration conf) {
host = conf.getString("host");
port = Integer.parseInt(conf.getString("port"));
protocol = conf.getString("protocol");
format = conf.getString("format");
if (format == null || format.equals("")) {
format = "plain";
}
log.info("Creating syslog output " + protocol + "://" + host + ":" + port + ", format " + format);
SyslogConfigIF config = null;
if (protocol.toLowerCase().equals("udp")) {
config = new UDPNetSyslogConfig();
} else
if (protocol.toLowerCase().equals("tcp")) {
config = new TCPNetSyslogConfig();
} else
if (protocol.toLowerCase().equals("tcp-ssl")) {
SSLTCPNetSyslogConfig sslConfig = new SSLTCPNetSyslogConfig();
String ks = conf.getString("keystore");
String ksp = conf.getString("keystorePassword");
String ts = conf.getString("truststore");
String tsp = conf.getString("truststorePassword");
if (ts == null || ts.trim().equals("")) {
ts = ks;
}
if (tsp == null || ts.trim().equals("")) {
tsp = ksp;
}
if (ksp == null) {
ksp = "";
}
if (ks == null) {
throw new IllegalArgumentException("Keystore not defined!");
}
config = sslConfig;
sslConfig.setKeyStore(ks);
sslConfig.setKeyStorePassword(ksp);
sslConfig.setTrustStore(ts);
sslConfig.setTrustStorePassword(tsp);
} else {
throw new IllegalArgumentException("Unknown protocol: " + protocol);
}
config.setHost(host);
config.setPort(port);
int maxlen = 16 * 1024;
try {
maxlen = Integer.parseInt(conf.getString("maxlen"));
} catch (Exception e) {
// Don`t care
}
config.setMaxMessageLength(maxlen);
config.setTruncateMessage(true);
String hash = protocol + "_" + host + "_" + port + "_" + format;
syslog = Syslog.exists(hash) ? Syslog.getInstance(hash) : Syslog.createInstance(hash, config);
sender = createSender(format, conf);
if (sender instanceof StructuredSender) {
// Always send via structured data
syslog.getConfig().setUseStructuredData(true);
} else
if (sender instanceof PlainSender || sender instanceof CEFSender) {
// Will write this fields manually
syslog.getConfig().setSendLocalName(false);
syslog.getConfig().setSendLocalTimestamp(false);
}
}
@Override
public boolean isRunning() {
return syslog != null;
}
@Override
public void stop() {
if (syslog != null) {
log.info("Stopping syslog instance: " + syslog);
Syslog.destroyInstance(syslog);
}
if (syslog != null) {
syslog = null;
}
}
@Override
public void write(List<Message> msgs) throws Exception {
for (Message msg: msgs) {
write(msg);
}
}
@Override
public void write(Message msg) throws Exception {
int level = -1;
if (level < 0) {
Object mlev = msg.getField("level");
if (mlev != null && mlev instanceof Number) {
level = ((Number) mlev).intValue();
}
}
if (level < 0) {
Object mlev = msg.getField("_level");
if (mlev != null && mlev instanceof Number) {
level = ((Number) mlev).intValue();
}
}
if (level < 0) {
Object mlev = msg.getField("original_level");
if (mlev != null && mlev instanceof String) {
if (mlev.toString().equalsIgnoreCase("INFO")) {
level = SyslogIF.LEVEL_INFO;
} else
if (mlev.toString().equalsIgnoreCase("SEVERE")) {
level = SyslogIF.LEVEL_ERROR;
} else
if (mlev.toString().equalsIgnoreCase("WARNING")) {
level = SyslogIF.LEVEL_WARN;
};
}
}
if (level < 0) {
level = SyslogIF.LEVEL_INFO;
}
if (sender != null) {
sender.send(syslog, level, msg);
} else {
syslog.log(level, msg.getMessage());
}
}
public interface Factory extends MessageOutput.Factory<SyslogOutput> {
@Override
SyslogOutput create(Stream stream, Configuration configuration);
@Override
Config getConfig();
@Override
Descriptor getDescriptor();
}
public static class Descriptor extends MessageOutput.Descriptor {
public Descriptor() {
super("Syslog Output", false, "", "Forwards stream to Syslog.");
}
}
public static class Config extends MessageOutput.Config {
@Override
public ConfigurationRequest getRequestedConfiguration() {
final ConfigurationRequest configurationRequest = new ConfigurationRequest();
final Map<String, String> protocols = ImmutableMap.of("tcp", "TCP", "udp", "UDP", "tcp-ssl", "SSL over TCP");
configurationRequest.addField(new DropdownField(
"protocol", "Message dispatch protocol", "tcp", protocols,
"The protocol that should be used to send messages to the remote syslog server",
ConfigurationField.Optional.NOT_OPTIONAL)
);
configurationRequest.addField(new TextField("host", "Syslog host", "localhost", "Remote host to send syslog messages to.", ConfigurationField.Optional.NOT_OPTIONAL));
configurationRequest.addField(new TextField("port", "Syslog port", "514", "Syslog port on the remote host. Default is 514.", ConfigurationField.Optional.NOT_OPTIONAL));
HashMap<String, String> types = new HashMap<String,String>();
types.put("plain", "plain");
types.put("structured", "structured");
types.put("cef", "cef");
types.put("full", "full");
types.put("transparent", "transparent");
types.put("snare", "snare");
final Map<String, String> formats = ImmutableMap.copyOf(types);
configurationRequest.addField(new DropdownField(
"format", "Message format", "plain", formats,
"Message format. For detailed explanation, see https://github.com/wizecore/graylog2-output-syslog",
ConfigurationField.Optional.NOT_OPTIONAL)
);
configurationRequest.addField(new BooleanField("removeHeader", "Remove header (only for transparent)", false, "Do not insert timestamp header when it forwards the message content."));
configurationRequest.addField(new TextField("maxlen", "Maximum message length", "", "Maximum message (body) length. Longer messages will be truncated. If not specified defaults to 16384 bytes.", ConfigurationField.Optional.OPTIONAL));
configurationRequest.addField(new TextField("keystore", "Key store", "", "Path to Java keystore (required for SSL over TCP). Must contain private key and cert for this client.", ConfigurationField.Optional.OPTIONAL));
configurationRequest.addField(new TextField("keystorePassword", "Key store password", "", "", ConfigurationField.Optional.OPTIONAL));
configurationRequest.addField(new TextField("truststore", "Trust store", "", "Path to Java keystore (required for SSL over TCP). Optional (if not set, equals to key store). Must contain peers we trust connecting to.", ConfigurationField.Optional.OPTIONAL));
configurationRequest.addField(new TextField("truststorePassword", "Trust store password", "", "", ConfigurationField.Optional.OPTIONAL));
return configurationRequest;
}
}
}
|
package org.jivesoftware.spark.ui;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.Res;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.spark.SparkManager;
/**
*
* @author ps
*/
public class BroadcastHistoryFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public BroadcastHistoryFrame() {
BroadcastHistoryArea = new javax.swing.JTextArea();
BroadcastHistoryArea.setEditable(false);
BroadcastHistoryArea.setLineWrap(true);
BroadcastHistoryArea.setWrapStyleWord(true);
initComponents();
}
public void readFromFile(String date) throws FileNotFoundException, IOException {
//String fileName = Spark.getSparkUserHome()+File.separator+"broadcast_history."+date+".txt";
String fileLocation=Spark.getSparkUserHome()+File.separator+"user"+File.separator+SparkManager.getSessionManager().getUsername()+"@"+SparkManager.getSessionManager().getServerAddress()+File.separator+"transcripts"+File.separator+"broadcast_history."+date+".txt";
File myfile = new File(fileLocation);
FileInputStream fis = new FileInputStream(myfile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
BroadcastHistoryArea.append(line+"\n");
}
br.close();
}
private void initComponents() {
SearchButton = new javax.swing.JToggleButton();
DateField = new javax.swing.JFormattedTextField();
SearchDate = new javax.swing.JLabel();
Date date=new Date();
Format formatter = new SimpleDateFormat("yyy-MM");
String myDate = formatter.format(date);
DateField.setValue(myDate);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JScrollPane panelPane = new JScrollPane(BroadcastHistoryArea);
SearchDate.setText(Res.getString("label.broadcast.history.search.date"));
setTitle(Res.getString("title.broadcast.history"));
try {
readFromFile(myDate);
} catch (IOException ex) {
Log.error("Couldn't read from file"+ex.getMessage()+ex.getStackTrace());
}
SearchButton.setText((Res.getString("button.search")));
SearchButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
SearchButtonMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelPane, javax.swing.GroupLayout.DEFAULT_SIZE, 533, javax.swing.GroupLayout.DEFAULT_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(SearchDate)
.addComponent(SearchButton)
.addComponent(DateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(panelPane, javax.swing.GroupLayout.DEFAULT_SIZE, 350, javax.swing.GroupLayout.DEFAULT_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(SearchDate)
.addGap(10, 10, 10)
.addComponent(DateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(SearchButton)))
.addContainerGap(15, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}
private void SearchButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SearchButtonMouseClicked
// TODO add your handling code here:
BroadcastHistoryArea.setText("");
try {
readFromFile(DateField.getText());
} catch (IOException ex) {
Log.error("Couldn't read from file"+ex.getCause()+ex.getStackTrace());
}
}//GEN-LAST:event_SearchButtonMouseClicked
public void run() {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
BroadcastHistoryFrame frame= new BroadcastHistoryFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
});
}
/**
* @param args the command line arguments
*/
private javax.swing.JFormattedTextField DateField;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea BroadcastHistoryArea;
private javax.swing.JLabel SearchDate;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToggleButton SearchButton;
// End of variables declaration//GEN-END:variables
}
|
package com.xpn.xwiki.plugin;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Api;
import com.xpn.xwiki.doc.XWikiAttachment;
public interface XWikiPluginInterface {
String getClassName();
String getName();
void setClassName(String name);
void setName(String name);
void init(XWikiContext context) throws XWikiException;
void virtualInit(XWikiContext context);
/*
Called to flush cache
*/
void flushCache();
/*
Called at the begin of each request
*/
void beginRendering(XWikiContext context);
/*
Called at the end of each request
*/
void endRendering(XWikiContext context);
String commonTagsHandler(String line, XWikiContext context);
String startRenderingHandler(String line, XWikiContext context);
String outsidePREHandler(String line, XWikiContext context);
String insidePREHandler(String line, XWikiContext context);
String endRenderingHandler(String line, XWikiContext context);
Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context);
/**
* Plugin extension point allowing the plugin to perform modifications to an attachement when the
* user clicks on an attachement in a document. The plugin is passed the original attachement and it has
* to return the new modified attachment.
*
* @param attachment the original attachment
* @param context the xwiki context object
* @return the modified attachment
*/
XWikiAttachment downloadAttachment(XWikiAttachment attachment, XWikiContext context);
}
|
package org.jivesoftware.sparkimpl.profile;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketInterceptor;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.packet.VCard;
import org.jivesoftware.smackx.provider.VCardProvider;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.util.Base64;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.manager.Enterprise;
import org.jivesoftware.sparkimpl.profile.ext.JabberAvatarExtension;
import org.jivesoftware.sparkimpl.profile.ext.VCardUpdateExtension;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
/**
* VCardManager handles all VCard loading/caching within Spark.
*
* @author Derek DeMoro
*/
public class VCardManager {
private VCard personalVCard;
private Map<String, VCard> vcards = new HashMap<String, VCard>();
private boolean vcardLoaded;
private File imageFile;
private final VCardEditor editor;
private File vcardStorageDirectory;
final MXParser parser;
private LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
/**
* Initialize VCardManager.
*/
public VCardManager() {
// Initialize parser
parser = new MXParser();
try {
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
}
catch (XmlPullParserException e) {
Log.error(e);
}
imageFile = new File(SparkManager.getUserDirectory(), "personal.png");
// Initialize vCard.
personalVCard = new VCard();
// Set VCard Storage
vcardStorageDirectory = new File(SparkManager.getUserDirectory(), "vcards");
vcardStorageDirectory.mkdirs();
initializeUI();
// Intercept all presence packets being sent and append vcard information.
PacketFilter presenceFilter = new PacketTypeFilter(Presence.class);
SparkManager.getConnection().addPacketWriterInterceptor(new PacketInterceptor() {
public void interceptPacket(Packet packet) {
Presence newPresence = (Presence)packet;
VCardUpdateExtension update = new VCardUpdateExtension();
JabberAvatarExtension jax = new JabberAvatarExtension();
PacketExtension updateExt = newPresence.getExtension(update.getElementName(), update.getNamespace());
PacketExtension jabberExt = newPresence.getExtension(jax.getElementName(), jax.getNamespace());
if (updateExt != null) {
newPresence.removeExtension(updateExt);
}
if (jabberExt != null) {
newPresence.removeExtension(jabberExt);
}
if (personalVCard != null) {
byte[] bytes = personalVCard.getAvatar();
if (bytes != null) {
String hash = org.jivesoftware.spark.util.StringUtils.hash(bytes);
update.setPhotoHash(hash);
jax.setPhotoHash(hash);
newPresence.addExtension(update);
newPresence.addExtension(jax);
}
}
}
}, presenceFilter);
editor = new VCardEditor();
// Start Listener
startQueueListener();
}
/**
* Listens for new VCards to lookup in a queue.
*/
private void startQueueListener() {
final Runnable queueListener = new Runnable() {
public void run() {
while (true) {
try {
String jid = queue.take();
reloadVCard(jid);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
TaskEngine.getInstance().submit(queueListener);
}
/**
* Adds a jid to lookup vCard.
*
* @param jid the jid to lookup.
*/
private void addToQueue(String jid) {
if (!queue.contains(jid)) {
queue.add(jid);
}
}
/**
* Adds VCard capabilities to menus and other components in Spark.
*/
private void initializeUI() {
boolean enabled = Enterprise.containsFeature(Enterprise.VCARD_FEATURE);
if (!enabled) {
return;
}
// Add Actions Menu
final JMenu contactsMenu = SparkManager.getMainWindow().getMenuByName(Res.getString("menuitem.contacts"));
final JMenu communicatorMenu = SparkManager.getMainWindow().getJMenuBar().getMenu(0);
JMenuItem editProfileMenu = new JMenuItem(SparkRes.getImageIcon(SparkRes.SMALL_BUSINESS_MAN_VIEW));
ResourceUtils.resButton(editProfileMenu, Res.getString("menuitem.edit.my.profile"));
int size = contactsMenu.getMenuComponentCount();
communicatorMenu.insert(editProfileMenu, 1);
editProfileMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingWorker vcardLoaderWorker = new SwingWorker() {
public Object construct() {
try {
personalVCard.load(SparkManager.getConnection());
}
catch (XMPPException e) {
Log.error("Error loading vcard information.", e);
}
return true;
}
public void finished() {
editor.editProfile(personalVCard, SparkManager.getWorkspace());
}
};
vcardLoaderWorker.start();
}
});
JMenuItem viewProfileMenu = new JMenuItem("", SparkRes.getImageIcon(SparkRes.FIND_TEXT_IMAGE));
ResourceUtils.resButton(viewProfileMenu, Res.getString("menuitem.lookup.profile"));
contactsMenu.insert(viewProfileMenu, size - 1);
viewProfileMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jidToView = JOptionPane.showInputDialog(SparkManager.getMainWindow(), Res.getString("message.enter.jabber.id") + ":", Res.getString("title.lookup.profile"), JOptionPane.QUESTION_MESSAGE);
if (ModelUtil.hasLength(jidToView) && jidToView.indexOf("@") != -1 && ModelUtil.hasLength(StringUtils.parseServer(jidToView))) {
viewProfile(jidToView, SparkManager.getWorkspace());
}
else if (ModelUtil.hasLength(jidToView)) {
JOptionPane.showMessageDialog(SparkManager.getMainWindow(), Res.getString("message.invalid.jabber.id"), Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
}
}
});
}
/**
* Displays <code>VCardViewer</code> for a particular JID.
*
* @param jid the jid of the user to display.
* @param parent the parent component to use for displaying dialog.
*/
public void viewProfile(final String jid, final JComponent parent) {
final SwingWorker vcardThread = new SwingWorker() {
VCard vcard = new VCard();
public Object construct() {
vcard = getVCard(jid);
return vcard;
}
public void finished() {
if (vcard.getError() != null || vcard == null) {
// Show vcard not found
JOptionPane.showMessageDialog(parent, Res.getString("message.unable.to.load.profile", jid), Res.getString("title.profile.not.found"), JOptionPane.ERROR_MESSAGE);
}
else {
editor.displayProfile(jid, vcard, parent);
}
}
};
vcardThread.start();
}
/**
* Displays the full profile for a particular JID.
*
* @param jid the jid of the user to display.
* @param parent the parent component to use for displaying dialog.
*/
public void viewFullProfile(final String jid, final JComponent parent) {
final SwingWorker vcardThread = new SwingWorker() {
VCard vcard = new VCard();
public Object construct() {
vcard = getVCard(jid);
return vcard;
}
public void finished() {
if (vcard.getError() != null || vcard == null) {
// Show vcard not found
JOptionPane.showMessageDialog(parent, Res.getString("message.unable.to.load.profile", jid), Res.getString("title.profile.not.found"), JOptionPane.ERROR_MESSAGE);
}
else {
editor.viewFullProfile(vcard, parent);
}
}
};
vcardThread.start();
}
/**
* Returns the VCard for this Spark user. This information will be cached after loading.
*
* @return this users VCard.
*/
public VCard getVCard() {
if (!vcardLoaded) {
try {
personalVCard.load(SparkManager.getConnection());
// If VCard is loaded, then save the avatar to the personal folder.
byte[] bytes = personalVCard.getAvatar();
if (bytes != null) {
ImageIcon icon = new ImageIcon(bytes);
icon = VCardManager.scale(icon);
if (icon != null && icon.getIconWidth() != -1) {
BufferedImage image = GraphicUtils.convert(icon.getImage());
ImageIO.write(image, "PNG", imageFile);
}
}
}
catch (Exception e) {
Log.error(e);
}
vcardLoaded = true;
}
return personalVCard;
}
/**
* Returns the Avatar in the form of an <code>ImageIcon</code>.
*
* @param vcard the vCard containing the avatar.
* @return the ImageIcon or null if no avatar was present.
*/
public static ImageIcon getAvatarIcon(VCard vcard) {
// Set avatar
byte[] bytes = vcard.getAvatar();
if (bytes != null) {
ImageIcon icon = new ImageIcon(bytes);
return GraphicUtils.scaleImageIcon(icon, 40, 40);
}
return null;
}
/**
* Returns the VCard. Will first look in VCard cache and only do a network
* operation if no vcard is found.
*
* @param jid the users jid.
* @return the VCard.
*/
public VCard getVCard(String jid) {
return getVCard(jid, true);
}
/**
* Loads the vCard from memory. If no vCard is found in memory,
* will add it to a loading queue for future loading. Users of this method
* should only use it if the correct vCard is not important the first time around.
*
* @param jid the users jid.
* @return the users VCard or an empty VCard.
*/
public VCard getVCardFromMemory(String jid) {
// Check in memory first.
if (vcards.containsKey(jid)) {
return vcards.get(jid);
}
// if not in memory
VCard vcard = loadFromFileSystem(jid);
if (vcard == null) {
addToQueue(jid);
// Create temp vcard.
vcard = new VCard();
vcard.setJabberId(jid);
}
return vcard;
}
/**
* Returns the VCard.
*
* @param jid the users jid.
* @param useCache true to check in cache, otherwise false will do a new network vcard operation.
* @return the VCard.
*/
public VCard getVCard(String jid, boolean useCache) {
jid = StringUtils.parseBareAddress(jid);
if (!vcards.containsKey(jid) || !useCache) {
VCard vcard = new VCard();
try {
// Check File system first
VCard localVCard = loadFromFileSystem(jid);
if (localVCard != null) {
localVCard.setJabberId(jid);
vcards.put(jid, localVCard);
return localVCard;
}
// Otherwise retrieve vCard from server and persist back out.
vcard.load(SparkManager.getConnection(), jid);
vcard.setJabberId(jid);
vcards.put(jid, vcard);
}
catch (XMPPException e) {
vcard.setJabberId(jid);
//Log.warning("Unable to load vcard for " + jid, e);
vcard.setError(new XMPPError(409));
vcards.put(jid, vcard);
}
// Persist XML
persistVCard(jid, vcard);
}
return vcards.get(jid);
}
/**
* Forces a reload of a <code>VCard</code>.
*
* @param jid the jid of the user.
* @return the new VCard.
*/
public VCard reloadVCard(String jid) {
jid = StringUtils.parseBareAddress(jid);
VCard vcard = new VCard();
try {
vcard.load(SparkManager.getConnection(), jid);
vcard.setJabberId(jid);
vcards.put(jid, vcard);
}
catch (XMPPException e) {
vcard.setError(new XMPPError(409));
vcards.put(jid, vcard);
}
// Persist XML
persistVCard(jid, vcard);
return vcards.get(jid);
}
/**
* Adds a new vCard to the cache.
*
* @param jid the jid of the user.
* @param vcard the users vcard to cache.
*/
public void addVCard(String jid, VCard vcard) {
vcard.setJabberId(jid);
vcards.put(jid, vcard);
}
/**
* Scales an image to the preferred avatar size.
*
* @param icon the icon to scale.
* @return the scaled version of the image.
*/
public static ImageIcon scale(ImageIcon icon) {
Image avatarImage = icon.getImage();
if (icon.getIconHeight() > 64 || icon.getIconWidth() > 64) {
avatarImage = avatarImage.getScaledInstance(-1, 64, Image.SCALE_SMOOTH);
}
return new ImageIcon(avatarImage);
}
/**
* Returns the URL of the avatar image associated with the users JID.
*
* @param jid the jid of the user.
* @return the URL of the image. If not image is found, a default avatar is returned.
*/
public URL getAvatar(String jid) {
// Handle own avatar file.
if (jid != null && StringUtils.parseBareAddress(SparkManager.getSessionManager().getJID()).equals(StringUtils.parseBareAddress(jid))) {
if (imageFile.exists()) {
try {
return imageFile.toURL();
}
catch (MalformedURLException e) {
Log.error(e);
}
}
else {
return SparkRes.getURL(SparkRes.DUMMY_CONTACT_IMAGE);
}
}
// Handle other users JID
ContactItem item = SparkManager.getWorkspace().getContactList().getContactItemByJID(jid);
URL avatarURL = null;
if (item != null) {
try {
avatarURL = item.getAvatarURL();
}
catch (MalformedURLException e) {
Log.error(e);
}
}
if (avatarURL == null) {
return SparkRes.getURL(SparkRes.DUMMY_CONTACT_IMAGE);
}
return avatarURL;
}
/**
* Searches all vCards for a specified phone number.
*
* @param phoneNumber the phoneNumber.
* @return the vCard which contains the phone number.
*/
public VCard searchPhoneNumber(String phoneNumber) {
for (VCard vcard : vcards.values()) {
String homePhone = getNumbersFromPhone(vcard.getPhoneHome("VOICE"));
String workPhone = getNumbersFromPhone(vcard.getPhoneWork("VOICE"));
String cellPhone = getNumbersFromPhone(vcard.getPhoneWork("CELL"));
String query = getNumbersFromPhone(phoneNumber);
if ((homePhone != null && homePhone.contains(query)) ||
(workPhone != null && workPhone.contains(query)) ||
(cellPhone != null && cellPhone.contains(query))) {
return vcard;
}
}
return null;
}
/**
* Parses out the numbers only from a phone number.
*
* @param number the full phone number.
* @return the phone number only (5551212)
*/
public static String getNumbersFromPhone(String number) {
if (number == null) {
return null;
}
number = number.replace("-", "");
number = number.replace("(", "");
number = number.replace(")", "");
number = number.replace(" ", "");
if (number.startsWith("1")) {
number = number.substring(1);
}
return number;
}
/**
* Sets the personal vcard of the user.
*
* @param vcard the users vCard.
*/
public void setPersonalVCard(VCard vcard) {
this.personalVCard = vcard;
}
/**
* Persist vCard information out for caching.
*
* @param jid the users jid.
* @param vcard the users vcard.
*/
private void persistVCard(String jid, VCard vcard) {
String fileName = Base64.encodeBytes(jid.getBytes());
byte[] bytes = vcard.getAvatar();
if (bytes != null) {
vcard.setAvatar(bytes);
}
// Set timestamp
vcard.setField("timestamp", Long.toString(System.currentTimeMillis()));
final String xml = vcard.toString();
File vcardFile = new File(vcardStorageDirectory, fileName);
// write xml to file
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(vcardFile), "UTF-8"));
out.write(xml);
out.close();
}
catch (IOException e) {
Log.error(e);
}
}
/**
* Attempts to load
*
* @param jid the jid of the user.
* @return the VCard if found, otherwise null.
*/
private VCard loadFromFileSystem(String jid) {
// Unescape JID
String fileName = Base64.encodeBytes(jid.getBytes());
final File vcardFile = new File(vcardStorageDirectory, fileName);
if (!vcardFile.exists()) {
return null;
}
try {
// Otherwise load from file system.
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(vcardFile), "UTF-8"));
VCardProvider provider = new VCardProvider();
parser.setInput(in);
VCard vcard = (VCard)provider.parseIQ(parser);
// Check to see if the file is older 10 minutes. If so, reload.
String timestamp = vcard.getField("timestamp");
if (timestamp != null) {
long time = Long.parseLong(timestamp);
long now = System.currentTimeMillis();
long hour = (1000 * 60) * 60;
if (now - time > hour) {
addToQueue(jid);
}
}
vcard.setJabberId(jid);
vcards.put(jid, vcard);
return vcard;
}
catch (Exception e) {
Log.warning("Unable to load vCard for " + jid, e);
}
return null;
}
}
|
package sizebay.catalog.client.model;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class TenantDetails {
private Long tenantId;
private String name;
private String domain;
private List<String> subdomains;
private String productIntegrationXmlLink;
private TenantPlan plan;
private String gtmCode;
private TenantProfile tenantProfile;
private SizeSystem sizeSystem;
private TenantOperation tenantOperation;
private TenantStatus status;
private CoverageDetails coverageDetails;
}
|
package com.yuvalshavit.effes.parser;
import com.google.common.base.Supplier;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.Token;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
public final class DenterHelper {
private final Queue<Token> dentsBuffer = new ArrayDeque<>();
private final Deque<Integer> indentations = new ArrayDeque<>();
private final Supplier<Token> tokens;
private final int nlToken;
private final int indentToken;
private final int dedentToken;
private Token nextNonNL;
public DenterHelper(Supplier<Token> tokens, int nlToken, int indentToken, int dedentToken) {
this.tokens = tokens;
this.nlToken = nlToken;
this.indentToken = indentToken;
this.dedentToken = dedentToken;
}
public Token nextToken() {
Token t;
if (nextNonNL != null) {
t = nextNonNL;
nextNonNL = null;
} else if (!dentsBuffer.isEmpty()) {
t = dentsBuffer.remove();
} else {
t = tokens.get();
}
if (indentations.isEmpty()) {
indentations.push(t.getCharPositionInLine());
}
final Token r;
if (t.getType() == nlToken) {
// fast-forward to the next non-NL
Token nextNext = tokens.get();
while (nextNext.getType() == nlToken) {
t = nextNext;
nextNext = tokens.get();
}
// nextNext is now a non-NL token; queue it up for the next call to this method
nextNonNL = nextNext;
String nlText = t.getText();
int indent = nlText.length() - 1; // evern NL has one \n char, so shorten the length to account for it
if (indent > 0 && nlText.charAt(0) == '\r') {
--indent; // If the NL also has a \r char, we should account for that as well
}
int prevIndent = indentations.peek();
if (indent == prevIndent) {
r = t; // just a newline
} else if (indent > prevIndent) {
indentations.push(indent);
r = createToken(indentToken, t);
} else {
r = unwindTo(indent, t);
}
} else if (t.getType() == Token.EOF && indentations.size() > 1) {
r = unwindTo(0, t);
nextNonNL = t; // still need the EOF after the unwinds!
} else {
r = t;
}
return r;
}
private Token createToken(int tokenType, Token copyFrom) {
CommonToken r = new CommonToken(copyFrom);
r.setType(tokenType);
return r;
}
/**
* Returns a DEDENT token, and also queues up additional DEDENTS as necessary.
* @param targetIndent the "size" of the indentation (number of spaces) by the end
* @param copyFrom the triggering token
* @return a DEDENT token, unless the indentation level is already okay
*/
private Token unwindTo(int targetIndent, Token copyFrom) {
assert dentsBuffer.isEmpty() : dentsBuffer;
// To make things easier, we'll queue up ALL of the dedents, and then pop off the first one.
// For example, here's how some text is analyzed:
// Text : Indentation : Action : Indents Deque
// [ baseline ] : 0 : nothing : [0]
// [ --foo ] : 2 : INDENT : [0, 2]
// [ baz ] : 0 : DEDENT x2 : [0]
// [ --again ] : 2 : INDENT : [0, 1]
// [ -weird ] : 1 : DEDENT,INDENT : [0, 1]
// This method is only interested in the DEDENT actions, although it may also enqueue an INDENT as seen above.
// (This will probably cause a parse error, but that's not our concern!)
while (true) {
int prevIndent = indentations.pop(); // throwing NoSuchElementException indicates a bug in this class
if (prevIndent == targetIndent) {
break;
}
dentsBuffer.add(createToken(dedentToken, copyFrom));
if (targetIndent > prevIndent) {
// "weird" condition above
dentsBuffer.add(createToken(indentToken, copyFrom));
break;
}
}
indentations.push(targetIndent);
return dentsBuffer.remove();
}
}
|
package net.drewke.tdme.tools.leveleditor.views;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import net.drewke.tdme.engine.Camera;
import net.drewke.tdme.engine.Engine;
import net.drewke.tdme.engine.Entity;
import net.drewke.tdme.engine.EntityPickingFilter;
import net.drewke.tdme.engine.Light;
import net.drewke.tdme.engine.Object3D;
import net.drewke.tdme.engine.PartitionQuadTree;
import net.drewke.tdme.engine.Rotation;
import net.drewke.tdme.engine.Timing;
import net.drewke.tdme.engine.Transformations;
import net.drewke.tdme.engine.fileio.models.DAEReader;
import net.drewke.tdme.engine.model.Color4;
import net.drewke.tdme.engine.model.Face;
import net.drewke.tdme.engine.model.FacesEntity;
import net.drewke.tdme.engine.model.Group;
import net.drewke.tdme.engine.model.Material;
import net.drewke.tdme.engine.model.Model;
import net.drewke.tdme.engine.model.Model.UpVector;
import net.drewke.tdme.engine.model.ModelHelper;
import net.drewke.tdme.engine.model.RotationOrder;
import net.drewke.tdme.engine.model.TextureCoordinate;
import net.drewke.tdme.engine.primitives.BoundingBox;
import net.drewke.tdme.engine.primitives.BoundingVolume;
import net.drewke.tdme.gui.events.GUIInputEventHandler;
import net.drewke.tdme.gui.events.GUIKeyboardEvent;
import net.drewke.tdme.gui.events.GUIKeyboardEvent.Type;
import net.drewke.tdme.gui.events.GUIMouseEvent;
import net.drewke.tdme.math.Vector3;
import net.drewke.tdme.math.Vector4;
import net.drewke.tdme.tools.leveleditor.TDMELevelEditor;
import net.drewke.tdme.tools.leveleditor.controller.LevelEditorScreenController;
import net.drewke.tdme.tools.leveleditor.logic.Level;
import net.drewke.tdme.tools.shared.files.LevelFileExport;
import net.drewke.tdme.tools.shared.files.LevelFileImport;
import net.drewke.tdme.tools.shared.model.LevelEditorEntity;
import net.drewke.tdme.tools.shared.model.LevelEditorEntity.EntityType;
import net.drewke.tdme.tools.shared.model.LevelEditorEntityLibrary;
import net.drewke.tdme.tools.shared.model.LevelEditorLevel;
import net.drewke.tdme.tools.shared.model.LevelEditorObject;
import net.drewke.tdme.tools.shared.model.LevelPropertyPresets;
import net.drewke.tdme.tools.shared.model.PropertyModelClass;
import net.drewke.tdme.tools.shared.tools.Tools;
import net.drewke.tdme.tools.shared.views.PopUps;
import net.drewke.tdme.tools.shared.views.View;
import com.jogamp.opengl.GLAutoDrawable;
/**
* TDME Level Editor View
* @author andreas.drewke
* @version $Id: 04313d20d0978eefc881024d6e0af748196c1425 $
*/
public final class LevelEditorView implements View, GUIInputEventHandler {
/**
* Object Color
* @author Andreas Drewke
* @version $Id$
*/
class ObjectColor {
/**
* Public constructor
* @param name
* @param colorMulR
* @param colorMulG
* @param colorMulB
* @param colorAddR
* @param colorAddG
* @param colorAddB
*/
public ObjectColor(
float colorMulR, float colorMulG, float colorMulB,
float colorAddR, float colorAddG, float colorAddB) {
this.colorMulR = colorMulR;
this.colorMulG = colorMulG;
this.colorMulB = colorMulB;
this.colorAddR = colorAddR;
this.colorAddG = colorAddG;
this.colorAddB = colorAddB;
}
// protected members
protected float colorMulR = 1.0f;
protected float colorMulG = 1.0f;
protected float colorMulB = 1.0f;
protected float colorAddR = 0.0f;
protected float colorAddG = 0.0f;
protected float colorAddB = 0.0f;
}
private final static String[] OBJECTCOLOR_NAMES = {"blue", "yellow", "magenta", "cyan", "none"};
private final static int MOUSE_BUTTON_NONE = 0;
private final static int MOUSE_BUTTON_LEFT = 1;
private final static int MOUSE_BUTTON_MIDDLE = 2;
private final static int MOUSE_BUTTON_RIGHT = 3;
private final static int MOUSE_DOWN_LAST_POSITION_NONE = -1;
private final static int MOUSE_PANNING_NONE = 0;
private final static int MOUSE_ROTATION_NONE = 0;
private int GRID_DIMENSION_X = 20;
private int GRID_DIMENSION_Y = 20;
private LevelEditorScreenController levelEditorScreenController;
private Engine engine;
private LevelEditorEntity selectedEntity;
private boolean reloadEntityLibrary;
private HashMap<String, ObjectColor> objectColors;
// camera properties
private Rotation camLookRotationX = new Rotation(-45f, new Vector3(1f, 0f, 0f));
private Rotation camLookRotationY = new Rotation(0f, new Vector3(0f, 1f, 0f));
private float camScale;
private float camScaleMax = 3f;
private float camScaleMin = 0.05f;
private Vector3 FORWARD_VECTOR = new Vector3(0f, 0f, 1f);
private Vector3 SIDE_VECTOR = new Vector3(1f, 0f, 0f);
private Vector3 camForwardVector = new Vector3();
private Vector3 camSideVector = new Vector3();
private Vector3 camLookAtToFromVector = new Vector3();
private Vector3 camLookAt = new Vector3();
// input properties
private int mouseDownLastX = MOUSE_DOWN_LAST_POSITION_NONE;
private int mouseDownLastY = MOUSE_DOWN_LAST_POSITION_NONE;
private boolean mouseDragging;
private Entity mouseDraggingLastObject;
private int mousePanningSide = MOUSE_PANNING_NONE;
private int mousePanningForward = MOUSE_PANNING_NONE;
private int mouseRotationX = MOUSE_ROTATION_NONE;
private int mouseRotationY = MOUSE_ROTATION_NONE;
private Vector3 gridCenter;
private Vector3 gridCenterLast;
private boolean gridEnabled;
private float gridY;
private boolean keyLeft;
private boolean keyRight;
private boolean keyUp;
private boolean keyDown;
private boolean keyA;
private boolean keyD;
private boolean keyW;
private boolean keyS;
private boolean keyC;
private boolean keyV;
private boolean keyX;
private boolean keyDelete;
private boolean keyPlus;
private boolean keyMinus;
private boolean keyR;
private boolean keyControl;
private boolean keyEscape;
float groundPlateWidth = 1.0f;
float groundPlateDepth = 1.0f;
private Model levelEditorGround;
private LevelEditorLevel level;
private ArrayList<Entity> selectedObjects = null;
private HashMap<String, Entity> selectedObjectsById = null;
private ArrayList<LevelEditorObject> pasteObjects = null;
private PopUps popUps;
private EntityPickingFilter entityPickingFilterNoGrid;
private Vector3 tmpVector3;
/**
* Public constructor
* @param pop ups
*/
public LevelEditorView(PopUps popUps) {
this.popUps = popUps;
level = TDMELevelEditor.getInstance().getLevel();
reloadEntityLibrary = false;
selectedEntity = null;
keyLeft = false;
keyRight = false;
keyUp = false;
keyDown = false;
keyPlus = false;
keyMinus = false;
keyR = false;
keyControl = false;
keyEscape = false;
mouseDownLastX = MOUSE_DOWN_LAST_POSITION_NONE;
mouseDownLastY = MOUSE_DOWN_LAST_POSITION_NONE;
mouseDragging = false;
mouseDraggingLastObject = null;
gridCenter = new Vector3();
gridCenterLast = null;
gridEnabled = true;
gridY = 0f;
objectColors = new HashMap<String, LevelEditorView.ObjectColor>();
objectColors.put("red", new ObjectColor(1.5f, 0.8f, 0.8f, 0.5f, 0.0f, 0.0f));
objectColors.put("green", new ObjectColor(0.8f, 1.5f, 0.8f, 0.0f, 0.5f, 0.0f));
objectColors.put("blue", new ObjectColor(0.8f, 0.8f, 1.5f, 0.0f, 0.0f, 0.5f));
objectColors.put("yellow", new ObjectColor(1.5f, 1.5f, 0.8f, 0.5f, 0.5f, 0.0f));
objectColors.put("magenta", new ObjectColor(1.5f, 0.8f, 1.5f, 0.5f, 0.0f, 0.5f));
objectColors.put("cyan", new ObjectColor(0.8f, 1.5f, 1.5f, 0.0f, 0.5f, 0.5f));
objectColors.put("none", new ObjectColor(1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f));
selectedObjects = new ArrayList<Entity>();
selectedObjectsById = new HashMap<String, Entity>();
pasteObjects = new ArrayList<LevelEditorObject>();
camScale = 1.0f;
camLookRotationX.update();
camLookRotationY.update();
levelEditorGround = createLevelEditorGroundPlateModel();
engine = Engine.getInstance();
entityPickingFilterNoGrid = new EntityPickingFilter() {
public boolean filterEntity(Entity entity) {
return entity.getId().startsWith("leveleditor.ground@") == false;
}
};
tmpVector3 = new Vector3();
}
/**
* @return pop ups
*/
public PopUps getPopUps() {
return popUps;
}
/**
* @return level file name
*/
public String getFileName() {
return new File(level.getFileName()).getName();
}
/**
* @return level
*/
public LevelEditorLevel getLevel() {
return level;
}
/**
* @return selected entity
*/
public LevelEditorEntity getSelectedEntity() {
return selectedEntity;
}
/**
* @return selected level editor object
*/
public LevelEditorObject getSelectedObject() {
if (selectedObjects.size() != 1) return null;
Entity selectedObject = selectedObjects.get(0);
return selectedObject != null && selectedObject.getId().startsWith("leveleditor.") == false?level.getObjectById(selectedObject.getId()):null;
}
/**
* @return grid enabled
*/
public boolean isGridEnabled() {
return gridEnabled;
}
/**
* @param grid enabled
*/
public void setGridEnabled(boolean gridEnabled) {
this.gridEnabled = gridEnabled;
if (gridEnabled) {
updateGrid();
} else {
removeGrid();
}
}
/**
* @return grid y
*/
public float getGridY() {
return gridY;
}
/**
* Set grid y position
* @param grid y
*/
public void setGridY(float gridY) {
if (gridEnabled) removeGrid();
this.gridY = gridY;
if (gridEnabled) updateGrid();
}
/**
* Load selected entity from library
* @param id
*/
public void loadEntityFromLibrary(int id) {
selectedEntity = TDMELevelEditor.getInstance().getEntityLibrary().getEntity(id);
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.events.GUIInputEventHandler#handleInputEvents()
*/
public void handleInputEvents() {
boolean keyDeleteBefore = keyDelete;
boolean keyControlBefore = keyControl;
boolean keyCBefore = keyC;
boolean keyVBefore = keyV;
boolean keyXBefore = keyX;
// handle keyboard events
for (int i = 0; i < engine.getGUI().getKeyboardEvents().size(); i++) {
GUIKeyboardEvent event = engine.getGUI().getKeyboardEvents().get(i);
// skip on processed events
if (event.isProcessed() == true) continue;
boolean isKeyDown = event.getType() == Type.KEY_PRESSED;
if (event.getKeyCode() == GUIKeyboardEvent.KEYCODE_CONTROL) keyControl = isKeyDown;
if (event.getKeyCode() == GUIKeyboardEvent.KEYCODE_ESCAPE) keyEscape = isKeyDown;
if (event.getKeyCode() == GUIKeyboardEvent.KEYCODE_LEFT) keyLeft = isKeyDown;
if (event.getKeyCode() == GUIKeyboardEvent.KEYCODE_RIGHT) keyRight = isKeyDown;
if (event.getKeyCode() == GUIKeyboardEvent.KEYCODE_UP) keyUp = isKeyDown;
if (event.getKeyCode() == GUIKeyboardEvent.KEYCODE_DOWN) keyDown = isKeyDown;
if (event.getKeyCode() == GUIKeyboardEvent.KEYCODE_BACKSPACE) keyDelete = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 'x') keyX = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 'c') keyC = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 'v') keyV = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 'a') keyA = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 'd') keyD = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 'w') keyW = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 's') keyS = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == '+') keyPlus = isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == '-') keyMinus= isKeyDown;
if (Character.toLowerCase(event.getKeyChar()) == 'r') keyR = isKeyDown;
}
// unselect objects by key escape
if (keyEscape == true && selectedObjects.size() > 0) {
ArrayList<Entity> objectsToRemove = new ArrayList<Entity>();
for (Entity selectedObject: selectedObjects) {
objectsToRemove.add(selectedObject);
}
for (Entity objectToRemove: objectsToRemove) {
setStandardObjectColorEffect(objectToRemove);
selectedObjects.remove(objectToRemove);
selectedObjectsById.remove(objectToRemove.getId());
}
levelEditorScreenController.unselectObjectsInObjectListBox();
}
// handle mouse events
for (int i = 0; i < engine.getGUI().getMouseEvents().size(); i++) {
GUIMouseEvent event = engine.getGUI().getMouseEvents().get(i);
// skip on processed events
if (event.isProcessed() == true) continue;
// check if dragging
if (event.getButton() != MOUSE_BUTTON_NONE) {
// check if dragging
if (mouseDragging == false) {
if (mouseDownLastX != event.getX() ||
mouseDownLastY != event.getY()) {
mouseDragging = true;
}
}
} else {
// unset dragging
if (mouseDragging == true) {
mouseDownLastX = MOUSE_DOWN_LAST_POSITION_NONE;
mouseDownLastY = MOUSE_DOWN_LAST_POSITION_NONE;
mouseDragging = false;
mouseDraggingLastObject = null;
}
}
// selection
if (event.getButton() == MOUSE_BUTTON_LEFT) {
// check if dragging
if (mouseDragging == false) {
if (mouseDownLastX != event.getX() ||
mouseDownLastY != event.getY()) {
mouseDragging = true;
}
}
// unselect current selected objects
if (keyControl == false) {
ArrayList<Entity> objectsToRemove = new ArrayList<Entity>();
for (Entity selectedObject: selectedObjects) {
if (mouseDragging == true && mouseDraggingLastObject == selectedObject) {
/// no op
} else {
objectsToRemove.add(selectedObject);
}
}
for (Entity objectToRemove: objectsToRemove) {
setStandardObjectColorEffect(objectToRemove);
selectedObjects.remove(objectToRemove);
selectedObjectsById.remove(objectToRemove.getId());
levelEditorScreenController.unselectObjectInObjectListBox(objectToRemove.getId());
}
}
// check if object was clicked first
Entity selectedObject = engine.getObjectByMousePosition(event.getX(), event.getY(), entityPickingFilterNoGrid);
// if not, check if ground plate was clicked
if (selectedObject == null) {
selectedObject = engine.getObjectByMousePosition(event.getX(), event.getY());
}
// select cell if any was selected
if (selectedObject != null) {
// add to selected objects if not yet done
if (mouseDragging == true && mouseDraggingLastObject == selectedObject) {
// no op
} else {
if (selectedObjects.contains(selectedObject) == false) {
setStandardObjectColorEffect(selectedObject);
setHighlightObjectColorEffect(selectedObject);
selectedObjects.add(selectedObject);
selectedObjectsById.put(selectedObject.getId(), selectedObject);
// select in objects listbox
levelEditorScreenController.selectObjectInObjectListbox(selectedObject.getId());
// select in entity library
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
if (levelEditorObject != null) {
TDMELevelEditor.getInstance().getLevelEditorEntityLibraryScreenController().selectEntity(levelEditorObject.getEntity().getId());
}
} else {
// undo add
setStandardObjectColorEffect(selectedObject);
selectedObjects.remove(selectedObject);
selectedObjectsById.remove(selectedObject.getId());
// unselect in objects listbox
levelEditorScreenController.unselectObjectInObjectListBox(selectedObject.getId());
}
}
}
// set mouse dragging last
mouseDraggingLastObject = selectedObject;
// update gui elements
updateGUIElements();
} else
// panning
if (event.getButton() == MOUSE_BUTTON_RIGHT) {
if (mouseDownLastX != MOUSE_DOWN_LAST_POSITION_NONE &&
mouseDownLastY != MOUSE_DOWN_LAST_POSITION_NONE) {
mousePanningSide = event.getX() - mouseDownLastX;
mousePanningForward = event.getY() - mouseDownLastY;
}
} else
if (event.getButton() == MOUSE_BUTTON_MIDDLE) {
centerObject();
if (mouseDownLastX != MOUSE_DOWN_LAST_POSITION_NONE &&
mouseDownLastY != MOUSE_DOWN_LAST_POSITION_NONE) {
mouseRotationX = event.getX() - mouseDownLastX;
mouseRotationY = event.getY() - mouseDownLastY;
}
}
// last mouse down position
if (event.getButton() != MOUSE_BUTTON_NONE) {
mouseDownLastX = event.getX();
mouseDownLastY = event.getY();
}
// process mouse wheel events
float mouseWheel = event.getWheelY();
if (mouseWheel != 0) {
camScale+= -mouseWheel * 0.05f;
if (camScale < camScaleMin) camScale = camScaleMin;
if (camScale > camScaleMax) camScale = camScaleMax;
}
}
// delete objects
if (keyDeleteBefore == true && keyDelete == false) {
removeObject();
}
// cut objects
if ((keyControlBefore == true || keyControl == true) &&
keyXBefore == true && keyX == false) {
copyObjects();
removeObject();
}
// copy objects
if ((keyControlBefore == true || keyControl == true) &&
keyCBefore == true && keyC == false) {
copyObjects();
}
// paste objects
if ((keyControlBefore == true || keyControl == true) &&
keyVBefore == true && keyV == false) {
pasteObjects();
}
}
/**
* Renders the scene
*/
public void display(GLAutoDrawable drawable) {
// camera
Camera cam = engine.getCamera();
// reload entity library
if (reloadEntityLibrary == true) {
LevelEditorEntityLibrary entityLibrary = TDMELevelEditor.getInstance().getEntityLibrary();
for (int i = 0; i < entityLibrary.getEntityCount(); i++) {
selectedEntity = entityLibrary.getEntityAt(i);
Tools.oseThumbnail(drawable, selectedEntity);
}
reloadEntityLibrary = false;
TDMELevelEditor.getInstance().getLevelEditorEntityLibraryScreenController().setEntityLibrary();
}
// do camera rotation by middle mouse button
if (mouseRotationX != MOUSE_ROTATION_NONE) {
camLookRotationY.setAngle(camLookRotationY.getAngle() + mouseRotationX);
camLookRotationY.update();
mouseRotationX = 0;
}
if (mouseRotationY != MOUSE_ROTATION_NONE) {
camLookRotationX.setAngle(camLookRotationX.getAngle() + mouseRotationY);
camLookRotationX.update();
mouseRotationY = 0;
}
// transfer keyboard inputs to rotations
if (keyA) camLookRotationY.setAngle(camLookRotationY.getAngle() + 1.0f);
if (keyD) camLookRotationY.setAngle(camLookRotationY.getAngle() - 1.0f);
if (keyW) camLookRotationX.setAngle(camLookRotationX.getAngle() + 1.0f);
if (keyS) camLookRotationX.setAngle(camLookRotationX.getAngle() - 1.0f);
if (keyMinus) camScale+= 0.05f;
if (keyPlus) camScale-= 0.05f;
if (camScale < camScaleMin) camScale = camScaleMin;
if (camScale > camScaleMax) camScale = camScaleMax;
if (keyR) {
camLookRotationX.setAngle(-45.0f);
camLookRotationX.update();
camLookRotationY.setAngle(0.0f);
camLookRotationY.update();
cam.getLookAt().set(level.computeCenter());
camScale = 1.0f;
}
// update cam look from rotations if changed
if (keyA || keyD) camLookRotationY.update();
if (keyW || keyS) {
if (camLookRotationX.getAngle() > 89.99f) camLookRotationX.setAngle(89.99f);
if (camLookRotationX.getAngle() < -89.99f) camLookRotationX.setAngle(-89.99f);
camLookRotationX.update();
}
// look at -> look to vector
camLookRotationX.getQuaternion().multiply(FORWARD_VECTOR, tmpVector3);
camLookRotationY.getQuaternion().multiply(tmpVector3, tmpVector3);
// apply look from rotations
camLookAtToFromVector.set(tmpVector3).scale(camScale * 10.0f);
// timing
Timing timing = engine.getTiming();
// do camera movement with arrow keys
camLookRotationY.getQuaternion().multiply(FORWARD_VECTOR, camForwardVector).scale(timing.getDeltaTime() / 1000f * 60f);
camLookRotationY.getQuaternion().multiply(SIDE_VECTOR, camSideVector).scale(timing.getDeltaTime() / 1000f * 60f);
if (keyUp) cam.getLookAt().sub(tmpVector3.set(camForwardVector).scale(0.1f));
if (keyDown) cam.getLookAt().add(tmpVector3.set(camForwardVector).scale(0.1f));
if (keyLeft) cam.getLookAt().sub(tmpVector3.set(camSideVector).scale(0.1f));
if (keyRight) cam.getLookAt().add(tmpVector3.set(camSideVector).scale(0.1f));
// mouse panning
if (mousePanningForward != MOUSE_PANNING_NONE) {
cam.getLookAt().sub(tmpVector3.set(camForwardVector).scale(mousePanningForward / 30f * camScale));
mousePanningForward = MOUSE_PANNING_NONE;
}
if (mousePanningSide != MOUSE_PANNING_NONE) {
cam.getLookAt().sub(tmpVector3.set(camSideVector).scale(mousePanningSide / 30f * camScale));
mousePanningSide = MOUSE_PANNING_NONE;
}
// look from with rotations
cam.getLookFrom().set(cam.getLookAt()).add(camLookAtToFromVector);
// up vector
cam.computeUpVector(cam.getLookFrom(), cam.getLookAt(), cam.getUpVector());
// update grid
gridCenter.set(cam.getLookAt());
updateGrid();
// do GUI
engine.getGUI().render();
engine.getGUI().handleEvents();
}
/**
* Select objects
* @param object ids
*/
public void selectObjects(ArrayList<String> objectIds) {
// remove all objects which are currently selected
ArrayList<Entity> objectsToRemove = (ArrayList<Entity>)selectedObjects.clone();
for (Entity objectToRemove: objectsToRemove) {
setStandardObjectColorEffect(objectToRemove);
selectedObjects.remove(objectToRemove);
selectedObjectsById.remove(objectToRemove.getId());
}
// select objects from selection
for (String objectId: objectIds) {
Entity selectedObject = engine.getEntity(objectId);
setStandardObjectColorEffect(selectedObject);
setHighlightObjectColorEffect(selectedObject);
selectedObjects.add(selectedObject);
selectedObjectsById.put(selectedObject.getId(), selectedObject);
}
// update gui elements
updateGUIElements();
}
/**
* Select objects by id
* @param id
*/
public void unselectObjects() {
// remove all objects which are currently selected
ArrayList<Entity> objectsToRemove = (ArrayList<Entity>)selectedObjects.clone();
for (Entity objectToRemove: objectsToRemove) {
setStandardObjectColorEffect(objectToRemove);
selectedObjects.remove(objectToRemove);
selectedObjectsById.remove(objectToRemove.getId());
}
levelEditorScreenController.unselectObjectsInObjectListBox();
// update gui elements
updateGUIElements();
}
/**
* Update GUI elements
* screen caption
* level size
* selected object
* object properties
* object 3d transformations
* object data
*/
private void updateGUIElements() {
levelEditorScreenController.setScreenCaption("Level Editor - " + level.getFileName());
levelEditorScreenController.setLevelSize(level.getDimension().getX(), level.getDimension().getZ(), level.getDimension().getY());
if (selectedObjects.size() == 1) {
Entity selectedObject = selectedObjects.get(0);
if (selectedObject != null && selectedObject.getId().startsWith("leveleditor.") == false) {
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
PropertyModelClass preset = levelEditorObject.getProperty("preset");
levelEditorScreenController.setObjectProperties(
preset != null?preset.getValue():"",
levelEditorObject.getProperties(),
null
);
levelEditorScreenController.setObject(
selectedObject.getTranslation(),
selectedObject.getScale(),
selectedObject.getRotations().get(level.getRotationOrder().getAxisXIndex()).getAngle(),
selectedObject.getRotations().get(level.getRotationOrder().getAxisYIndex()).getAngle(),
selectedObject.getRotations().get(level.getRotationOrder().getAxisZIndex()).getAngle()
);
// determine center
Vector3 objectCenter = null;
if (levelEditorObject.getEntity().getModel() != null) {
BoundingVolume bv = levelEditorObject.getEntity().getModel().getBoundingBox().clone();
bv.fromBoundingVolumeWithTransformations(bv, levelEditorObject.getTransformations());
objectCenter = bv.getCenter();
} else {
// TODO: this is not the center, applies currently to particle systems
objectCenter = levelEditorObject.getTransformations().getTranslation();
}
levelEditorScreenController.setObjectData(
levelEditorObject.getId(),
levelEditorObject.getDescription(),
levelEditorObject.getEntity().getName(),
objectCenter
);
} else {
levelEditorScreenController.unsetObjectData();
levelEditorScreenController.unsetObject();
levelEditorScreenController.unsetObjectProperties();
}
} else
if (selectedObjects.size() > 1) {
levelEditorScreenController.unsetObjectData();
levelEditorScreenController.setObject(
new Vector3(0f,0f,0f),
new Vector3(1f,1f,1f),
0f,
0f,
0f
);
levelEditorScreenController.unsetObjectProperties();
} else
if (selectedObjects.size() == 0) {
levelEditorScreenController.unsetObjectData();
levelEditorScreenController.unsetObject();
levelEditorScreenController.unsetObjectProperties();
}
// set up lights
for (int i = 0; i < 4; i++) {
levelEditorScreenController.setLight(
i,
level.getLightAt(i).getAmbient(),
level.getLightAt(i).getDiffuse(),
level.getLightAt(i).getSpecular(),
level.getLightAt(i).getPosition(),
level.getLightAt(i).getConstantAttenuation(),
level.getLightAt(i).getLinearAttenuation(),
level.getLightAt(i).getQuadraticAttenuation(),
level.getLightAt(i).getSpotTo(),
level.getLightAt(i).getSpotDirection(),
level.getLightAt(i).getSpotExponent(),
level.getLightAt(i).getSpotCutOff(),
level.getLightAt(i).isEnabled()
);
}
}
/**
* Updates objects list box
*/
public void setObjectsListBox() {
levelEditorScreenController.setObjectListbox(level.getObjectIdsIterator());
}
/**
* Unselect light presets
*/
public void unselectLightPresets() {
levelEditorScreenController.unselectLightPresets();
}
/**
* Load settings
*/
private void loadSettings() {
// read settings
FileInputStream fis = null;
Object tmp;
try {
fis = new FileInputStream("./settings/leveleditor.properties");
Properties settings = new Properties();
settings.load(fis);
gridEnabled = (tmp = settings.get("grid.enabled")) != null?tmp.equals("true") == true:true;
gridY = (tmp = settings.get("grid.y")) != null?Float.parseFloat(tmp.toString()):0f;
levelEditorScreenController.getMapPath().setPath((tmp = settings.get("map.path")) != null?tmp.toString():".");
TDMELevelEditor.getInstance().getLevelEditorEntityLibraryScreenController().setModelPath((tmp = settings.get("model.path")) != null?tmp.toString():".");
fis.close();
} catch (Exception ioe) {
if (fis != null) try { fis.close(); } catch (IOException ioeInner) {}
ioe.printStackTrace();
}
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.tools.shared.views.View#init()
*/
public void init() {
// reset engine and partition
engine.reset();
engine.setPartition(new PartitionQuadTree());
try {
levelEditorScreenController = new LevelEditorScreenController(this);
levelEditorScreenController.init();
levelEditorScreenController.getScreenNode().setInputEventHandler(this);
engine.getGUI().addScreen(levelEditorScreenController.getScreenNode().getId(), levelEditorScreenController.getScreenNode());
} catch (Exception e) {
e.printStackTrace();
}
// load settings
loadSettings();
// set up grid
levelEditorScreenController.setGrid(gridEnabled, gridY);
// set up map properties
levelEditorScreenController.setMapProperties(level.getProperties(), null);
// set up object properties presets
levelEditorScreenController.setObjectPresetIds(LevelPropertyPresets.getInstance().getObjectPropertiesPresets().keySet());
// set up ligh presets
levelEditorScreenController.setLightPresetsIds(LevelPropertyPresets.getInstance().getLightPresets().keySet());
updateGUIElements();
// lights
Light light0 = engine.getLightAt(0);
light0.getAmbient().set(1.0f, 1.0f, 1.0f, 1.0f);
light0.getDiffuse().set(1.0f, 1.0f, 1.0f, 1.0f);
light0.getPosition().set(0f, 20f, 0f, 1.0f);
light0.setEnabled(true);
// cam
Camera cam = engine.getCamera();
cam.setZNear(1f);
cam.setZFar(1000f);
cam.getLookAt().set(level.computeCenter());
gridCenter.set(cam.getLookAt());
// store cam look at
camLookAt.set(engine.getCamera().getLookAt());
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.tools.shared.views.View#activate()
*/
public void activate() {
engine.getGUI().resetRenderScreens();
engine.getGUI().addRenderScreen(levelEditorScreenController.getScreenNode().getId());
engine.getGUI().addRenderScreen(TDMELevelEditor.getInstance().getLevelEditorEntityLibraryScreenController().getScreenNode().getId());
engine.getGUI().addRenderScreen(popUps.getFileDialogScreenController().getScreenNode().getId());
engine.getGUI().addRenderScreen(popUps.getInfoDialogScreenController().getScreenNode().getId());
TDMELevelEditor.getInstance().getLevelEditorEntityLibraryScreenController().setEntityLibrary();
loadLevel();
// restore cam look at
engine.getCamera().getLookAt().set(camLookAt);
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.tools.shared.views.View#deactivate()
*/
public void deactivate() {
// store cam look at
camLookAt.set(engine.getCamera().getLookAt());
}
/**
* Store settings
*/
private void storeSettings() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("./settings/leveleditor.properties");
Properties settings = new Properties();
settings.put("grid.enabled", gridEnabled == true?"true":"false");
settings.put("grid.y", String.valueOf(gridY));
settings.put("map.path", levelEditorScreenController.getMapPath().getPath());
settings.put("model.path", TDMELevelEditor.getInstance().getLevelEditorEntityLibraryScreenController().getModelPath());
settings.store(fos, null);
fos.close();
} catch (Exception ioe) {
if (fos != null) try { fos.close(); } catch (IOException ioeInner) {}
ioe.printStackTrace();
}
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.tools.shared.views.View#dispose()
*/
public void dispose() {
// reset engine
Engine.getInstance().reset();
// store settings
storeSettings();
}
/**
* Set highlight object color effect
* @param object
*/
private void setHighlightObjectColorEffect(Entity object) {
ObjectColor red = objectColors.get("red");
object.getEffectColorAdd().set(red.colorAddR, red.colorAddG, red.colorAddB, 0.0f);
object.getEffectColorMul().set(red.colorMulR, red.colorMulG, red.colorMulB, 1.0f);
}
/**
* Set standard object color effect
* @param object
*/
private void setStandardObjectColorEffect(Entity object) {
ObjectColor color = objectColors.get("none");
object.getEffectColorAdd().set(color.colorAddR, color.colorAddG, color.colorAddB, 0.0f);
object.getEffectColorMul().set(color.colorMulR, color.colorMulG, color.colorMulB, 1.0f);
// color object
LevelEditorObject levelEditorObject = level.getObjectById(object.getId());
if (levelEditorObject == null) return;
// try to get object color from object properties
PropertyModelClass colorProperty = levelEditorObject.getProperty("object.color");
// try to get object color from model properties
if (colorProperty == null) colorProperty = levelEditorObject.getEntity().getProperty("object.color");
// handle object color if we have any
ObjectColor objectColor = colorProperty != null?objectColors.get(colorProperty.getValue()):null;
if (objectColor != null) {
object.getEffectColorAdd().set(
object.getEffectColorAdd().getRed() + objectColor.colorAddR,
object.getEffectColorAdd().getGreen() + objectColor.colorAddG,
object.getEffectColorAdd().getBlue() + objectColor.colorAddB,
0.0f
);
object.getEffectColorMul().set(
object.getEffectColorMul().getRed() * objectColor.colorMulR,
object.getEffectColorMul().getGreen() * objectColor.colorMulG,
object.getEffectColorMul().getBlue() * objectColor.colorMulB,
1.0f
);
}
}
/**
* Loads a level from internal level representation to tdme
*/
public void loadLevel() {
// reset engine / view
removeGrid();
engine.reset();
selectedObjects.clear();
selectedObjectsById.clear();
// set up level in engine
Level.setLight(engine, level, null);
Level.addLevel(engine, level, true, true, false, true, null);
setObjectsListBox();
unselectLightPresets();
updateGrid();
}
/**
* Update dynamic grid
*/
private void updateGrid() {
// check if to display grid
if (gridEnabled == false) return;
// TODO: use pool
// check if to move grid
int centerX = (int)gridCenter.getX();
int centerZ = (int)gridCenter.getZ();
int centerLastX = gridCenterLast == null?centerX:(int)gridCenterLast.getX();
int centerLastZ = gridCenterLast == null?centerZ:(int)gridCenterLast.getZ();
if (gridCenterLast != null &&
(centerLastX != centerX || centerLastZ != centerZ) == false) {
return;
}
int gridDimensionLeft = GRID_DIMENSION_X + (centerLastX < centerX?centerX - centerLastX:0);
int gridDimensionRight = GRID_DIMENSION_X + (centerLastX > centerX?centerLastX - centerX:0);
int gridDimensionNear = GRID_DIMENSION_Y + (centerLastZ < centerZ?centerZ - centerLastZ:0);
int gridDimensionFar = GRID_DIMENSION_Y + (centerLastZ > centerZ?centerLastZ - centerZ:0);
// create ground plates
int addedCells = 0;
int removedCells = 0;
int reAddedCells = 0;
for (int gridZ = -gridDimensionNear; gridZ < gridDimensionFar; gridZ++)
for (int gridX = -gridDimensionLeft; gridX < gridDimensionRight; gridX++) {
String objectId = "leveleditor.ground@" + (centerX + gridX) + "," + (centerZ + gridZ);
Entity _object = engine.getEntity(objectId);
if (gridX < -GRID_DIMENSION_X || gridX >= GRID_DIMENSION_X ||
gridZ < -GRID_DIMENSION_Y || gridZ >= GRID_DIMENSION_Y) {
if (_object != null) {
engine.removeEntity(objectId);
removedCells++;
}
} else
if (_object == null) {
_object = selectedObjectsById.get(objectId);
if (_object != null) {
engine.addEntity(_object);
reAddedCells++;
} else {
_object = new Object3D(objectId, levelEditorGround);
_object.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis0()));
_object.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis1()));
_object.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis2()));
_object.getTranslation().set(
centerX + (float)gridX * groundPlateWidth,
gridY-0.05f,
centerZ + (float)gridZ * groundPlateDepth);
//_object.setDynamicShadowingEnabled(false); // TODO
_object.setEnabled(true);
_object.setPickable(true);
_object.update();
setStandardObjectColorEffect(_object);
engine.addEntity(_object);
addedCells++;
}
}
}
// some stats to check if its working
// System.out.println("readded: " + reAddedCells + ", added: " + addedCells + ", removed: " + removedCells + ", total:" + engine.getEntityCount());
if (gridCenterLast == null) gridCenterLast = new Vector3();
gridCenterLast.set(gridCenter);
}
/**
* Remove grid
*/
private void removeGrid() {
if (gridCenterLast == null) return;
int removedCells = 0;
int centerX = (int)gridCenterLast.getX();
int centerZ = (int)gridCenterLast.getZ();
for (int gridZ = -GRID_DIMENSION_Y; gridZ < GRID_DIMENSION_Y; gridZ++)
for (int gridX = -GRID_DIMENSION_X; gridX < GRID_DIMENSION_X; gridX++) {
String objectId = "leveleditor.ground@" + (centerX + gridX) + "," + (centerZ + gridZ);
Entity _object = engine.getEntity(objectId);
if (_object != null) {
removedCells++;
engine.removeEntity(objectId);
}
}
// System.out.println("removed: " + removedCells + ", total:" + engine.getEntityCount());
gridCenterLast = null;
}
/**
* Creates a level editor ground plate
* @return ground
*/
private Model createLevelEditorGroundPlateModel() {
// ground selectedEntity
Model groundPlate = new Model(
"leveleditor.ground",
"leveleditor.ground",
UpVector.Y_UP,
RotationOrder.XYZ,
(BoundingBox)BoundingBox.createBoundingVolume(
new Vector3(0f,-0.01f,0f),
new Vector3(1f,+0.01f,1f)
)
);
// material
Material groundPlateMaterial = new Material("ground");
groundPlateMaterial.getDiffuseColor().setAlpha(0.75f);
groundPlateMaterial.setDiffuseTexture("resources/tools/leveleditor/textures", "groundplate.png");
groundPlateMaterial.getSpecularColor().set(0f, 0f, 0f, 1f);
groundPlate.getMaterials().put("ground", groundPlateMaterial);
// group
Group groundGroup = new Group(groundPlate, null, "ground", "ground");
// faces entity
// ground
FacesEntity groupFacesEntityGround = new FacesEntity(groundGroup, "leveleditor.ground.facesentity");
groupFacesEntityGround.setMaterial(groundPlateMaterial);
// faces entity
ArrayList<FacesEntity> groupFacesEntities = new ArrayList<FacesEntity>();
groupFacesEntities.add(groupFacesEntityGround);
// vertices
ArrayList<Vector3> groundVertices = new ArrayList<Vector3>();
// left, near, ground
groundVertices.add(new Vector3(0.0f, 0.0f, 0.0f));
// left, far, ground
groundVertices.add(new Vector3(0.0f, 0.0f, +groundPlateDepth));
// right far, ground
groundVertices.add(new Vector3(+groundPlateWidth, 0.0f, +groundPlateDepth));
// right, near, ground
groundVertices.add(new Vector3(+groundPlateWidth, 0.0f, 0.0f));
// normals
ArrayList<Vector3> groundNormals = new ArrayList<Vector3>();
// ground
groundNormals.add(new Vector3(0f, 1f, 0f));
// texture coordinates
ArrayList<TextureCoordinate> groundTextureCoordinates = new ArrayList<TextureCoordinate>();
groundTextureCoordinates.add(new TextureCoordinate(0f, 1f));
groundTextureCoordinates.add(new TextureCoordinate(0f, 0f));
groundTextureCoordinates.add(new TextureCoordinate(1f, 0f));
groundTextureCoordinates.add(new TextureCoordinate(1f, 1f));
// faces ground
ArrayList<Face> groundFacesGround = new ArrayList<Face>();
groundFacesGround.add(new Face(groundGroup,0,1,2,0,0,0,0,1,2));
groundFacesGround.add(new Face(groundGroup,2,3,0,0,0,0,2,3,0));
// set up faces entity
groupFacesEntityGround.setFaces(groundFacesGround);
// setup ground group
groundGroup.setVertices(groundVertices);
groundGroup.setNormals(groundNormals);
groundGroup.setTextureCoordinates(groundTextureCoordinates);
groundGroup.setFacesEntities(groupFacesEntities);
// register group
groundPlate.getGroups().put(groundGroup.getId(), groundGroup);
groundPlate.getSubGroups().put(groundGroup.getId(), groundGroup);
// prepare for indexed rendering
ModelHelper.prepareForIndexedRendering(groundPlate);
return groundPlate;
}
/**
* On object data apply
* @param name
* @param description
*/
public boolean objectDataApply(String name, String description) {
if (selectedObjects.size() != 1) return false;
// we only accept a single selection
Entity selectedObject = selectedObjects.get(0);
// skip if level editor internal object
if (selectedObject.getId().startsWith("leveleditor.")) return false;
// check if not a internal leveleditor object
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
// we need a associated object in level
if (levelEditorObject == null) return false;
// we always can safely set the description
levelEditorObject.setDescription(description);
// did id changed
if (levelEditorObject.getId().equals(name) == false) {
// yep, check if name is already in use
if (engine.getEntity(name) != null) {
return false;
}
// remove from engine, level and selection
String oldId = levelEditorObject.getId();
level.removeObject(levelEditorObject.getId());
engine.removeEntity(levelEditorObject.getId());
selectedObjectsById.clear();
selectedObjects.clear();
// set up id
levelEditorObject.setId(name);
// add to level, 3d engine
level.addObject(levelEditorObject);
Object3D object = new Object3D(levelEditorObject.getId(), levelEditorObject.getEntity().getModel());
object.fromTransformations(levelEditorObject.getTransformations());
object.setPickable(true);
setStandardObjectColorEffect(object);
setHighlightObjectColorEffect(object);
engine.addEntity(object);
// add to selected objects
selectedObjects.add(object);
selectedObjectsById.put(object.getId(), object);
// update in objects listbox
levelEditorScreenController.setObjectListbox(level.getObjectIdsIterator());
}
// set description
levelEditorObject.setDescription(description);
return true;
}
/**
* Places selected model on selected object
*/
public void placeObject() {
for(Entity selectedObject: selectedObjects) {
placeObject(selectedObject);
}
level.computeDimension();
updateGUIElements();
}
/**
* Places selected model on given object
*/
public void placeObject(Entity selectedObject) {
if (selectedEntity != null && selectedObject != null) {
// get selected level entity if it is one
LevelEditorObject selectedLevelEditorObject = level.getObjectById(selectedObject.getId());
// create level entity
Transformations levelEditorObjectTransformations = new Transformations();
// take translation of selected object as base
levelEditorObjectTransformations.getTranslation().set(selectedObject.getTranslation());
Vector3 centerSelectedObject =
selectedObject.getBoundingBox().getMin().clone().add(selectedObject.getBoundingBox().getMax()).scale(0.5f);
// compute center of selected model
Vector3 centerNewObject =
selectedEntity.getModel() != null?
selectedEntity.getModel().getBoundingBox().getCenter().clone():
new Vector3(0f,0f,0f);
// put new object on middle of selected object
levelEditorObjectTransformations.getTranslation().add(centerNewObject.clone().add(centerSelectedObject));
// set on selected object / y
if (selectedLevelEditorObject == null ||
selectedLevelEditorObject.getEntity().getType() == EntityType.PARTICLESYSTEM ||
selectedEntity.getType() == EntityType.PARTICLESYSTEM) {
levelEditorObjectTransformations.getTranslation().setY(
gridY +
(selectedEntity.getModel() != null?
-selectedEntity.getModel().getBoundingBox().getMin().getY():
0f
)
);
} else {
// create transformed level editor object bounding box
BoundingVolume bv = selectedLevelEditorObject.getEntity().getModel().getBoundingBox().clone();
bv.fromBoundingVolumeWithTransformations(
selectedLevelEditorObject.getEntity().getModel().getBoundingBox(),
selectedLevelEditorObject.getTransformations()
);
levelEditorObjectTransformations.getTranslation().setY(
bv.computeDimensionOnAxis(new Vector3(0f,1f,0f)) / 2 + bv.getCenter().getY() +
-selectedEntity.getModel().getBoundingBox().getMin().getY()
);
}
// standard scale
levelEditorObjectTransformations.getScale().set(new Vector3(1f,1f,1f));
// standard rotations
levelEditorObjectTransformations.getPivot().set(selectedEntity.getPivot());
levelEditorObjectTransformations.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis0()));
levelEditorObjectTransformations.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis1()));
levelEditorObjectTransformations.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis2()));
levelEditorObjectTransformations.update();
// check if entity already exists
for (int i = 0; i < level.getObjectCount(); i++) {
LevelEditorObject levelEditorObject = level.getObjectAt(i);
if (levelEditorObject.getEntity() == selectedEntity &&
levelEditorObject.getTransformations().getTranslation().equals(levelEditorObjectTransformations.getTranslation())) {
// we already have a object with selected model on this translation
return;
}
}
// create new level editor object
LevelEditorObject levelEditorObject = new LevelEditorObject(
selectedEntity.getName() + "_" + level.allocateObjectId(),
"",
levelEditorObjectTransformations,
selectedEntity
);
// add to level
level.addObject(levelEditorObject);
// add model to 3d engine
if (levelEditorObject.getEntity().getModel() != null) {
Object3D object = new Object3D(levelEditorObject.getId(), levelEditorObject.getEntity().getModel());
object.fromTransformations(levelEditorObjectTransformations);
object.setPickable(true);
engine.addEntity(object);
}
// add particle system to 3d engine
if (levelEditorObject.getEntity().getType() == EntityType.PARTICLESYSTEM) {
Entity object = Level.createParticleSystem(levelEditorObject.getEntity().getParticleSystem(), levelEditorObject.getId(), false);
object.fromTransformations(levelEditorObjectTransformations);
object.setPickable(true);
engine.addEntity(object);
}
// add to objects listbox
levelEditorScreenController.setObjectListbox(level.getObjectIdsIterator());
}
}
/**
* Removes selected object
*/
public void removeObject() {
ArrayList<Entity> objectsToRemove = new ArrayList<Entity>();
for (Entity selectedObject: selectedObjects) {
if (selectedObject != null && selectedObject.getId().startsWith("leveleditor.") == false) {
level.removeObject(selectedObject.getId());
engine.removeEntity(selectedObject.getId());
objectsToRemove.add(selectedObject);
}
}
for (Entity objectToRemove: objectsToRemove) {
selectedObjects.remove(objectToRemove);
}
level.computeDimension();
// update objects listbox
levelEditorScreenController.setObjectListbox(level.getObjectIdsIterator());
updateGUIElements();
}
/**
* Centers selected objects
*/
public void colorObject() {
// skip if no objects selected
if (selectedObjects.size() == 0) return;
// color selected objects in blue
for (Entity selectedObject: selectedObjects) {
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
if (levelEditorObject == null) continue;
String color = OBJECTCOLOR_NAMES[0];
PropertyModelClass colorProperty = levelEditorObject.getProperty("object.color");
if (colorProperty == null) {
levelEditorObject.addProperty("object.color", color);
} else {
// switch color
color = colorProperty.getValue();
for (int i = 0; i < OBJECTCOLOR_NAMES.length; i++) {
if (color.equalsIgnoreCase(OBJECTCOLOR_NAMES[i])) {
color = OBJECTCOLOR_NAMES[(i + 1) % OBJECTCOLOR_NAMES.length];
break;
}
}
// set up color in object properties
if (color.equals("none")) {
levelEditorObject.removeProperty("object.color");
} else {
levelEditorObject.updateProperty(colorProperty.getName(), "object.color", color);
}
}
setStandardObjectColorEffect(selectedObject);
setHighlightObjectColorEffect(selectedObject);
}
// set object properties if changed
if (selectedObjects.size() == 1) {
Entity selectedObject = selectedObjects.get(0);
if (selectedObject != null && selectedObject.getId().startsWith("leveleditor.") == false) {
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
PropertyModelClass preset = levelEditorObject.getProperty("preset");
levelEditorScreenController.setObjectProperties(
preset != null?preset.getValue():"",
levelEditorObject.getProperties(),
null
);
} else {
levelEditorScreenController.unsetObjectProperties();
}
} else
if (selectedObjects.size() > 1) {
levelEditorScreenController.unsetObjectProperties();
}
}
/**
* Centers selected objects
*/
public void centerObject() {
// skip if no objects selected
if (selectedObjects.size() == 0) {
return;
}
// compute center of selected objects
Vector3 center = new Vector3();
for (Entity selectedObject: selectedObjects) {
center.add(
selectedObject.getBoundingBoxTransformed().getMin().clone().add(
selectedObject.getBoundingBoxTransformed().getMax()
).
scale(0.5f)
);
}
engine.getCamera().getLookAt().set(
center.scale(1.0f / selectedObjects.size())
);
}
/**
* Apply object translation
* @param x
* @param y
* @param z
*/
public void objectTranslationApply(float x, float y, float z) {
if (selectedObjects.size() == 0) return;
// handle single object
if (selectedObjects.size() == 1) {
Entity selectedObject = selectedObjects.get(0);
LevelEditorObject currentEntity = level.getObjectById(selectedObject.getId());
if (currentEntity == null) return;
currentEntity.getTransformations().getTranslation().set(x,y,z);
currentEntity.getTransformations().update();
selectedObject.fromTransformations(currentEntity.getTransformations());
} else
if (selectedObjects.size() > 1) {
// multiple objects
for (Entity selectedObject: selectedObjects) {
LevelEditorObject currentEntity = level.getObjectById(selectedObject.getId());
if (currentEntity == null) continue;
currentEntity.getTransformations().getTranslation().add(new Vector3(x,y,z));
currentEntity.getTransformations().update();
selectedObject.fromTransformations(currentEntity.getTransformations());
}
// reset controller object properties
levelEditorScreenController.setObject(
new Vector3(0f,0f,0f),
new Vector3(1f,1f,1f),
0f,
0f,
0f
);
}
level.computeDimension();
updateGUIElements();
}
/**
* Apply object scale
* @param x
* @param y
* @param z
*/
public void objectScaleApply(float x, float y, float z) {
if (selectedObjects.size() == 0) return;
// handle single object
if (selectedObjects.size() == 1) {
Entity selectedObject = selectedObjects.get(0);
LevelEditorObject currentEntity = level.getObjectById(selectedObject.getId());
if (currentEntity == null) return;
currentEntity.getTransformations().getScale().set(x,y,z);
currentEntity.getTransformations().update();
selectedObject.fromTransformations(currentEntity.getTransformations());
} else
if (selectedObjects.size() > 1) {
// multiple objects
for (Entity selectedObject: selectedObjects) {
LevelEditorObject currentEntity = level.getObjectById(selectedObject.getId());
if (currentEntity == null) continue;
currentEntity.getTransformations().getScale().scale(new Vector3(x,y,z));
currentEntity.getTransformations().update();
selectedObject.fromTransformations(currentEntity.getTransformations());
}
// reset controller object properties
levelEditorScreenController.setObject(
new Vector3(0f,0f,0f),
new Vector3(1f,1f,1f),
0f,
0f,
0f
);
}
level.computeDimension();
updateGUIElements();
}
/**
* Apply object rotations
* @param x
* @param y
* @param z
*/
public void objectRotationsApply(float x, float y, float z) {
if (selectedObjects.size() == 0) return;
// handle single object
if (selectedObjects.size() == 1) {
Entity selectedObject = selectedObjects.get(0);
LevelEditorObject currentEntity = level.getObjectById(selectedObject.getId());
if (currentEntity == null) return;
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisXIndex()).setAngle(x);
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisYIndex()).setAngle(y);
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisZIndex()).setAngle(z);
currentEntity.getTransformations().update();
selectedObject.fromTransformations(currentEntity.getTransformations());
} else
if (selectedObjects.size() > 1) {
// multiple objects
for (Entity selectedObject: selectedObjects) {
LevelEditorObject currentEntity = level.getObjectById(selectedObject.getId());
if (currentEntity == null) continue;
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisXIndex()).setAngle(
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisXIndex()).getAngle() + x
);
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisYIndex()).setAngle(
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisYIndex()).getAngle() + y
);
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisZIndex()).setAngle(
currentEntity.getTransformations().getRotations().get(level.getRotationOrder().getAxisZIndex()).getAngle() + z
);
currentEntity.getTransformations().update();
selectedObject.fromTransformations(currentEntity.getTransformations());
}
// reset controller object properties
levelEditorScreenController.setObject(
new Vector3(0f,0f,0f),
new Vector3(1f,1f,1f),
0f,
0f,
0f
);
}
level.computeDimension();
updateGUIElements();
}
/**
* Save a map property
* @param old name
* @param name
* @param value
* @return success
*/
public boolean mapPropertySave(String oldName, String name, String value) {
// try to update property
if (level.updateProperty(oldName, name, value) == true) {
// reload model properties
levelEditorScreenController.setMapProperties(
level.getProperties(),
name
);
return true;
}
return false;
}
/**
* Add a map property
* @return success
*/
public boolean mapPropertyAdd() {
// try to add property
if (level.addProperty("new.property", "new.value")) {
// reload model properties
levelEditorScreenController.setMapProperties(
level.getProperties(),
"new.property"
);
return true;
}
return false;
}
/**
* Remove a map property from model properties
* @param name
* @return success
*/
public boolean mapPropertyRemove(String name) {
// try to remove property
int idx = level.getPropertyIndex(name);
if (idx != -1 && level.removeProperty(name) == true) {
// get property first at index that was removed
PropertyModelClass property = level.getPropertyByIndex(idx);
if (property == null) {
// if current index does not work, take current one -1
property = level.getPropertyByIndex(idx - 1);
}
// reload model properties
levelEditorScreenController.setMapProperties(
level.getProperties(),
property == null?null:property.getName()
);
return true;
}
return false;
}
/**
* Remove a object property from object properties
* @param name
* @return success
*/
public boolean objectPropertyRemove(String name) {
if (selectedObjects.size() != 1) return false;
// handle single object
Entity selectedObject = selectedObjects.get(0);
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
if (levelEditorObject == null) return false;
// try to remove property
int idx = levelEditorObject.getPropertyIndex(name);
if (idx != -1 && levelEditorObject.removeProperty(name) == true) {
// get property first at index that was removed
PropertyModelClass property = levelEditorObject.getPropertyByIndex(idx);
if (property == null) {
// if current index does not work, take current one -1
property = levelEditorObject.getPropertyByIndex(idx - 1);
}
// reload model properties
levelEditorScreenController.setObjectProperties(
null,
levelEditorObject.getProperties(),
property == null?null:property.getName()
);
return true;
}
return false;
}
/**
* Apply object property preset
* @param preset id
*/
public void objectPropertiesPreset(String presetId) {
if (selectedObjects.size() != 1) return;
// handle single object
Entity selectedObject = selectedObjects.get(0);
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
if (levelEditorObject == null) return;
// clear object properties
levelEditorObject.clearProperties();
// add object properties by preset if missing
ArrayList<PropertyModelClass> objectPropertyPresetVector = LevelPropertyPresets.getInstance().getObjectPropertiesPresets().get(presetId);
if (objectPropertyPresetVector != null) {
for (PropertyModelClass objectPropertyPreset: objectPropertyPresetVector) {
levelEditorObject.addProperty(objectPropertyPreset.getName(), objectPropertyPreset.getValue());
}
}
// update object properties to gui
levelEditorScreenController.setObjectProperties(
presetId,
levelEditorObject.getProperties(),
null
);
}
/**
* Save a model property
* @param old name
* @param name
* @param value
* @return success
*/
public boolean objectPropertySave(String oldName, String name, String value) {
if (selectedObjects.size() != 1) return false;
// handle single object
Entity selectedObject = selectedObjects.get(0);
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
if (levelEditorObject == null) return false;
// try to update property
if (levelEditorObject.updateProperty(oldName, name, value) == true) {
// reload model properties
levelEditorScreenController.setObjectProperties(
null,
levelEditorObject.getProperties(),
name
);
return true;
}
return false;
}
/**
* Add a model property
* @return success
*/
public boolean objectPropertyAdd() {
if (selectedObjects.size() != 1) return false;
// handle single object
Entity selectedObject = selectedObjects.get(0);
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
if (levelEditorObject == null) return false;
// try to add property
if (levelEditorObject.addProperty("new.property", "new.value")) {
// reload model properties
levelEditorScreenController.setObjectProperties(
null,
levelEditorObject.getProperties(),
"new.property"
);
return true;
}
return false;
}
/**
* Triggers loading a map
*/
public void loadMap(String path, String file) {
selectedEntity = null;
try {
// export level from DAE if requested
if (file.toLowerCase().endsWith(".dae") == true) {
LevelEditorLevel daeLevel = DAEReader.readLevel(path, file);
// adjust file name
file+= ".tl";
}
// do import
LevelFileImport.doImport(
path,
file,
level
);
// set default bounding volumes
for (int i = 0; i < level.getEntityLibrary().getEntityCount(); i++) {
level.getEntityLibrary().getEntityAt(i).setDefaultBoundingVolumes();
}
// set up map properties
levelEditorScreenController.setMapProperties(level.getProperties(), null);
levelEditorScreenController.unsetObjectProperties();
levelEditorScreenController.unsetObject();
loadLevel();
// reset cam
engine.getCamera().getLookAt().set(level.computeCenter());
camLookRotationX.setAngle(-45.0f);
camLookRotationX.update();
camLookRotationY.setAngle(0.0f);
camLookRotationY.update();
camScale = 1.0f;
// grid
gridCenter.set(engine.getCamera().getLookAt());
reloadEntityLibrary = true;
updateGUIElements();
} catch (Exception exception) {
exception.printStackTrace();
levelEditorScreenController.showErrorPopUp("Warning: Could not load level file", exception.getMessage());
}
}
/**
* Triggers saving a map
*/
public void saveMap(String pathName, String fileName) {
try {
File levelFile = new File(pathName, fileName);
LevelFileExport.export(levelFile.getAbsolutePath(), level);
} catch (Exception exception) {
exception.printStackTrace();
levelEditorScreenController.showErrorPopUp("Warning: Could not save level file", exception.getMessage());
}
updateGUIElements();
}
/**
* Copy current selected objects
*/
private void copyObjects() {
pasteObjects.clear();
for (Entity selectedObject: selectedObjects) {
if (selectedObject != null && selectedObject.getId().startsWith("leveleditor.") == false) {
LevelEditorObject levelEditorObject = level.getObjectById(selectedObject.getId());
if (levelEditorObject == null) continue;
pasteObjects.add(levelEditorObject);
}
}
}
/**
* Paste objects
*/
private void pasteObjects() {
// determine top left of paste objects
float pasteObjectsMinX = Float.MAX_VALUE;
float pasteObjectsMinZ = Float.MAX_VALUE;
float pasteObjectsMinY = Float.MIN_VALUE;
for (LevelEditorObject object: pasteObjects) {
BoundingVolume obv = object.getEntity().getModel().getBoundingBox();
BoundingVolume cbv = obv.clone();
cbv.fromBoundingVolumeWithTransformations(obv, object.getTransformations());
float[] objectBBMinXYZ = ((BoundingBox)cbv).getMin().getArray();
if (objectBBMinXYZ[0] < pasteObjectsMinX) pasteObjectsMinX = objectBBMinXYZ[0];
if (objectBBMinXYZ[1] < pasteObjectsMinY) pasteObjectsMinY = objectBBMinXYZ[1];
if (objectBBMinXYZ[2] < pasteObjectsMinZ) pasteObjectsMinZ = objectBBMinXYZ[2];
}
// determine top left of selected objects
float selectedObjectsMinX = Float.MAX_VALUE;
float selectedObjectsMinZ = Float.MAX_VALUE;
float selectedObjectsMaxY = Float.MIN_VALUE;
for (Entity object: selectedObjects) {
LevelEditorObject levelEditorObject = level.getObjectById(object.getId());
if (levelEditorObject == null) continue;
BoundingVolume obv = levelEditorObject.getEntity().getModel().getBoundingBox();
BoundingVolume cbv = obv.clone();
cbv.fromBoundingVolumeWithTransformations(obv, levelEditorObject.getTransformations());
float[] objectBBMinXYZ = ((BoundingBox)cbv).getMin().getArray();
float[] objectBBMaxXYZ = ((BoundingBox)cbv).getMax().getArray();
if (objectBBMinXYZ[0] < selectedObjectsMinX) selectedObjectsMinX = objectBBMinXYZ[0];
if (objectBBMaxXYZ[1] > selectedObjectsMaxY) selectedObjectsMaxY = objectBBMaxXYZ[1];
if (objectBBMinXYZ[2] < selectedObjectsMinZ) selectedObjectsMinZ = objectBBMinXYZ[2];
}
// paste objects
for (LevelEditorObject pasteObject: pasteObjects) {
// get selected level entity if it is one
LevelEditorEntity pasteModel = pasteObject.getEntity();
// create level entity, copy transformations from original
Transformations levelEditorObjectTransformations = new Transformations();
levelEditorObjectTransformations.fromTransformations(pasteObject.getTransformations());
// compute new translation
float objectDiffX = pasteObject.getTransformations().getTranslation().getX() - pasteObjectsMinX;
float objectDiffY = pasteObject.getTransformations().getTranslation().getY() - pasteObjectsMinY;
float objectDiffZ = pasteObject.getTransformations().getTranslation().getZ() - pasteObjectsMinZ;
levelEditorObjectTransformations.getTranslation().setX(selectedObjectsMinX + objectDiffX);
levelEditorObjectTransformations.getTranslation().setY(selectedObjectsMaxY + objectDiffY);
levelEditorObjectTransformations.getTranslation().setZ(selectedObjectsMinZ + objectDiffZ);
levelEditorObjectTransformations.update();
// check if entity already exists
for (int i = 0; i < level.getObjectCount(); i++) {
LevelEditorObject levelEditorObject = level.getObjectAt(i);
if (levelEditorObject.getEntity() == pasteModel &&
levelEditorObject.getTransformations().getTranslation().equals(levelEditorObjectTransformations.getTranslation())) {
// we already have a object with selected model on this translation
return;
}
}
// create new level editor object
LevelEditorObject levelEditorObject = new LevelEditorObject(
pasteModel.getName() + "_" + level.allocateObjectId(),
"",
levelEditorObjectTransformations,
pasteModel
);
// copy properties
for (PropertyModelClass property: pasteObject.getProperties()) {
levelEditorObject.addProperty(property.getName(), property.getValue());
}
// add to level
level.addObject(levelEditorObject);
// add to 3d engine
Object3D object = new Object3D(levelEditorObject.getId(), levelEditorObject.getEntity().getModel());
object.fromTransformations(levelEditorObjectTransformations);
object.setPickable(true);
engine.addEntity(object);
}
// add to objects listbox
levelEditorScreenController.setObjectListbox(level.getObjectIdsIterator());
}
/**
* Compute spot direction
* @param i
*/
public void computeSpotDirection(int i, Vector4 position, Vector3 spotTo) {
Vector3 _from = new Vector3(position.getArray());
Vector3 spotDirection = spotTo.clone().sub(_from);
// set up in level light
level.getLightAt(i).getPosition().set(
position.getX(),
position.getY(),
position.getZ(),
position.getW()
);
level.getLightAt(i).getSpotTo().set(
spotTo.getX(),
spotTo.getY(),
spotTo.getZ()
);
level.getLightAt(i).getSpotDirection().set(
spotDirection.getX(),
spotDirection.getY(),
spotDirection.getZ()
);
// set up in engine light
engine.getLightAt(i).getPosition().set(
position.getX(),
position.getY(),
position.getZ(),
position.getW()
);
engine.getLightAt(i).getSpotDirection().set(
spotDirection.getX(),
spotDirection.getY(),
spotDirection.getZ()
);
// set light in controller
levelEditorScreenController.setLight(
i,
level.getLightAt(i).getAmbient(),
level.getLightAt(i).getDiffuse(),
level.getLightAt(i).getSpecular(),
level.getLightAt(i).getPosition(),
level.getLightAt(i).getConstantAttenuation(),
level.getLightAt(i).getLinearAttenuation(),
level.getLightAt(i).getQuadraticAttenuation(),
level.getLightAt(i).getSpotTo(),
level.getLightAt(i).getSpotDirection(),
level.getLightAt(i).getSpotExponent(),
level.getLightAt(i).getSpotCutOff(),
level.getLightAt(i).isEnabled()
);
}
/**
* Apply light with index i
* @param i
* @param ambient
* @param diffuse
* @param position
* @param constant attenuation
* @param linear attenuation
* @param quadratic attenuation
* @param spot to
* @param spot direction
* @param spot exponent
* @param spot cutoff
* @param enabled
*/
public void applyLight(int i,
Color4 ambient, Color4 diffuse, Color4 specular,
Vector4 position, float constantAttenuation, float linearAttenuation, float quadraticAttenuation,
Vector3 spotTo, Vector3 spotDirection,
float spotExponent, float spotCutoff, boolean enabled) {
// set up light in level
level.getLightAt(i).getAmbient().set(
ambient.getRed(),
ambient.getGreen(),
ambient.getBlue(),
ambient.getAlpha()
);
level.getLightAt(i).getDiffuse().set(
diffuse.getRed(),
diffuse.getGreen(),
diffuse.getBlue(),
diffuse.getAlpha()
);
level.getLightAt(i).getSpecular().set(
specular.getRed(),
specular.getGreen(),
specular.getBlue(),
specular.getAlpha()
);
level.getLightAt(i).getPosition().set(
position.getX(),
position.getY(),
position.getZ(),
position.getW()
);
level.getLightAt(i).setConstantAttenuation(constantAttenuation);
level.getLightAt(i).setLinearAttenuation(linearAttenuation);
level.getLightAt(i).setQuadraticAttenuation(quadraticAttenuation);
level.getLightAt(i).getSpotTo().set(
spotTo.getX(),
spotTo.getY(),
spotTo.getZ()
);
level.getLightAt(i).getSpotDirection().set(
spotDirection.getX(),
spotDirection.getY(),
spotDirection.getZ()
);
level.getLightAt(i).setSpotExponent(spotExponent);
level.getLightAt(i).setSpotCutOff(spotCutoff);
level.getLightAt(i).setEnabled(enabled);
// set up light in engine
engine.getLightAt(i).getAmbient().set(
ambient.getRed(),
ambient.getGreen(),
ambient.getBlue(),
ambient.getAlpha()
);
engine.getLightAt(i).getDiffuse().set(
diffuse.getRed(),
diffuse.getGreen(),
diffuse.getBlue(),
diffuse.getAlpha()
);
engine.getLightAt(i).getSpecular().set(
specular.getRed(),
specular.getGreen(),
specular.getBlue(),
specular.getAlpha()
);
engine.getLightAt(i).getPosition().set(
position.getX(),
position.getY(),
position.getZ(),
position.getW()
);
engine.getLightAt(i).setConstantAttenuation(constantAttenuation);
engine.getLightAt(i).setLinearAttenuation(linearAttenuation);
engine.getLightAt(i).setQuadraticAttenuation(quadraticAttenuation);
engine.getLightAt(i).getSpotDirection().set(
spotDirection.getX(),
spotDirection.getY(),
spotDirection.getZ()
);
engine.getLightAt(i).setSpotExponent(spotExponent);
engine.getLightAt(i).setSpotCutOff(spotCutoff);
engine.getLightAt(i).setEnabled(enabled);
// set light in controller
levelEditorScreenController.setLight(
i,
level.getLightAt(i).getAmbient(),
level.getLightAt(i).getDiffuse(),
level.getLightAt(i).getSpecular(),
level.getLightAt(i).getPosition(),
level.getLightAt(i).getConstantAttenuation(),
level.getLightAt(i).getLinearAttenuation(),
level.getLightAt(i).getQuadraticAttenuation(),
level.getLightAt(i).getSpotTo(),
level.getLightAt(i).getSpotDirection(),
level.getLightAt(i).getSpotExponent(),
level.getLightAt(i).getSpotCutOff(),
level.getLightAt(i).isEnabled()
);
}
}
|
package org.opentdc.events.mongo;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.opentdc.mongo.AbstractMongodbServiceProvider;
import org.opentdc.events.EventModel;
import org.opentdc.events.InvitationState;
import org.opentdc.events.SalutationType;
import org.opentdc.events.ServiceProvider;
import org.opentdc.service.exception.DuplicateException;
import org.opentdc.service.exception.InternalServerErrorException;
import org.opentdc.service.exception.NotFoundException;
import org.opentdc.service.exception.ValidationException;
import org.opentdc.util.EmailSender;
import org.opentdc.util.FreeMarkerConfig;
import org.opentdc.util.PrettyPrinter;
import freemarker.template.Template;
/**
* A MongoDB-based implementation of the Events service.
* @author Bruno Kaiser
*
*/
public class MongodbServiceProvider
extends AbstractMongodbServiceProvider<EventModel>
implements ServiceProvider
{
private static final Logger logger = Logger.getLogger(MongodbServiceProvider.class.getName());
private EmailSender emailSender = null;
private static final String SUBJECT = "Einladung zum Arbalo Launch Event";
/**
* Constructor.
* @param context the servlet context.
* @param prefix the simple class name of the service provider; this is also used as the collection name.
*/
public MongodbServiceProvider(
ServletContext context,
String prefix)
{
super(context);
connect();
collectionName = prefix;
getCollection(collectionName);
new FreeMarkerConfig(context);
emailSender = new EmailSender(context);
logger.info("MongodbServiceProvider(context, " + prefix + ") -> OK");
}
private Document convert(EventModel eventModel, boolean withId)
{
Document _doc = new Document("firstName", eventModel.getFirstName())
.append("lastName", eventModel.getLastName())
.append("email", eventModel.getEmail())
.append("comment", eventModel.getComment())
.append("internalComment", eventModel.getInternalComment())
.append("contact", eventModel.getContact())
.append("salutation", eventModel.getSalutation().toString())
.append("invitationState", eventModel.getInvitationState().toString())
.append("createdAt", eventModel.getCreatedAt())
.append("createdBy", eventModel.getCreatedBy())
.append("modifiedAt", eventModel.getModifiedAt())
.append("modifiedBy", eventModel.getModifiedBy());
if (withId == true) {
_doc.append("_id", new ObjectId(eventModel.getId()));
}
return _doc;
}
private EventModel convert(Document doc)
{
EventModel _model = new EventModel();
_model.setId(doc.getObjectId("_id").toString());
_model.setFirstName(doc.getString("firstName"));
_model.setLastName(doc.getString("lastName"));
_model.setEmail(doc.getString("email"));
_model.setComment(doc.getString("comment"));
_model.setComment(doc.getString("internalComment"));
_model.setContact(doc.getString("contact"));
_model.setSalutation(SalutationType.valueOf(doc.getString("salutation")));
_model.setInvitationState(InvitationState.valueOf(doc.getString("invitationState")));
_model.setCreatedAt(doc.getDate("createdAt"));
_model.setCreatedBy(doc.getString("createdBy"));
_model.setModifiedAt(doc.getDate("modifiedAt"));
_model.setModifiedBy(doc.getString("modifiedBy"));
return _model;
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#list(java.lang.String, java.lang.String, long, long)
*/
@Override
public ArrayList<EventModel> list(
String queryType,
String query,
int position,
int size) {
List<Document> _docs = list(position, size);
ArrayList<EventModel> _selection = new ArrayList<EventModel>();
for (Document doc : _docs) {
_selection.add(convert(doc));
}
logger.info("list(<" + query + ">, <" + queryType +
">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " events.");
return _selection;
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#create(org.opentdc.events.EventsModel)
*/
@Override
public EventModel create(
EventModel event)
throws DuplicateException, ValidationException {
logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(event) + ")");
if (event.getId() != null && !event.getId().isEmpty()) {
throw new ValidationException("event <" + event.getId() + "> contains an id generated on the client.");
}
event.setId(new ObjectId().toString());
// enforce mandatory fields
if (event.getFirstName() == null || event.getFirstName().length() == 0) {
throw new ValidationException("event must contain a valid firstName.");
}
if (event.getLastName() == null || event.getLastName().length() == 0) {
throw new ValidationException("event must contain a valid lastName.");
}
if (event.getEmail() == null || event.getEmail().length() == 0) {
throw new ValidationException("event must contain a valid email address.");
}
// set default values
if (event.getInvitationState() == null) {
event.setInvitationState(InvitationState.INITIAL);
}
if (event.getSalutation() == null) {
event.setSalutation(SalutationType.DU_M);
}
// set modification / creation values
Date _date = new Date();
event.setCreatedAt(_date);
event.setCreatedBy(getPrincipal());
event.setModifiedAt(_date);
event.setModifiedBy(getPrincipal());
create(convert(event, true));
logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(event) + ")");
return event;
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#read(java.lang.String)
*/
@Override
public EventModel read(
String id)
throws NotFoundException {
EventModel _event = convert(readOne(id));
if (_event == null) {
throw new NotFoundException("no event with ID <" + id
+ "> was found.");
}
logger.info("read(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event));
return _event;
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#update(java.lang.String, org.opentdc.events.EventsModel)
*/
@Override
public EventModel update(
String id,
EventModel event
) throws NotFoundException, ValidationException {
EventModel _event = read(id);
if (! _event.getCreatedAt().equals(event.getCreatedAt())) {
logger.warning("event <" + id + ">: ignoring createdAt value <" + event.getCreatedAt().toString() +
"> because it was set on the client.");
}
if (! _event.getCreatedBy().equalsIgnoreCase(event.getCreatedBy())) {
logger.warning("event <" + id + ">: ignoring createdBy value <" + event.getCreatedBy() +
"> because it was set on the client.");
}
if (event.getFirstName() == null || event.getFirstName().length() == 0) {
throw new ValidationException("event <" + id +
"> must contain a valid firstName.");
}
if (event.getLastName() == null || event.getLastName().length() == 0) {
throw new ValidationException("event <" + id +
"> must contain a valid lastName.");
}
if (event.getEmail() == null || event.getEmail().length() == 0) {
throw new ValidationException("event <" + id +
"> must contain a valid email address.");
}
if (event.getInvitationState() == null) {
event.setInvitationState(InvitationState.INITIAL);
}
if (event.getSalutation() == null) {
event.setSalutation(SalutationType.DU_M);
}
_event.setFirstName(event.getFirstName());
_event.setLastName(event.getLastName());
_event.setEmail(event.getEmail());
_event.setContact(event.getContact());
_event.setSalutation(event.getSalutation());
_event.setInvitationState(event.getInvitationState());
_event.setComment(event.getComment());
_event.setModifiedAt(new Date());
_event.setModifiedBy(getPrincipal());
update(id, convert(_event, true));
logger.info("update(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event));
return _event;
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#delete(java.lang.String)
*/
@Override
public void delete(
String id)
throws NotFoundException, InternalServerErrorException {
read(id);
deleteOne(id);
logger.info("delete(" + id + ") -> OK");
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#getMessage(java.lang.String)
*/
@Override
public String getMessage(String id) throws NotFoundException,
InternalServerErrorException {
logger.info("getMessage(" + id + ")");
EventModel _model = read(id);
// create the FreeMarker data model
Map<String, Object> _root = new HashMap<String, Object>();
_root.put("event", _model);
// Merge data model with template
String _msg = FreeMarkerConfig.getProcessedTemplate(
_root,
getTemplate(_model.getSalutation(), _model.getContact()));
logger.info("getMessage(" + id + ") -> " + _msg);
return _msg;
}
/**
* Retrieve the email address of the contact.
* @param userName the name of the contact
* @return the corresponding email address
*/
private String getEmailAddress(String userName) {
logger.info("getEmailAddress(" + userName + ")");
String _emailAddress = null;
if (userName == null || userName.isEmpty()) {
userName = "arbalo";
}
if (userName.equalsIgnoreCase("bruno")) {
_emailAddress = "bruno.kaiser@arbalo.ch";
} else if (userName.equalsIgnoreCase("thomas")) {
_emailAddress = "thomas.huber@arbalo.ch";
} else if (userName.equalsIgnoreCase("peter")) {
_emailAddress = "peter.windemann@arbalo.ch";
} else if (userName.equalsIgnoreCase("marc")) {
_emailAddress = "marc.hofer@arbalo.ch";
} else if (userName.equalsIgnoreCase("werner")) {
_emailAddress = "werner.froidevaux@arbalo.ch";
} else {
_emailAddress = "info@arbalo.ch";
}
logger.info("getEmailAddress(" + userName + ") -> " + _emailAddress);
return _emailAddress;
}
/**
* @param salutation
* @return
*/
private Template getTemplate(
SalutationType salutation, String userName) {
String _templateName = null;
if (userName == null || userName.isEmpty()) {
userName = "arbalo";
}
switch (salutation) {
case HERR: _templateName = "emailHerr_" + userName + ".ftl"; break;
case FRAU: _templateName = "emailFrau_" + userName + ".ftl"; break;
case DU_F: _templateName = "emailDuf_" + userName + ".ftl"; break;
case DU_M: _templateName = "emailDum_" + userName + ".ftl"; break;
}
return FreeMarkerConfig.getTemplateByName(_templateName);
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#sendMessage(java.lang.String)
*/
@Override
public void sendMessage(
String id)
throws NotFoundException, InternalServerErrorException {
logger.info("sendMessage(" + id + ")");
EventModel _model = read(id);
emailSender.sendMessage(
_model.getEmail(),
getEmailAddress(_model.getContact()),
SUBJECT,
getMessage(id));
logger.info("sent email message to " + _model.getEmail());
_model.setId(null);
_model.setInvitationState(InvitationState.SENT);
update(id, _model);
}
/* (non-Javadoc)
* @see org.opentdc.events.ServiceProvider#sendAllMessages()
*/
@Override
public void sendAllMessages()
throws InternalServerErrorException {
logger.info("sendAllMessages()");
EventModel _model = null;
String _id = null;
for (Document doc : list(0, 200)) {
_model = convert(doc);
_id = _model.getId();
emailSender.sendMessage(
_model.getEmail(),
getEmailAddress(_model.getContact()),
SUBJECT,
getMessage(_id));
logger.info("sent email message to " + _model.getEmail());
_model.setId(null);
_model.setInvitationState(InvitationState.SENT);
update(_id, _model);
try {
Thread.sleep(1000);
} catch (InterruptedException _ex) {
_ex.printStackTrace();
throw new InternalServerErrorException(_ex.getMessage());
}
}
}
}
|
package thredds.server.root;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.LastModified;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import thredds.servlet.ServletUtil;
import thredds.server.config.TdsContext;
import thredds.util.TdsPathUtils;
import java.io.File;
import java.io.IOException;
/**
* _more_
*
* @author edavis
* @since 4.0
*/
public class RootController extends AbstractController implements LastModified
{
// private static org.slf4j.Logger log =
// org.slf4j.LoggerFactory.getLogger( RootController.class );
private TdsContext tdsContext;
public void setTdsContext( TdsContext tdsContext )
{
this.tdsContext = tdsContext;
}
public void init()
{
WebApplicationContext webAppContext = this.getWebApplicationContext();
ServletContext sc = webAppContext.getServletContext();
initContent();
}
private void initContent()
//throws javax.servlet.ServletException
{
// first time, create content directory
File initialContentDirectory = tdsContext.getStartupContentDirectory();
if ( initialContentDirectory.exists() )
{
try
{
if ( ServletUtil.copyDir( initialContentDirectory.toString(),
tdsContext.getContentDirectory().toString() ) );
//log.info( "copyDir " + initialContentPath + " to " + contentPath );
}
catch ( IOException ioe )
{
//log.error( "failed to copyDir " + initialContentPath + " to " + contentPath, ioe );
}
}
}
public void destroy()
{
}
protected ModelAndView handleRequestInternal( HttpServletRequest req, HttpServletResponse res )
throws Exception
{
String path = TdsPathUtils.extractPath( req );
if ( path.equals( "/" ) || path.equals( ""))
{
String newPath = tdsContext.getContextPath() + "/catalog.html";
res.sendRedirect( newPath );
return null;
}
File file = tdsContext.getPublicDocFileSource().getFile( path );
if ( file == null )
{
tdsContext.getDefaultRequestDispatcher().forward( req, res );
return null;
}
return new ModelAndView( "threddsFileView", "file", file );
}
public long getLastModified( HttpServletRequest req )
{
String path = TdsPathUtils.extractPath( req );
File file = tdsContext.getPublicDocFileSource().getFile( path );
if ( file == null )
return -1;
long lastModTime = file.lastModified();
if ( lastModTime == 0L )
return -1;
return lastModTime;
}
}
|
package net.java.sip.communicator.impl.neomedia;
import java.io.*;
import java.net.*;
import java.util.*;
import java.beans.*;
import javax.media.*;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.protocol.*;
import javax.media.rtp.*;
import javax.media.rtp.event.*;
import com.sun.media.rtp.*;
import net.java.sip.communicator.impl.neomedia.device.*;
import net.java.sip.communicator.impl.neomedia.format.*;
import net.java.sip.communicator.impl.neomedia.transform.*;
import net.java.sip.communicator.impl.neomedia.transform.csrc.*;
import net.java.sip.communicator.impl.neomedia.transform.dtmf.*;
import net.java.sip.communicator.impl.neomedia.transform.zrtp.*;
import net.java.sip.communicator.service.neomedia.*;
import net.java.sip.communicator.service.neomedia.device.*;
import net.java.sip.communicator.service.neomedia.format.*;
import net.java.sip.communicator.util.*;
/**
* Implements <tt>MediaStream</tt> using JMF.
*
* @author Lubomir Marinov
* @author Emil Ivov
*/
public class MediaStreamImpl
extends AbstractMediaStream
implements ReceiveStreamListener,
SendStreamListener,
SessionListener
{
/**
* The <tt>Logger</tt> used by the <tt>MediaStreamImpl</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(MediaStreamImpl.class);
/**
* The name of the property indicating the length of our receive buffer.
*/
protected static final String PROPERTY_NAME_RECEIVE_BUFFER_LENGTH
= "net.java.sip.communicator.impl.neomedia.RECEIVE_BUFFER_LENGTH";
/**
* The session with the <tt>MediaDevice</tt> this instance uses for both
* capture and playback of media.
*/
protected MediaDeviceSession deviceSession;
/**
* The <tt>PropertyChangeListener</tt> which listens to
* {@link #deviceSession} and changes in the values of its
* {@link MediaDeviceSession#OUTPUT_DATA_SOURCE} property.
*/
private final PropertyChangeListener deviceSessionPropertyChangeListener =
new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent event)
{
if (MediaDeviceSession
.OUTPUT_DATA_SOURCE.equals(event.getPropertyName()))
deviceSessionOutputDataSourceChanged();
else if (MediaDeviceSession
.SSRC_LIST.equals(event.getPropertyName()))
deviceSessionSsrcListChanged(event);
}
};
/**
* The <tt>MediaDirection</tt> in which this <tt>MediaStream</tt> is allowed
* to stream media.
*/
private MediaDirection direction;
/**
* The <tt>Map</tt> of associations in this <tt>MediaStream</tt> and the
* <tt>RTPManager</tt> it utilizes of (dynamic) RTP payload types to
* <tt>MediaFormat</tt>s.
*/
private final Map<Byte, MediaFormat> dynamicRTPPayloadTypes
= new HashMap<Byte, MediaFormat>();
/**
* The <tt>ReceiveStream</tt> this instance plays back on its associated
* <tt>MediaDevice</tt>.
*/
private ReceiveStream receiveStream;
/**
* The <tt>Object</tt> which synchronizes the access to
* {@link #receiveStream} and its registration with {@link #deviceSession}.
*/
private final Object receiveStreamSyncRoot = new Object();
/**
* The <tt>RTPConnector</tt> through which this instance sends and receives
* RTP and RTCP traffic. The instance is a <tt>TransformConnector</tt> in
* order to also enable packet transformations.
*/
protected final RTPTransformConnector rtpConnector;
/**
* The one and only <tt>MediaStreamTarget</tt> this instance has added as a
* target in {@link #rtpConnector}.
*/
private MediaStreamTarget rtpConnectorTarget;
/**
* The <tt>RTPManager</tt> which utilizes {@link #rtpConnector} and sends
* and receives RTP and RTCP traffic on behalf of this <tt>MediaStream</tt>.
*/
private RTPManager rtpManager;
/**
* The indicator which determines whether {@link #createSendStreams()} has
* been executed for {@link #rtpManager}. If <tt>true</tt>, the
* <tt>SendStream</tt>s have to be recreated when the <tt>MediaDevice</tt>,
* respectively the <tt>MediaDeviceSession</tt>, of this instance is
* changed.
*/
private boolean sendStreamsAreCreated = false;
/**
* The indicator which determines whether {@link #start()} has been called
* on this <tt>MediaStream</tt> without {@link #stop()} or {@link #close()}.
*/
private boolean started = false;
/**
* The <tt>MediaDirection</tt> in which this instance is started. For
* example, {@link MediaDirection#SENDRECV} if this instances is both
* sending and receiving data (e.g. RTP and RTCP) or
* {@link MediaDirection#SENDONLY} if this instance is only sending data.
*/
private MediaDirection startedDirection;
/**
* The SSRC identifier of the party that we are exchanging media with.
*/
private long remoteSourceID = -1;
/**
* Our own SSRC identifier.
*/
private long localSourceID = -1;
/**
* The list of CSRC IDs contributing to the media that this
* <tt>MediaStream</tt> is sending to its remote party.
*/
private long[] localContributingSourceIDList = null;
/**
* The indicator which determines whether this <tt>MediaStream</tt> is set
* to transmit "silence" instead of the actual media fed from its
* <tt>MediaDevice</tt>.
*/
private boolean mute = false;
/**
* The current <tt>ZrtpControl</tt>
*/
private ZrtpControlImpl zrtpControl = null;
/**
* The map of currently active <tt>RTPExtension</tt>s and the IDs that they
* have been assigned for the lifetime of this <tt>MediaStream</tt>.
*/
private final Map<Byte, RTPExtension> activeRTPExtensions
= new Hashtable<Byte, RTPExtension>();
/**
* The engine that we are using in order to add CSRC lists in conference
* calls, send CSRC sound levels, and handle incoming levels and CSRC lists.
*/
private CsrcTransformEngine csrcEngine;
/**
* Map of advanced attributes.
*/
protected Map<String, String> advancedAttributes =
new Hashtable<String, String>();
/**
* Initializes a new <tt>MediaStreamImpl</tt> instance which will use the
* specified <tt>MediaDevice</tt> for both capture and playback of media
* exchanged via the specified <tt>StreamConnector</tt>.
*
* @param connector the <tt>StreamConnector</tt> the new instance is to use
* for sending and receiving media
* @param device the <tt>MediaDevice</tt> the new instance is to use for
* both capture and playback of media exchanged via the specified
* <tt>StreamConnector</tt>
* @param zrtpControl a control which is already created, used to control
* the zrtp operations.
*/
public MediaStreamImpl(StreamConnector connector, MediaDevice device,
ZrtpControlImpl zrtpControl)
{
/*
* XXX Set the device early in order to make sure that its of the right
* type because we do not support just about any MediaDevice yet.
*/
setDevice(device);
this.rtpConnector = new RTPTransformConnector(connector);
if(zrtpControl != null)
{
this.zrtpControl = zrtpControl;
}
else
this.zrtpControl = new ZrtpControlImpl();
this.zrtpControl.setConnector(rtpConnector);
//register the transform engines that we will be using in this stream.
TransformEngineChain engineChain = createTransformEngineChain();
rtpConnector.setEngine(engineChain);
}
/**
* Performs any optional configuration on the <tt>BufferControl</tt> of the
* specified <tt>RTPManager</tt> which is to be used as the
* <tt>RTPManager</tt> of this <tt>MediaStreamImpl</tt>. Allows extenders to
* override.
*
* @param rtpManager the <tt>RTPManager</tt> which is to be used by this
* <tt>MediaStreamImpl</tt>
* @param bufferControl the <tt>BufferControl</tt> of <tt>rtpManager</tt> on
* which any optional configuration is to be performed
*/
protected void configureRTPManagerBufferControl(
RTPManager rtpManager,
BufferControl bufferControl)
{
}
/**
* Creates a chain of transform engines for use with this stream. Note
* that this is the only place where the <tt>TransformEngineChain</tt> is
* and should be manipulated to avoid problems with the order of the
* transformers.
*
* @return the <tt>TransformEngineChain</tt> that this stream should be
* using.
*/
private TransformEngineChain createTransformEngineChain()
{
ArrayList<TransformEngine> engineChain
= new ArrayList<TransformEngine>(3);
//CSRCs and audio levels
if(csrcEngine == null)
csrcEngine = new CsrcTransformEngine(this);
engineChain.add(csrcEngine);
//DTMF
DtmfTransformEngine dtmfEngine = createDtmfTransformEngine();
if(dtmfEngine != null)
engineChain.add(dtmfEngine);
//ZRTP
engineChain.add(zrtpControl.getZrtpEngine());
return new TransformEngineChain( engineChain.toArray(
new TransformEngine[engineChain.size()]));
}
/**
* A stub that allows audio oriented streams to create and keep a reference
* to a <tt>DtmfTransformEngine</tt>.
*
* @return a <tt>DtmfTransformEngine</tt> if this is an audio oriented
* stream and <tt>null</tt> otherwise.
*/
protected DtmfTransformEngine createDtmfTransformEngine()
{
return null;
}
/**
* Adds a new association in this <tt>MediaStream</tt> of the specified RTP
* payload type with the specified <tt>MediaFormat</tt> in order to allow it
* to report <tt>rtpPayloadType</tt> in RTP flows sending and receiving
* media in <tt>format</tt>. Usually, <tt>rtpPayloadType</tt> will be in the
* range of dynamic RTP payload types.
*
* @param rtpPayloadType the RTP payload type to be associated in this
* <tt>MediaStream</tt> with the specified <tt>MediaFormat</tt>
* @param format the <tt>MediaFormat</tt> to be associated in this
* <tt>MediaStream</tt> with <tt>rtpPayloadType</tt>
* @see MediaStream#addDynamicRTPPayloadType(byte, MediaFormat)
*/
public void addDynamicRTPPayloadType(
byte rtpPayloadType,
MediaFormat format)
{
@SuppressWarnings("unchecked")
MediaFormatImpl<? extends Format> mediaFormatImpl
= (MediaFormatImpl<? extends Format>) format;
synchronized (dynamicRTPPayloadTypes)
{
dynamicRTPPayloadTypes.put(Byte.valueOf(rtpPayloadType), format);
if (rtpManager != null)
rtpManager
.addFormat(mediaFormatImpl.getFormat(), rtpPayloadType);
}
}
/**
* Maps or updates the mapping between <tt>extensionID</tt> and
* <tt>rtpExtension</tt>. If <tt>rtpExtension</tt>'s <tt>MediaDirection</tt>
* attribute is set to <tt>INACTIVE</tt> the mapping is removed from the
* local extensions table and the extension would not be transmitted or
* handled by this stream's <tt>RTPConnector</tt>.
*
* @param extensionID the ID that is being mapped to <tt>rtpExtension</tt>
* @param rtpExtension the <tt>RTPExtension</tt> that we are mapping.
*/
public void addRTPExtension(byte extensionID, RTPExtension rtpExtension)
{
synchronized (activeRTPExtensions)
{
if(rtpExtension.getDirection() == MediaDirection.INACTIVE)
activeRTPExtensions.remove(extensionID);
else
activeRTPExtensions.put(extensionID, rtpExtension);
}
}
/**
* Returns a map containing all currently active <tt>RTPExtension</tt>s in
* use by this stream.
*
* @return a map containing all currently active <tt>RTPExtension</tt>s in
* use by this stream.
*/
public Map<Byte, RTPExtension> getActiveRTPExtensions()
{
synchronized (activeRTPExtensions)
{
return new HashMap<Byte, RTPExtension>(activeRTPExtensions);
}
}
/**
* Returns the ID currently assigned to a specific RTP extension.
*
* @param rtpExtension the RTP extension to get the currently assigned ID of
* @return the ID currently assigned to the specified RTP extension or
* <tt>-1</tt> if no ID has been defined for this extension so far
*/
public byte getActiveRTPExtensionID(RTPExtension rtpExtension)
{
synchronized (activeRTPExtensions)
{
Set<Map.Entry<Byte, RTPExtension>> extSet
= this.activeRTPExtensions.entrySet();
for (Map.Entry<Byte, RTPExtension> entry : extSet)
{
if (entry.getValue().equals(rtpExtension))
return entry.getKey();
}
}
return -1;
}
/**
* Returns the engine that is responsible for adding the list of CSRC
* identifiers to outgoing RTP packets during a conference.
*
* @return the engine that is responsible for adding the list of CSRC
* identifiers to outgoing RTP packets during a conference.
*/
protected CsrcTransformEngine getCsrcEngine()
{
return csrcEngine;
}
/**
* Set list of advanced attributes.
*
* @param attrs advanced attributes map
*/
public void setAdvancedAttributes(Map<String, String> attrs)
{
if(attrs != null)
{
advancedAttributes.clear();
advancedAttributes.putAll(attrs);
}
}
/**
* Releases the resources allocated by this instance in the course of its
* execution and prepares it to be garbage collected.
*
* @see MediaStream#close()
*/
public void close()
{
stop();
closeSendStreams();
ZRTPTransformEngine engine = zrtpControl.getZrtpEngine();
if(engine != null)
{
engine.stopZrtp();
engine.cleanup();
}
if(csrcEngine != null)
{
csrcEngine.stop();
csrcEngine = null;
}
rtpConnector.removeTargets();
rtpConnectorTarget = null;
if (rtpManager != null)
{
rtpManager.removeReceiveStreamListener(this);
rtpManager.removeSendStreamListener(this);
rtpManager.removeSessionListener(this);
rtpManager.dispose();
rtpManager = null;
}
if (deviceSession != null)
deviceSession.close();
}
/**
* Closes the <tt>SendStream</tt>s this instance is sending to its remote
* peer.
*/
private void closeSendStreams()
{
stopSendStreams(true);
}
/**
* Creates new <tt>SendStream</tt> instances for the streams of
* {@link #deviceSession} through {@link #rtpManager}.
*/
private void createSendStreams()
{
RTPManager rtpManager = getRTPManager();
MediaDeviceSession deviceSession = getDeviceSession();
DataSource dataSource = deviceSession.getOutputDataSource();
int streamCount;
if (dataSource instanceof PushBufferDataSource)
{
PushBufferStream[] streams
= ((PushBufferDataSource) dataSource).getStreams();
streamCount = (streams == null) ? 0 : streams.length;
}
else if (dataSource instanceof PushDataSource)
{
PushSourceStream[] streams
= ((PushDataSource) dataSource).getStreams();
streamCount = (streams == null) ? 0 : streams.length;
}
else if (dataSource instanceof PullBufferDataSource)
{
PullBufferStream[] streams
= ((PullBufferDataSource) dataSource).getStreams();
streamCount = (streams == null) ? 0 : streams.length;
}
else if (dataSource instanceof PullDataSource)
{
PullSourceStream[] streams
= ((PullDataSource) dataSource).getStreams();
streamCount = (streams == null) ? 0 : streams.length;
}
else
streamCount = (dataSource == null) ? 0 : 1;
for (int streamIndex = 0; streamIndex < streamCount; streamIndex++)
{
Throwable exception = null;
try
{
SendStream sendStream
= rtpManager.createSendStream(dataSource, streamIndex);
if (logger.isTraceEnabled())
logger
.trace(
"Created SendStream"
+ " with hashCode "
+ sendStream.hashCode()
+ " for "
+ toString(dataSource)
+ " and streamIndex "
+ streamIndex
+ " in RTPManager with hashCode "
+ rtpManager.hashCode());
// If a ZRTP engine is availabe then set the SSRC of this stream
// currently ZRTP supports only one SSRC per engine
ZRTPTransformEngine engine = zrtpControl.getZrtpEngine();
if (engine != null)
engine.setOwnSSRC(sendStream.getSSRC());
}
catch (IOException ioe)
{
exception = ioe;
}
catch (UnsupportedFormatException ufe)
{
exception = ufe;
}
if (exception != null)
{
// TODO
logger
.error(
"Failed to create send stream for data source "
+ dataSource
+ " and stream index "
+ streamIndex,
exception);
}
}
sendStreamsAreCreated = true;
if (logger.isTraceEnabled())
{
@SuppressWarnings("unchecked")
Vector<SendStream> sendStreams = rtpManager.getSendStreams();
int sendStreamCount
= (sendStreams == null) ? 0 : sendStreams.size();
logger
.trace(
"Total number of SendStreams in RTPManager with hashCode "
+ rtpManager.hashCode()
+ " is "
+ sendStreamCount);
}
}
/**
* Notifies this <tt>MediaStream</tt> that the <tt>MediaDevice</tt> (and
* respectively the <tt>MediaDeviceSession</tt> with it) which this instance
* uses for capture and playback of media has been changed. Allows extenders
* to override and provide additional processing of <tt>oldValue</tt> and
* <tt>newValue</tt>.
*
* @param oldValue the <tt>MediaDeviceSession</tt> with the
* <tt>MediaDevice</tt> this instance used work with
* @param newValue the <tt>MediaDeviceSession</tt> with the
* <tt>MediaDevice</tt> this instance is to work with
*/
protected void deviceSessionChanged(
MediaDeviceSession oldValue,
MediaDeviceSession newValue)
{
recreateSendStreams();
}
/**
* Notifies this instance that the output <tt>DataSource</tt> of its
* <tt>MediaDeviceSession</tt> has changed. Recreates the
* <tt>SendStream</tt>s of this instance as necessary so that it, for
* example, continues streaming after the change if it was streaming before
* the change.
*/
private void deviceSessionOutputDataSourceChanged()
{
recreateSendStreams();
}
/**
* Recalculates the list of CSRC identifiers that this <tt>MediaStream</tt>
* needs to include in RTP packets bound to its interlocutor. The method
* uses the list of SSRC identifiers currently handled by our device
* (possibly a mixer), then removes the SSRC ID of this stream's
* interlocutor. If this turns out to be the only SSRC currently in the list
* we set the list of local CSRC identifiers to null since this is obviously
* a non-conf call and we don't need to be advertising CSRC lists. If that's
* not the case, we also add our own SSRC to the list of IDs and cache the
* entire list.
*
* @param evt the <tt>PropetyChangeEvent</tt> containing the list of SSRC
* identifiers handled by our device session before and after it changed.
*
*/
private void deviceSessionSsrcListChanged(PropertyChangeEvent evt)
{
long[] ssrcArray = (long[])evt.getNewValue();
// the list is empty
if(ssrcArray == null)
{
this.localContributingSourceIDList = null;
return;
}
int elementsToRemove = 0;
long remoteSrcID = this.getRemoteSourceID();
//in case of a conf call the mixer would return all SSRC IDs that are
//currently contributing including this stream's counterpart. We need
//to remove that last one since that's where we will be sending our
//csrc list
for(long csrc : ssrcArray)
{
if (csrc == remoteSrcID)
{
elementsToRemove ++;
}
}
//we don't seem to be in a conf call since the list only contains the
//SSRC id of the party that we are directly interacting with.
if (elementsToRemove >= ssrcArray.length)
{
this.localContributingSourceIDList = null;
return;
}
//prepare the new array. make it big enough to also add the local
//SSRC id but do not make it bigger than 15 since that's the maximum
//for RTP.
int cc = Math.min(ssrcArray.length - elementsToRemove + 1, 15);
long[] csrcArray = new long[cc];
for (int i = 0,j = 0;
i < ssrcArray.length
&& j < csrcArray.length - 1;
i++)
{
long ssrc = ssrcArray[i];
if (ssrc != remoteSrcID)
{
csrcArray[j] = ssrc;
j++;
}
}
csrcArray[csrcArray.length - 1] = getLocalSourceID();
this.localContributingSourceIDList = csrcArray;
}
/**
* Gets the <tt>MediaDevice</tt> that this stream uses to play back and
* capture media.
*
* @return the <tt>MediaDevice</tt> that this stream uses to play back and
* capture media
* @see MediaStream#getDevice()
*/
public AbstractMediaDevice getDevice()
{
return getDeviceSession().getDevice();
}
/**
* Gets the <tt>MediaDeviceSession</tt> which represents the work of this
* <tt>MediaStream</tt> with its associated <tt>MediaDevice</tt>.
*
* @return the <tt>MediaDeviceSession</tt> which represents the work of this
* <tt>MediaStream</tt> with its associated <tt>MediaDevice</tt>
*/
protected MediaDeviceSession getDeviceSession()
{
return deviceSession;
}
/**
* Gets the direction in which this <tt>MediaStream</tt> is allowed to
* stream media.
*
* @return the <tt>MediaDirection</tt> in which this <tt>MediaStream</tt> is
* allowed to stream media
* @see MediaStream#getDirection()
*/
public MediaDirection getDirection()
{
if (direction != null)
return direction;
MediaDeviceSession deviceSession = getDeviceSession();
return (deviceSession == null)
? MediaDirection.INACTIVE
: deviceSession.getDevice().getDirection();
}
/**
* Gets the existing associations in this <tt>MediaStream</tt> of RTP
* payload types to <tt>MediaFormat</tt>s. The returned <tt>Map</tt>
* only contains associations previously added in this instance with
* {@link #addDynamicRTPPayloadType(byte, MediaFormat)} and not globally or
* well-known associations reported by
* {@link MediaFormat#getRTPPayloadType()}.
*
* @return a <tt>Map</tt> of RTP payload type expressed as <tt>Byte</tt> to
* <tt>MediaFormat</tt> describing the existing (dynamic) associations in
* this instance of RTP payload types to <tt>MediaFormat</tt>s. The
* <tt>Map</tt> represents a snapshot of the existing associations at the
* time of the <tt>getDynamicRTPPayloadTypes()</tt> method call and
* modifications to it are not reflected on the internal storage
* @see MediaStream#getDynamicRTPPayloadTypes()
*/
public Map<Byte, MediaFormat> getDynamicRTPPayloadTypes()
{
synchronized (dynamicRTPPayloadTypes)
{
return new HashMap<Byte, MediaFormat>(dynamicRTPPayloadTypes);
}
}
/**
* Returns the payload type number that has been negotiated for the
* specified <tt>encoding</tt> or <tt>-1</tt> if no payload type has been
* negotiated for it. If multiple formats match the specified
* <tt>encoding</tt>, then this method would return the first one it
* encounters while iterating through the map.
*
* @param encoding the encoding whose payload type we are trying to obtain.
*
* @return the payload type number that has been negotiated for the
* specified <tt>encoding</tt> or <tt>-1</tt> if no payload type has been
* negotiated for it.
*/
public byte getDynamicRTPPayloadType(String encoding)
{
synchronized (dynamicRTPPayloadTypes)
{
for (Map.Entry<Byte, MediaFormat> entry
: dynamicRTPPayloadTypes.entrySet())
{
if (entry.getValue().getEncoding().equals(encoding))
return entry.getKey().byteValue();
}
return -1;
}
}
/**
* Gets the <tt>MediaFormat</tt> that this stream is currently transmitting
* in.
*
* @return the <tt>MediaFormat</tt> that this stream is currently
* transmitting in
* @see MediaStream#getFormat()
*/
public MediaFormat getFormat()
{
return getDeviceSession().getFormat();
}
/**
* Gets the synchronization source (SSRC) identifier of the local peer or
* <tt>-1</tt> if it is not yet known.
*
* @return the synchronization source (SSRC) identifier of the local peer
* or <tt>-1</tt> if it is not yet known
* @see MediaStream#getLocalSourceID()
*/
public long getLocalSourceID()
{
return this.localSourceID;
}
/**
* Gets the address that this stream is sending RTCP traffic to.
*
* @return an <tt>InetSocketAddress</tt> instance indicating the address
* that this stream is sending RTCP traffic to
* @see MediaStream#getRemoteControlAddress()
*/
public InetSocketAddress getRemoteControlAddress()
{
return (InetSocketAddress)
rtpConnector.getControlSocket().getRemoteSocketAddress();
}
/**
* Gets the address that this stream is sending RTP traffic to.
*
* @return an <tt>InetSocketAddress</tt> instance indicating the address
* that this stream is sending RTP traffic to
* @see MediaStream#getRemoteDataAddress()
*/
public InetSocketAddress getRemoteDataAddress()
{
return (InetSocketAddress)
rtpConnector.getDataSocket().getRemoteSocketAddress();
}
/**
* Get the synchronization source (SSRC) identifier of the remote peer or
* <tt>-1</tt> if it is not yet known.
*
* @return the synchronization source (SSRC) identifier of the remote
* peer or <tt>-1</tt> if it is not yet known
* @see MediaStream#getRemoteSourceID()
*/
public long getRemoteSourceID()
{
return remoteSourceID;
}
/**
* Gets the <tt>RTPManager</tt> instance which sends and receives RTP and
* RTCP traffic on behalf of this <tt>MediaStream</tt>.
*
* @return the <tt>RTPManager</tt> instance which sends and receives RTP and
* RTCP traffic on behalf of this <tt>MediaStream</tt>
*/
private RTPManager getRTPManager()
{
if (rtpManager == null)
{
rtpManager = RTPManager.newInstance();
registerCustomCodecFormats(rtpManager);
rtpManager.addReceiveStreamListener(this);
rtpManager.addSendStreamListener(this);
rtpManager.addSessionListener(this);
BufferControl bc
= (BufferControl)
rtpManager.getControl(BufferControl.class.getName());
if (bc != null)
configureRTPManagerBufferControl(rtpManager, bc);
//Emil: if you replace this method with another init method make
//sure you check that the line below still works.
rtpManager.initialize(rtpConnector);
//JMF inits the local SSRC upon initialize(RTPConnector) so now's
//the time to ask:
setLocalSourceID(((RTPSessionMgr)rtpManager).getLocalSSRC());
}
return rtpManager;
}
/**
* Gets the <tt>ZrtpControl</tt> which controls the ZRTP of this stream.
*
* @return the <tt>ZrtpControl</tt> which controls the ZRTP of this stream
*/
public ZrtpControl getZrtpControl()
{
return zrtpControl;
}
/**
* Resets the state of secure communication and restart the secure
* communication negotiation.
* @return the newly created <tt>ZrtpControl</tt>.
*/
public ZrtpControl restartZrtpControl()
{
ZrtpControlImpl oldZrtpControl = zrtpControl;
this.zrtpControl = new ZrtpControlImpl();
// as we are recreating this stream and it was obviously secured
// it may happen we receive unencrepted data and we will hear
// noise, so we mute it till secure connection is again established
zrtpControl.getZrtpEngine().setStartMuted(true);
this.zrtpControl.setConnector(rtpConnector);
rtpConnector.setEngine(createTransformEngineChain());
if(oldZrtpControl != null)
{
ZRTPTransformEngine engine = oldZrtpControl.getZrtpEngine();
if(engine != null)
{
engine.stopZrtp();
engine.cleanup();
}
}
return zrtpControl;
}
/**
* Determines whether this <tt>MediaStream</tt> is set to transmit "silence"
* instead of the media being fed from its <tt>MediaDevice</tt>. "Silence"
* for video is understood as video data which is not the captured video
* data and may represent, for example, a black image.
*
* @return <tt>true</tt> if this <tt>MediaStream</tt> is set to transmit
* "silence" instead of the media fed from its <tt>MediaDevice</tt>;
* <tt>false</tt>, otherwise
* @see MediaStream#isMute()
*/
public boolean isMute()
{
MediaDeviceSession deviceSession = getDeviceSession();
return (deviceSession == null) ? mute : deviceSession.isMute();
}
/**
* Determines whether {@link #start()} has been called on this
* <tt>MediaStream</tt> without {@link #stop()} or {@link #close()}
* afterwards.
*
* @return <tt>true</tt> if {@link #start()} has been called on this
* <tt>MediaStream</tt> without {@link #stop()} or {@link #close()}
* afterwards
* @see MediaStream#isStarted()
*/
public boolean isStarted()
{
return started;
}
/**
* Recreates the <tt>SendStream</tt>s of this instance (i.e. of its
* <tt>RTPManager</tt>) as necessary. For example, if there was no attempt
* to create the <tt>SendStream</tt>s prior to the call, does nothing. If
* they were created prior to the call, closes them and creates them again.
* If they were not started prior to the call, does not start them after
* recreating them.
*/
private void recreateSendStreams()
{
if (sendStreamsAreCreated)
{
closeSendStreams();
if ((getDeviceSession() != null) && (rtpManager != null))
{
if (MediaDirection.SENDONLY.equals(startedDirection)
|| MediaDirection.SENDRECV.equals(startedDirection))
startSendStreams();
}
}
}
/**
* Registers any custom JMF <tt>Format</tt>s with a specific
* <tt>RTPManager</tt>. Extenders should override in order to register their
* own customizations and should call back to this super implementation
* during the execution of their override in order to register the
* associations defined in this instance of (dynamic) RTP payload types to
* <tt>MediaFormat</tt>s.
*
* @param rtpManager the <tt>RTPManager</tt> to register any custom JMF
* <tt>Format</tt>s with
*/
protected void registerCustomCodecFormats(RTPManager rtpManager)
{
synchronized (dynamicRTPPayloadTypes)
{
for (Map.Entry<Byte, MediaFormat> dynamicRTPPayloadType
: dynamicRTPPayloadTypes.entrySet())
{
@SuppressWarnings("unchecked")
MediaFormatImpl<? extends Format> mediaFormatImpl
= (MediaFormatImpl<? extends Format>)
dynamicRTPPayloadType.getValue();
rtpManager.addFormat( mediaFormatImpl.getFormat(),
dynamicRTPPayloadType.getKey());
}
}
}
/**
* Sets the <tt>MediaDevice</tt> that this stream should use to play back
* and capture media.
* <p>
* <b>Note</b>: Also resets any previous direction set with
* {@link #setDirection(MediaDirection)} to the direction of the specified
* <tt>MediaDevice</tt>.
* </p>
*
* @param device the <tt>MediaDevice</tt> that this stream should use to
* play back and capture media
* @see MediaStream#setDevice(MediaDevice)
*/
public void setDevice(MediaDevice device)
{
if (device == null)
throw new NullPointerException("device");
// Require AbstractMediaDevice for MediaDeviceSession support.
AbstractMediaDevice abstractMediaDevice = (AbstractMediaDevice) device;
if ((deviceSession == null) || (deviceSession.getDevice() != device))
{
MediaDeviceSession oldValue = deviceSession;
MediaDirection startedDirection;
if (deviceSession != null)
{
startedDirection = deviceSession.getStartedDirection();
deviceSession.removePropertyChangeListener(
deviceSessionPropertyChangeListener);
deviceSession.close();
deviceSession = null;
}
else
startedDirection = MediaDirection.INACTIVE;
deviceSession = abstractMediaDevice.createSession();
deviceSession.addPropertyChangeListener(
deviceSessionPropertyChangeListener);
/*
* Setting a new device resets any previously-set direction.
* Otherwise, we risk not being able to set a new device if it is
* mandatory for the new device to fully cover any previously-set
* direction.
*/
direction = null;
MediaDeviceSession newValue = deviceSession;
deviceSessionChanged(oldValue, newValue);
if (deviceSession != null)
{
deviceSession.setMute(mute);
deviceSession.start(startedDirection);
synchronized (receiveStreamSyncRoot)
{
if (receiveStream != null)
deviceSession.setReceiveStream(receiveStream);
}
}
}
}
/**
* Sets the direction in which media in this <tt>MediaStream</tt> is to be
* streamed. If this <tt>MediaStream</tt> is not currently started, calls to
* {@link #start()} later on will start it only in the specified
* <tt>direction</tt>. If it is currently started in a direction different
* than the specified, directions other than the specified will be stopped.
*
* @param direction the <tt>MediaDirection</tt> in which this
* <tt>MediaStream</tt> is to stream media when it is started
* @see MediaStream#setDirection(MediaDirection)
*/
public void setDirection(MediaDirection direction)
{
if (direction == null)
throw new NullPointerException("direction");
/*
* Make sure that the specified direction is in accord with the
* direction of the MediaDevice of this instance.
*/
MediaDeviceSession deviceSession = getDeviceSession();
MediaDirection deviceDirection
= (deviceSession == null)
? MediaDirection.INACTIVE
: deviceSession.getDevice().getDirection();
if (!deviceDirection.and(direction).equals(direction))
throw new IllegalArgumentException("direction");
this.direction = direction;
switch (this.direction)
{
case INACTIVE:
stop(MediaDirection.SENDRECV);
return;
case RECVONLY:
stop(MediaDirection.SENDONLY);
break;
case SENDONLY:
stop(MediaDirection.RECVONLY);
break;
case SENDRECV:
break;
default:
// Don't know what it may be (in the future) so ignore it.
return;
}
if (started)
start(this.direction);
}
/**
* Sets the <tt>MediaFormat</tt> that this <tt>MediaStream</tt> should
* transmit in.
*
* @param format the <tt>MediaFormat</tt> that this <tt>MediaStream</tt>
* should transmit in
* @see MediaStream#setFormat(MediaFormat)
*/
public void setFormat(MediaFormat format)
{
setAdvancedAttributes(format.getAdvancedAttributes());
getDeviceSession().setFormat(format);
}
/**
* Causes this <tt>MediaStream</tt> to stop transmitting the media being fed
* from this stream's <tt>MediaDevice</tt> and transmit "silence" instead.
* "Silence" for video is understood as video data which is not the captured
* video data and may represent, for example, a black image.
*
* @param mute <tt>true</tt> to have this <tt>MediaStream</tt> transmit
* "silence" instead of the actual media data that it captures from its
* <tt>MediaDevice</tt>; <tt>false</tt> to transmit actual media data
* captured from the <tt>MediaDevice</tt> of this <tt>MediaStream</tt>
* @see MediaStream#setMute(boolean)
*/
public void setMute(boolean mute)
{
if (this.mute != mute)
{
this.mute = mute;
MediaDeviceSession deviceSession = getDeviceSession();
if (deviceSession != null)
deviceSession.setMute(this.mute);
}
}
/**
* Sets the target of this <tt>MediaStream</tt> to which it is to send and
* from which it is to receive data (e.g. RTP) and control data (e.g. RTCP).
*
* @param target the <tt>MediaStreamTarget</tt> describing the data
* (e.g. RTP) and the control data (e.g. RTCP) locations to which this
* <tt>MediaStream</tt> is to send and from which it is to receive
* @see MediaStream#setTarget(MediaStreamTarget)
*/
public void setTarget(MediaStreamTarget target)
{
// Short-circuit if setting the same target.
if (target == null)
{
if (rtpConnectorTarget == null)
return;
}
else if (target.equals(rtpConnectorTarget))
return;
rtpConnector.removeTargets();
rtpConnectorTarget = null;
boolean targetIsSet;
if (target != null)
{
InetSocketAddress dataAddr = target.getDataAddress();
InetSocketAddress controlAddr = target.getControlAddress();
try
{
rtpConnector
.addTarget(
new SessionAddress(
dataAddr.getAddress(),
dataAddr.getPort(),
controlAddr.getAddress(),
controlAddr.getPort()));
targetIsSet = true;
}
catch (IOException ioe)
{
// TODO
targetIsSet = false;
logger.error("Failed to set target " + target, ioe);
}
}
else
targetIsSet = true;
if (targetIsSet)
{
rtpConnectorTarget = target;
if (logger.isTraceEnabled())
logger
.trace(
"Set target of "
+ getClass().getSimpleName()
+ " with hashCode "
+ hashCode()
+ " to "
+ target);
}
}
/**
* Starts capturing media from this stream's <tt>MediaDevice</tt> and then
* streaming it through the local <tt>StreamConnector</tt> toward the
* stream's target address and port. Also puts the <tt>MediaStream</tt> in a
* listening state which make it play all media received from the
* <tt>StreamConnector</tt> on the stream's <tt>MediaDevice</tt>.
*
* @see MediaStream#start()
*/
public void start()
{
start(getDirection());
started = true;
}
/**
* Starts the processing of media in this instance in a specific direction.
*
* @param direction a <tt>MediaDirection</tt> value which represents the
* direction of the processing of media to be started. For example,
* {@link MediaDirection#SENDRECV} to start both capture and playback of
* media in this instance or {@link MediaDirection#SENDONLY} to only start
* the capture of media in this instance
*/
private void start(MediaDirection direction)
{
if (direction == null)
throw new NullPointerException("direction");
if (direction.allowsSending()
&& ((startedDirection == null)
|| !startedDirection.allowsSending()))
{
startSendStreams();
getDeviceSession().start(MediaDirection.SENDONLY);
if (MediaDirection.RECVONLY.equals(startedDirection))
startedDirection = MediaDirection.SENDRECV;
else if (startedDirection == null)
startedDirection = MediaDirection.SENDONLY;
}
if (direction.allowsReceiving()
&& ((startedDirection == null)
|| !startedDirection.allowsReceiving()))
{
startReceiveStreams();
getDeviceSession().start(MediaDirection.RECVONLY);
if (MediaDirection.SENDONLY.equals(startedDirection))
startedDirection = MediaDirection.SENDRECV;
else if (startedDirection == null)
startedDirection = MediaDirection.RECVONLY;
}
}
@SuppressWarnings("unchecked")
private void startReceiveStreams()
{
RTPManager rtpManager = getRTPManager();
Iterable<ReceiveStream> receiveStreams;
try
{
receiveStreams = rtpManager.getReceiveStreams();
}
catch (Exception ex)
{
/*
* It appears that in early call states when there are no streams, a
* NullPointerException could be thrown. Make sure we handle it
* gracefully.
*/
logger.trace("Failed to retrieve receive streams", ex);
receiveStreams = null;
}
if (receiveStreams != null)
{
for (ReceiveStream receiveStream : receiveStreams)
{
try
{
DataSource receiveStreamDataSource
= receiveStream.getDataSource();
/*
* For an unknown reason, the stream DataSource can be null
* at the end of the Call after re-INVITEs have been
* handled.
*/
if (receiveStreamDataSource != null)
receiveStreamDataSource.start();
}
catch (IOException ioex)
{
logger.warn(
"Failed to start stream " + receiveStream,
ioex);
}
}
}
}
/**
* Starts the <tt>SendStream</tt>s of the <tt>RTPManager</tt> of this
* <tt>MediaStreamImpl</tt>.
*/
private void startSendStreams()
{
/*
* Until it's clear that the SendStreams are required (i.e. we've
* negotiated to send), they will not be created. Otherwise, their
* creation isn't only illogical but also causes the CaptureDevice to
* be used.
*/
if (!sendStreamsAreCreated)
createSendStreams();
RTPManager rtpManager = getRTPManager();
@SuppressWarnings("unchecked")
Iterable<SendStream> sendStreams = rtpManager.getSendStreams();
if (sendStreams != null)
{
for (SendStream sendStream : sendStreams)
{
try
{
// TODO Are we sure we want to connect here?
sendStream.getDataSource().connect();
sendStream.start();
sendStream.getDataSource().start();
if (logger.isTraceEnabled())
{
logger.trace(
"Started SendStream with hashCode "
+ sendStream.hashCode());
}
}
catch (IOException ioe)
{
logger
.warn("Failed to start stream " + sendStream, ioe);
}
}
}
}
/**
* Stops all streaming and capturing in this <tt>MediaStream</tt> and closes
* and releases all open/allocated devices/resources. Has no effect if this
* <tt>MediaStream</tt> is already closed and is simply ignored.
*
* @see MediaStream#stop()
*/
public void stop()
{
stop(MediaDirection.SENDRECV);
started = false;
}
/**
* Stops the processing of media in this instance in a specific direction.
*
* @param direction a <tt>MediaDirection</tt> value which represents the
* direction of the processing of media to be stopped. For example,
* {@link MediaDirection#SENDRECV} to stop both capture and playback of
* media in this instance or {@link MediaDirection#SENDONLY} to only stop
* the capture of media in this instance
*/
private void stop(MediaDirection direction)
{
if (direction == null)
throw new NullPointerException("direction");
if (rtpManager == null)
return;
if ((MediaDirection.SENDRECV.equals(direction)
|| MediaDirection.SENDONLY.equals(direction))
&& (MediaDirection.SENDRECV.equals(startedDirection)
|| MediaDirection.SENDONLY.equals(startedDirection)))
{
stopSendStreams(false);
if (deviceSession != null)
deviceSession.stop(MediaDirection.SENDONLY);
if (MediaDirection.SENDRECV.equals(startedDirection))
startedDirection = MediaDirection.RECVONLY;
else if (MediaDirection.SENDONLY.equals(startedDirection))
startedDirection = null;
}
if ((MediaDirection.SENDRECV.equals(direction)
|| MediaDirection.RECVONLY.equals(direction))
&& (MediaDirection.SENDRECV.equals(startedDirection)
|| MediaDirection.RECVONLY.equals(startedDirection)))
{
stopReceiveStreams();
if (deviceSession != null)
deviceSession.stop(MediaDirection.RECVONLY);
if (MediaDirection.SENDRECV.equals(startedDirection))
startedDirection = MediaDirection.SENDONLY;
else if (MediaDirection.RECVONLY.equals(startedDirection))
startedDirection = null;
}
}
@SuppressWarnings("unchecked")
private void stopReceiveStreams()
{
Iterable<ReceiveStream> receiveStreams;
try
{
receiveStreams = rtpManager.getReceiveStreams();
}
catch (Exception ex)
{
/*
* It appears that in early call states when there are no streams, a
* NullPointerException could be thrown. Make sure we handle it
* gracefully.
*/
logger.trace("Failed to retrieve receive streams", ex);
receiveStreams = null;
}
if (receiveStreams != null)
{
for (ReceiveStream receiveStream : receiveStreams)
{
try
{
DataSource receiveStreamDataSource
= receiveStream.getDataSource();
/*
* For an unknown reason, the stream DataSource can be null
* at the end of the Call after re-INVITEs have been
* handled.
*/
if (receiveStreamDataSource != null)
receiveStreamDataSource.stop();
}
catch (IOException ioex)
{
logger.warn("Failed to stop stream " + receiveStream, ioex);
}
}
}
}
/**
* Stops the <tt>SendStream</tt>s that this instance is sending to its
* remote peer and optionally closes them.
*
* @param close <tt>true</tt> to close the <tt>SendStream</tt>s that this
* instance is sending to its remote peer after stopping them;
* <tt>false</tt> to only stop them
* @return the <tt>SendStream</tt>s which were stopped
*/
private Iterable<SendStream> stopSendStreams(boolean close)
{
if (rtpManager == null)
return null;
@SuppressWarnings("unchecked")
Iterable<SendStream> sendStreams = rtpManager.getSendStreams();
Iterable<SendStream> stoppedSendStreams
= stopSendStreams(sendStreams, close);
if (close)
sendStreamsAreCreated = false;
return stoppedSendStreams;
}
/**
* Stops specific <tt>SendStream</tt>s and optionally closes them.
*
* @param sendStreams the <tt>SendStream</tt>s to be stopped and optionally
* closed
* @param close <tt>true</tt> to close the specified <tt>SendStream</tt>s
* after stopping them; <tt>false</tt> to only stop them
* @return the stopped <tt>SendStream</tt>s
*/
private Iterable<SendStream> stopSendStreams(
Iterable<SendStream> sendStreams,
boolean close)
{
if (sendStreams == null)
return null;
for (SendStream sendStream : sendStreams)
try
{
sendStream.getDataSource().stop();
sendStream.stop();
if (close)
try
{
sendStream.close();
}
catch (NullPointerException npe)
{
/*
* Sometimes com.sun.media.rtp.RTCPTransmitter#bye() may
* throw NullPointerException but it does not seem to be
* guaranteed because it does not happen while debugging
* and stopping at a breakpoint on SendStream#close().
* One of the cases in which it appears upon call
* hang-up is if we do not close the "old" SendStreams
* upon reinvite(s). Though we are now closing such
* SendStreams, ignore the exception here just in case
* because we already ignore IOExceptions.
*/
logger
.error(
"Failed to close stream " + sendStream,
npe);
}
}
catch (IOException ioe)
{
logger.warn("Failed to stop stream " + sendStream, ioe);
}
return sendStreams;
}
/**
* Returns a human-readable representation of a specific <tt>DataSource</tt>
* instance in the form of a <tt>String</tt> value.
*
* @param dataSource the <tt>DataSource</tt> to return a human-readable
* representation of
* @return a <tt>String</tt> value which gives a human-readable
* representation of the specified <tt>dataSource</tt>
*/
public static String toString(DataSource dataSource)
{
StringBuffer str = new StringBuffer();
str.append(dataSource.getClass().getSimpleName());
str.append(" with hashCode ");
str.append(dataSource.hashCode());
MediaLocator locator = dataSource.getLocator();
if (locator != null)
{
str.append(" and locator ");
str.append(locator);
}
return str.toString();
}
/**
* Notifies this <tt>ReceiveStreamListener</tt> that the <tt>RTPManager</tt>
* it is registered with has generated an event related to a <tt>ReceiveStream</tt>.
*
* @param event the <tt>ReceiveStreamEvent</tt> which specifies the
* <tt>ReceiveStream</tt> that is the cause of the event and the very type
* of the event
* @see ReceiveStreamListener#update(ReceiveStreamEvent)
*/
public void update(ReceiveStreamEvent event)
{
if (event instanceof NewReceiveStreamEvent)
{
ReceiveStream receiveStream = event.getReceiveStream();
if (receiveStream != null)
{
long receiveStreamSSRC = receiveStream.getSSRC();
if (logger.isTraceEnabled())
{
logger.trace(
"Received new ReceiveStream with ssrc "
+ receiveStreamSSRC);
}
setRemoteSourceID(receiveStreamSSRC);
synchronized (receiveStreamSyncRoot)
{
if (this.receiveStream != receiveStream)
{
this.receiveStream = receiveStream;
MediaDeviceSession deviceSession = getDeviceSession();
if (deviceSession != null)
deviceSession.setReceiveStream(this.receiveStream);
}
}
}
}
else if (event instanceof TimeoutEvent)
{
ReceiveStream receiveStream = event.getReceiveStream();
if (receiveStream != null)
{
synchronized (receiveStreamSyncRoot)
{
if (this.receiveStream == receiveStream)
{
this.receiveStream = null;
MediaDeviceSession deviceSession = getDeviceSession();
if (deviceSession != null)
deviceSession.setReceiveStream(null);
}
}
}
}
}
/**
* Notifies this <tt>SendStreamListener</tt> that the <tt>RTPManager</tt> it
* is registered with has generated an event related to a <tt>SendStream</tt>.
*
* @param event the <tt>SendStreamEvent</tt> which specifies the
* <tt>SendStream</tt> that is the cause of the event and the very type of
* the event
* @see SendStreamListener#update(SendStreamEvent)
*/
public void update(SendStreamEvent event)
{
// TODO Auto-generated method stub
}
/**
* Notifies this <tt>SessionListener</tt> that the <tt>RTPManager</tt> it is
* registered with has generated an event which pertains to the session as a
* whole and does not belong to a <tt>ReceiveStream</tt> or a
* <tt>SendStream</tt> or a remote participant necessarily.
*
* @param event the <tt>SessionEvent</tt> which specifies the source and the
* very type of the event
* @see SessionListener#update(SessionEvent)
*/
public void update(SessionEvent event)
{
// TODO Auto-generated method stub
}
/**
* Sets the local SSRC identifier and fires the corresponding
* <tt>PropertyChangeEvent</tt>.
*
* @param ssrc the SSRC identifier that this stream will be using in
* outgoing RTP packets from now on.
*/
protected void setLocalSourceID(long ssrc)
{
Long oldValue = this.localSourceID;
this.localSourceID = ssrc;
firePropertyChange(PNAME_LOCAL_SSRC, oldValue, ssrc);
}
/**
* Sets the remote SSRC identifier and fires the corresponding
* <tt>PropertyChangeEvent</tt>.
*
* @param ssrc the SSRC identifier that this stream will be using in
* outgoing RTP packets from now on.
*/
protected void setRemoteSourceID(long ssrc)
{
Long oldValue = this.remoteSourceID;
this.remoteSourceID = ssrc;
firePropertyChange(PNAME_REMOTE_SSRC, oldValue, ssrc);
}
/**
* Returns the list of CSRC identifiers for all parties currently known
* to contribute to the media that this stream is sending toward its remote
* counter part. In other words, the method returns the list of CSRC IDs
* that this stream will include in outgoing RTP packets. This method will
* return an <tt>null</tt> in case this stream is not part of a mixed
* conference call.
*
* @return a <tt>long[]</tt> array of CSRC IDs representing parties that are
* currently known to contribute to the media that this stream is sending
* or an <tt>null</tt> in case this <tt>MediaStream</tt> is not part of a
* conference call.
*/
public long[] getLocalContributingSourceIDs()
{
return localContributingSourceIDList;
}
/**
* Returns the <tt>List</tt> of CSRC identifiers representing the parties
* contributing to the stream that we are receiving from this
* <tt>MediaStream</tt>'s remote party.
*
* @return a <tt>List</tt> of CSRC identifiers representing the parties
* contributing to the stream that we are receiving from this
* <tt>MediaStream</tt>'s remote party.
*/
public long[] getRemoteContributingSourceIDs()
{
long[] remoteSsrcList = getDeviceSession().getRemoteSSRCList();
// TODO implement
return remoteSsrcList;
}
}
|
package hudson.slaves;
import hudson.FilePath;
import hudson.Functions;
import hudson.model.Computer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Used by {@link Computer} to keep track of workspaces that are actively in use.
*
* <p>
* SUBJECT TO CHANGE! Do not use this from plugins directly.
*
* @author Kohsuke Kawaguchi
* @since 1.319
* @see Computer#getWorkspaceList()
*/
public final class WorkspaceList {
private static final String WORKSPACE_NAME_SUFFIX = "_";
/**
* Book keeping for workspace allocation.
*/
public static final class Entry {
/**
* Who acquired this workspace?
*/
public final Thread holder = Thread.currentThread();
/**
* When?
*/
public final long time = System.currentTimeMillis();
/**
* From where?
*/
public final Exception source = new Exception();
/**
* True makes the caller of {@link WorkspaceList#allocate(FilePath)} wait
* for this workspace.
*/
public final boolean quick;
public final FilePath path;
private Entry(FilePath path, boolean quick) {
this.path = path;
this.quick = quick;
}
@Override
public String toString() {
String s = path+" owned by "+holder.getName()+" from "+new Date(time);
if(quick) s+=" (quick)";
s+="\n"+Functions.printThrowable(source);
return s;
}
}
/**
* Represents a leased workspace that needs to be returned later.
*/
public static abstract class Lease {
public final FilePath path;
protected Lease(FilePath path) {
this.path = path;
}
/**
* Releases this lease.
*/
public abstract void release();
/**
* Creates a dummy {@link Lease} object that does no-op in the release.
*/
public static Lease createDummyLease(FilePath p) {
return new Lease(p) {
public void release() {
// noop
}
};
}
}
private final Map<FilePath,Entry> inUse = new HashMap<FilePath,Entry>();
public WorkspaceList() {
}
/**
* Allocates a workspace by adding some variation to the given base to make it unique.
*/
public synchronized Lease allocate(FilePath base) throws InterruptedException {
for (int i=1; ; i++) {
//Workspace suffix was changed from @ to _, because of some issues with SCMs.
FilePath candidate = i==1 ? base : base.withSuffix(WORKSPACE_NAME_SUFFIX + i);
Entry e = inUse.get(candidate);
if(e!=null && !e.quick)
continue;
return acquire(candidate);
}
}
/**
* Just record that this workspace is being used, without paying any attention to the sycnhronization support.
*/
public synchronized Lease record(FilePath p) {
log("recorded "+p);
Entry old = inUse.put(p, new Entry(p, false));
if (old!=null)
throw new AssertionError("Tried to record a workspace already owned: "+old);
return lease(p);
}
/**
* Releases an allocated or acquired workspace.
*/
private synchronized void _release(FilePath p) {
Entry old = inUse.remove(p);
if (old==null)
throw new AssertionError("Releasing unallocated workspace "+p);
notifyAll();
}
/**
* Acquires the given workspace. If necessary, this method blocks until it's made available.
*
* @return
* The same {@link FilePath} as given to this method.
*/
public synchronized Lease acquire(FilePath p) throws InterruptedException {
return acquire(p,false);
}
/**
* See {@link #acquire(FilePath)}
*
* @param quick
* If true, indicates that the acquired workspace will be returned quickly.
* This makes other calls to {@link #allocate(FilePath)} to wait for the release of this workspace.
*/
public synchronized Lease acquire(FilePath p, boolean quick) throws InterruptedException {
while (inUse.containsKey(p))
wait();
log("acquired "+p);
inUse.put(p,new Entry(p,quick));
return lease(p);
}
/**
* Wraps a path into a valid lease.
*/
private Lease lease(FilePath p) {
return new Lease(p) {
public void release() {
_release(path);
}
};
}
private void log(String msg) {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine(Thread.currentThread().getName() + " " + msg);
}
private static final Logger LOGGER = Logger.getLogger(WorkspaceList.class.getName());
}
|
package org.orbeon.oxf.processor.XQuery;
import org.apache.log4j.Logger;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.pipeline.api.XMLReceiver;
import org.orbeon.oxf.processor.ProcessorImpl;
import org.orbeon.oxf.processor.ProcessorInputOutputInfo;
import org.orbeon.oxf.processor.ProcessorOutput;
import org.orbeon.oxf.processor.transformer.TransformerURIResolver;
import org.orbeon.oxf.xml.ContentHandlerHelper;
import org.orbeon.oxf.xml.SimpleForwardingXMLReceiver;
import org.orbeon.oxf.xml.XMLUtils;
import org.orbeon.saxon.xqj.SaxonXQDataSource;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import javax.xml.xquery.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
/**
* XQuery client/server processor, typically based on XQJ.
*/
public class XQueryProcessor extends ProcessorImpl {
public static final String XQUERY_NAMESPACE_URI = "http:
private static Logger logger = Logger.getLogger(XQueryProcessor.class);
private static HashMap<String, String> knownImplementations = initKnownImplementations();
private static HashMap<String, String> initKnownImplementations() {
HashMap<String, String> implementations = new HashMap<String, String>();
implementations.put("exist", "net.xqj.exist.ExistXQDataSource");
implementations.put("oracle", "oracle.xquery.xqj.OXQDataSource");
implementations.put("saxon", "org.orbeon.saxon.xqj.SaxonXQDataSource");
return implementations;
}
private static HashMap<String, String> knownJDBCImplementations = initKnownJDBCImplementations();
private static HashMap<String, String> initKnownJDBCImplementations() {
HashMap<String, String> implementations = new HashMap<String, String>();
implementations.put("oracle", "oracle.jdbc.OracleDriver");
return implementations;
}
public XQueryProcessor() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, XQUERY_NAMESPACE_URI));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA));
}
@Override
public ProcessorOutput createOutput(String name) {
final ProcessorOutput output = new ProcessorOutputImpl(XQueryProcessor.this, name) {
public void readImpl(final PipelineContext pipelineContext, XMLReceiver xmlReceiver) {
class ConfigContainer extends ObjectReceiver {
public ConfigContainer() {
}
public Config config;
class Config extends ObjectReceiver {
public Config() {
}
public String vendor;
public String implementation;
public String info;
public String username;
public String password;
public JDBC jdbc;
public Vector<NameValuePair> property = new Vector<NameValuePair>();
public String query;
public Vector<NameValuePair> parameter = new Vector<NameValuePair>();
class NameValuePair extends ObjectReceiver {
public NameValuePair() {
}
public String name;
public String value;
}
class JDBC extends ObjectReceiver {
public JDBC() {
}
public String url;
public String implementation;
}
String getImplementation() {
if (vendor != null) {
return knownImplementations.get(vendor);
}
return implementation;
}
public String getJDBCImplementation() {
if (jdbc.implementation != null) {
return jdbc.implementation;
}
return knownJDBCImplementations.get(vendor);
}
}
}
final ConfigContainer container = new ConfigContainer();
readInputAsSAX(pipelineContext, INPUT_CONFIG, container);
final ConfigContainer.Config config = container.config;
ContentHandlerHelper helper = new ContentHandlerHelper(xmlReceiver);
try {
if ("oracle".equals(config.vendor)) {
// Use JDBC as a workaround until we find out how to set the connection info in XQJ
// (see https://forums.oracle.com/forums/thread.jspa?messageID=10338407#10338407)
Driver driver = (Driver) Class.forName(config.getJDBCImplementation()).newInstance();
Connection conn = driver.connect(config.jdbc.url, null);
StringBuilder xquery = new StringBuilder("SELECT * from XMLTable('" + config.query.replaceAll("'", "''") + "' ");
Iterator<ConfigContainer.Config.NameValuePair> iter = config.parameter.iterator();
int i = 1;
while (iter.hasNext()) {
ConfigContainer.Config.NameValuePair parameter = iter.next();
xquery.append((i == 1 ? "PASSING " : ", ") + ":" + i + " AS \"" + parameter.name + "\" ");
i++;
}
xquery.append(")");
logger.debug("XQuery: " + xquery.toString());
PreparedStatement statement = conn.prepareStatement(xquery.toString());
i = 1;
iter = config.parameter.iterator();
while (iter.hasNext()) {
ConfigContainer.Config.NameValuePair parameter = iter.next();
statement.setString(i, parameter.value);
i++;
}
ResultSet rs = statement.executeQuery();
helper.startDocument();
helper.startElement("results");
while (rs.next()) {
for (i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
helper.startElement("result");
// This used to use SQLXML.getString() but "The behavior of this method is the same as
// ResultSet.getString() when the designated column of the ResultSet has a
// type java.sql.Types of SQLXML." For 1.5 compatibility we use getString() instead.
String sqlxml = rs.getString(i);
if (sqlxml != null) {
XMLUtils.parseDocumentFragment(sqlxml, xmlReceiver);
}
}
helper.endElement();
}
helper.endElement();
helper.endDocument();
rs.close();
statement.close();
conn.close();
} else {
// Use XQJ
XQDataSource xqs = (XQDataSource) Class.forName(config.getImplementation()).newInstance();
if (config.info != null) {
helper.startDocument();
helper.startElement("info");
helper.element("vendor", config.vendor == null ? "" : config.vendor);
helper.element("implementation", config.getImplementation());
Class[] interfaces = xqs.getClass().getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
helper.element("implements", interfaces[i].getCanonicalName());
}
Constructor[] constructors = xqs.getClass().getConstructors();
for (int i = 0; i < constructors.length; i++) {
helper.element("constructor", constructors[i].toString());
}
Method[] methods = xqs.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
helper.element("method", methods[i].toString());
}
String[] names = xqs.getSupportedPropertyNames();
helper.startElement("supported-properties");
for (int i = 0; i < names.length; i++) {
helper.element("property", names[i]);
}
helper.endElement();
helper.endElement();
helper.endDocument();
} else {
Iterator<ConfigContainer.Config.NameValuePair> iter = config.property.iterator();
while (iter.hasNext()) {
ConfigContainer.Config.NameValuePair property = iter.next();
xqs.setProperty(property.name, property.value);
}
if (SaxonXQDataSource.class.isInstance(xqs)) {
// For Saxon: setup a URI resolver to support the "input:" scheme
final TransformerURIResolver resolver = new TransformerURIResolver(XQueryProcessor.this, pipelineContext, INPUT_CONFIG, XMLUtils.ParserConfiguration.PLAIN);
((SaxonXQDataSource) xqs).getConfiguration().setURIResolver(resolver);
}
XQConnection conn;
if (config.jdbc != null) {
Driver driver = (Driver) Class.forName(config.getJDBCImplementation()).newInstance();
Connection jdbcConn = driver.connect(config.jdbc.url, null);
// Class.forName(config.getJDBCImplementation());
// Connection jdbcConn = DriverManager.getConnection(config.jdbc.url);
conn = xqs.getConnection(jdbcConn);
} else if (config.username != null) {
conn = xqs.getConnection(config.username, config.password);
} else {
conn = xqs.getConnection();
}
XQPreparedExpression xqpe = conn.prepareExpression(config.query);
iter = config.parameter.iterator();
while (iter.hasNext()) {
ConfigContainer.Config.NameValuePair parameter = iter.next();
xqpe.bindString(new QName(parameter.name), parameter.value, null);
}
XQResultSequence rs = xqpe.executeQuery();
helper.startDocument();
helper.startElement("results");
while (rs.next()) {
helper.startElement("result");
if (rs.getItemType().getItemKind() == XQItemType.XQITEMKIND_TEXT || rs.getItemType().getItemKind() == XQItemType.XQITEMKIND_ATOMIC) {
helper.text(rs.getItem().getAtomicValue());
} else {
rs.writeItemToSAX(new SimpleForwardingXMLReceiver(xmlReceiver) {
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
});
}
helper.endElement();
}
helper.endElement();
helper.endDocument();
conn.close();
}
}
} catch (Exception e) {
throw new OXFException(e);
}
}
};
addOutput(name, output);
return output;
}
}
|
package urlshortener.aeternum;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import urlshortener.aeternum.web.QrGenerator;
import java.net.URI;
import java.nio.charset.Charset;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.Banner.Mode.LOG;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= RANDOM_PORT)
@DirtiesContext
public class SystemTests {
private static final Logger LOG = LoggerFactory
.getLogger(SystemTests.class);
@Value("${local.server.port}")
private int port = 0;
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port, String.class);
assertThat(entity.getStatusCode(), is(HttpStatus.OK));
assertTrue(entity.getHeaders().getContentType().isCompatibleWith(new MediaType("text", "html")));
assertThat(entity.getBody(), containsString("<title>URL"));
}
@Test
public void testCss() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port
+ "/webjars/bootstrap/3.3.5/css/bootstrap.min.css", String.class);
assertThat(entity.getStatusCode(), is(HttpStatus.OK));
assertThat(entity.getHeaders().getContentType(), is(MediaType.valueOf("text/css")));
assertThat(entity.getBody(), containsString("body"));
}
@Test
public void testCreateLink() throws Exception {
ResponseEntity<String> entity = postLink("http://example.com/");
assertThat(entity.getStatusCode(), is(HttpStatus.CREATED));
assertThat(entity.getHeaders().getLocation(), is(new URI("http://localhost:"+ this.port+"/f684a3c4")));
assertThat(entity.getHeaders().getContentType(), is(new MediaType("application", "json", Charset.forName("UTF-8"))));
ReadContext rc = JsonPath.parse(entity.getBody());
assertThat(rc.read("$.hash"), is("f684a3c4"));
assertThat(rc.read("$.uri"), is("http://localhost:"+ this.port+"/f684a3c4"));
assertThat(rc.read("$.target"), is("http://example.com/"));
assertThat(rc.read("$.sponsor"), is(nullValue()));
}
@Test
public void testRedirection() throws Exception {
postLink("http://example.com/");
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port
+ "/f684a3c4", String.class);
assertThat(entity.getStatusCode().toString(), is("307"));
assertThat(entity.getHeaders().getLocation().toString(), is("http://example.com/"));
}
private ResponseEntity<String> postLink(String url) {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("url", url);
return new TestRestTemplate().postForEntity(
"http://localhost:" + this.port+"/link", parts, String.class);
}
}
|
package de.dhbw.humbuch.view;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import com.google.common.eventbus.EventBus;
import com.google.inject.Inject;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.fieldgroup.BeanFieldGroup;
import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.data.util.filter.Or;
import com.vaadin.data.util.filter.SimpleStringFilter;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.event.ShortcutListener;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.AbstractTextField.TextChangeEventMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.DateField;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import de.davherrmann.mvvm.BasicState;
import de.davherrmann.mvvm.State;
import de.davherrmann.mvvm.StateChangeListener;
import de.davherrmann.mvvm.ViewModelComposer;
import de.davherrmann.mvvm.annotations.BindState;
import de.dhbw.humbuch.event.ConfirmEvent;
import de.dhbw.humbuch.event.MessageEvent;
import de.dhbw.humbuch.model.entity.Category;
import de.dhbw.humbuch.model.entity.SchoolYear.Term;
import de.dhbw.humbuch.model.entity.Subject;
import de.dhbw.humbuch.model.entity.TeachingMaterial;
import de.dhbw.humbuch.util.BookLookup;
import de.dhbw.humbuch.util.BookLookup.Book;
import de.dhbw.humbuch.util.BookLookup.BookNotFoundException;
import de.dhbw.humbuch.viewmodel.TeachingMaterialViewModel;
import de.dhbw.humbuch.viewmodel.TeachingMaterialViewModel.Categories;
import de.dhbw.humbuch.viewmodel.TeachingMaterialViewModel.TeachingMaterials;
/**
*
* @author Martin Wentzel
*
*/
public class TeachingMaterialView extends VerticalLayout implements View, ViewInformation {
private static final long serialVersionUID = -5063268947544706757L;
private static final String TITLE = "Lehrmittelverwaltung";
private static final String TABLE_CATEGORY = "category";
private static final String TABLE_NAME = "name";
private static final String TABLE_PROFILE = "profile";
private static final String TABLE_FROMGRADE = "fromGrade";
private static final String TABLE_FROMTERM = "fromTerm";
private static final String TABLE_TOGRADE = "toGrade";
private static final String TABLE_TOTERM = "toTerm";
private static final String TABLE_PRODUCER = "producer";
private static final String TABLE_IDENTNR = "identifyingNumber";
private static final String TABLE_COMMENT = "comment";
private static final String TABLE_VALIDFROM = "validFrom";
private static final String TABLE_VALIDUNTIL = "validUntil";
private EventBus eventBus;
private TeachingMaterialViewModel teachingMaterialViewModel;
/**
* Layout components
*/
private HorizontalLayout head;
private TextField filter;
private Button btnEdit;
private Button btnNew;
private Button btnDelete;
private Table materialsTable;
private BeanItemContainer<TeachingMaterial> tableData;
private BeanFieldGroup<TeachingMaterial> binder = new BeanFieldGroup<TeachingMaterial>(TeachingMaterial.class);
@BindState(TeachingMaterials.class)
public final State<Collection<TeachingMaterial>> teachingMaterials = new BasicState<>(Collection.class);
@BindState(Categories.class)
public final State<Collection<Category>> categories = new BasicState<>(Collection.class);
/**
* All popup-window components and the corresponding binded states. The
* popup-window for adding a new teaching material and editing a teaching
* material is the same. Only the caption will be set differently
*/
private Window windowEditTeachingMaterial;
private FormLayout windowContent;
private HorizontalLayout windowButtons;
private TextField txtTmName = new TextField("Titel");
private TextField txtIdentNr = new TextField();
private TextField txtProducer = new TextField("Hersteller/Verlag");
private TextField txtFromGrade = new TextField();
private TextField txtToGrade = new TextField();
private ComboBox cbProfiles = new ComboBox("Profil");
private ComboBox cbFromTerm = new ComboBox();
private ComboBox cbToTerm = new ComboBox();
private ComboBox cbCategory = new ComboBox("Kategorie");
private DateField dfValidFrom = new DateField("Gültig von");
private DateField dfValidUntil = new DateField("Gültig bis");
private TextArea textAreaComment = new TextArea("Kommentar");
private Button btnWindowSave = new Button("Speichern");
private Button btnWindowCancel = new Button("Abbrechen");
private Button btnISBNImport = new Button("Hole Daten");
@Inject
public TeachingMaterialView(ViewModelComposer viewModelComposer, TeachingMaterialViewModel teachingMaterialViewModel, EventBus eventBus) {
this.teachingMaterialViewModel = teachingMaterialViewModel;
this.eventBus = eventBus;
init();
buildLayout();
bindViewModel(viewModelComposer, teachingMaterialViewModel);
}
/**
* Initializes the components and sets attributes.
*
*/
@SuppressWarnings("serial")
private void init() {
head = new HorizontalLayout();
head.setWidth("100%");
head.setSpacing(true);
// Filter
filter = new TextField();
filter.setImmediate(true);
filter.setInputPrompt("Lehrmittel suchen...");
filter.setWidth("50%");
filter.setTextChangeEventMode(TextChangeEventMode.EAGER);
head.addComponent(filter);
head.setExpandRatio(filter, 1);
head.setComponentAlignment(filter, Alignment.MIDDLE_LEFT);
// Buttons
HorizontalLayout buttons = new HorizontalLayout();
buttons.setSpacing(true);
// Add
btnNew = new Button("Hinzufügen");
buttons.addComponent(btnNew);
// Delete
btnDelete = new Button("Löschen");
btnDelete.setEnabled(false);
buttons.addComponent(btnDelete);
// Edit
btnEdit = new Button("Bearbeiten");
btnEdit.setEnabled(false);
btnEdit.addStyleName("default");
btnEdit.setClickShortcut(KeyCode.ENTER);
buttons.addComponent(btnEdit);
head.addComponent(buttons);
head.setComponentAlignment(buttons, Alignment.MIDDLE_RIGHT);
// Instantiate table
materialsTable = new Table();
materialsTable.setSelectable(true);
materialsTable.setImmediate(true);
materialsTable.setSizeFull();
materialsTable.setColumnCollapsingAllowed(true);
tableData = new BeanItemContainer<TeachingMaterial>(
TeachingMaterial.class);
materialsTable.setContainerDataSource(tableData);
materialsTable.setVisibleColumns(new Object[] { TABLE_NAME,
TABLE_PRODUCER, TABLE_PROFILE, TABLE_FROMGRADE, TABLE_TOGRADE,
TABLE_CATEGORY, TABLE_IDENTNR });
materialsTable.setColumnHeader(TABLE_CATEGORY, "Kategorie");
materialsTable.setColumnHeader(TABLE_NAME, "Titel");
materialsTable.setColumnHeader(TABLE_PROFILE, "Profil");
materialsTable.setColumnHeader(TABLE_FROMGRADE, "Von Klasse");
materialsTable.setColumnHeader(TABLE_TOGRADE, "Bis Klasse");
materialsTable.setColumnHeader(TABLE_PRODUCER, "Hersteller/Verlag");
materialsTable.setColumnHeader(TABLE_IDENTNR, "Nummer/ISBN");
materialsTable.setColumnHeader(TABLE_COMMENT, "Kommentar");
materialsTable.setColumnHeader(TABLE_VALIDFROM, "Gültig von");
materialsTable.setColumnHeader(TABLE_VALIDUNTIL, "Gültig bis");
materialsTable.addGeneratedColumn(TABLE_PROFILE, new ColumnGenerator() {
@Override
public Object generateCell(Table source, Object itemId,
Object columnId) {
TeachingMaterial item = (TeachingMaterial) itemId;
String profile = "";
for(Subject subject : item.getProfile()) {
profile = subject.toString();
}
return profile;
}
});
binder.setBuffered(true);
this.createEditWindow();
this.addListener();
}
/**
* Creates the window for editing and creating teaching materials
*
* @return The created Window
*/
@SuppressWarnings("serial")
public void createEditWindow() {
// Create Window and set parameters
windowEditTeachingMaterial = new Window();
windowEditTeachingMaterial.center();
windowEditTeachingMaterial.setModal(true);
windowEditTeachingMaterial.setResizable(false);
windowContent = new FormLayout();
windowContent.setMargin(true);
windowButtons = new HorizontalLayout();
windowButtons.setSpacing(true);
btnWindowSave.addStyleName("default");
// Fill Comboboxes
cbFromTerm.addItem(Term.FIRST);
cbFromTerm.addItem(Term.SECOND);
cbToTerm.addItem(Term.FIRST);
cbToTerm.addItem(Term.SECOND);
for (Subject subject : Subject.values()) {
Set<Subject> subjects = new HashSet<Subject>();
subjects.add(subject);
cbProfiles.addItem(subjects);
cbProfiles.setItemCaption(subjects, subject.toString());
}
// Set Form options
cbCategory.setNullSelectionAllowed(false);
cbProfiles.setNullSelectionAllowed(false);
cbFromTerm.setNullSelectionAllowed(false);
cbToTerm.setNullSelectionAllowed(false);
txtTmName.setRequired(true);
cbCategory.setRequired(true);
cbProfiles.setRequired(true);
dfValidFrom.setRequired(true);
dfValidUntil.setDescription("Leer für unbestimmtes Gültigkeitsdatum");
// Input prompts
txtIdentNr.setInputPrompt("ISBN");
txtTmName.setInputPrompt("Titel oder Name");
txtProducer.setInputPrompt("z.B. Klett");
txtFromGrade.setInputPrompt("z.B. 5");
txtToGrade.setInputPrompt("z.B. 7");
textAreaComment.setInputPrompt("Zusätzliche Informationen");
// NullRepresentation
txtIdentNr.setNullRepresentation("");
txtTmName.setNullRepresentation("");
txtProducer.setNullRepresentation("");
txtFromGrade.setNullRepresentation("");
txtToGrade.setNullRepresentation("");
textAreaComment.setNullRepresentation("");
// Bind to FieldGroup
binder.bind(txtTmName, TABLE_NAME);
binder.bind(txtIdentNr, TABLE_IDENTNR);
binder.bind(cbCategory, TABLE_CATEGORY);
binder.bind(txtProducer, TABLE_PRODUCER);
binder.bind(cbProfiles, TABLE_PROFILE);
binder.bind(txtFromGrade, TABLE_FROMGRADE);
binder.bind(cbFromTerm, TABLE_FROMTERM);
binder.bind(txtToGrade, TABLE_TOGRADE);
binder.bind(cbToTerm, TABLE_TOTERM);
binder.bind(dfValidFrom, TABLE_VALIDFROM);
binder.bind(dfValidUntil, TABLE_VALIDUNTIL);
binder.bind(textAreaComment, TABLE_COMMENT);
// Add all components
windowContent.addComponent(txtTmName);
windowContent.addComponent(new HorizontalLayout(){
{
setSpacing(true);
setCaption("ISBN/Nummer");
setStyleName("required");
addComponent(txtIdentNr);
addComponent(btnISBNImport);
}
});
windowContent.addComponent(cbCategory);
windowContent.addComponent(txtProducer);
windowContent.addComponent(cbProfiles);
windowContent.addComponent(new HorizontalLayout() {
{
setSpacing(true);
setCaption("Von Klassenstufe");
txtFromGrade.setWidth("80px");
addComponent(txtFromGrade);
addComponent(cbFromTerm);
}
});
windowContent.addComponent(new HorizontalLayout() {
{
setSpacing(true);
setCaption("Bis Klassenstufe");
txtToGrade.setWidth("80px");
addComponent(txtToGrade);
addComponent(cbToTerm);
}
});
windowContent.addComponent(dfValidFrom);
windowContent.addComponent(dfValidUntil);
windowContent.addComponent(textAreaComment);
windowButtons.addComponent(btnWindowCancel);
windowButtons.addComponent(btnWindowSave);
windowContent.addComponent(windowButtons);
windowEditTeachingMaterial.setContent(windowContent);
windowEditTeachingMaterial.setCaption("Lehrmittel bearbeiten");
windowEditTeachingMaterial.setCloseShortcut(KeyCode.ESCAPE, null);
}
/**
* Adds all listener to their corresponding components.
*
*/
@SuppressWarnings("serial")
private void addListener() {
/**
* Fetches the book data by using a given ISBN and inserting it into the
* corresponding fields
*/
btnISBNImport.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
try {
Book book = BookLookup.lookup(txtIdentNr.getValue());
txtTmName.setValue(book.title);
txtProducer.setValue(book.publisher);
String commentText = "Autor(en): " + book.author;
if (textAreaComment.getValue() != null && textAreaComment.getValue().isEmpty()) {
commentText += '\n' + textAreaComment.getValue();
}
textAreaComment.setValue(commentText);
} catch (BookNotFoundException e) {
eventBus.post(new MessageEvent("Es konnte kein Buch zu der ISBN gefunden werden."));
}
}
});
/**
* Listens for changes in the Collection teachingMaterials and adds them
* to the container
*/
teachingMaterials.addStateChangeListener(new StateChangeListener() {
@Override
public void stateChange(Object value) {
tableData.removeAllItems();
for (TeachingMaterial material : teachingMaterials.get()) {
tableData.addItem(material);
}
}
});
/**
* Enables/disables the edit and delete buttons
*/
materialsTable.addValueChangeListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
TeachingMaterial item = (TeachingMaterial) materialsTable
.getValue();
btnEdit.setEnabled(item != null);
btnDelete.setEnabled(item != null);
}
});
/**
* Opens the popup-window for editing a book and inserts the data from
* the teachingMaterialInfo-State.
*/
btnEdit.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
TeachingMaterial item = (TeachingMaterial) materialsTable
.getValue();
binder.setItemDataSource(item);
UI.getCurrent().addWindow(windowEditTeachingMaterial);
txtTmName.focus();
}
});
/**
* Opens a new popup-window with an empty new teaching material
*/
btnNew.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
TeachingMaterial item = new TeachingMaterial.Builder(null,
null, null, new Date()).build();
binder.setItemDataSource(item);
UI.getCurrent().addWindow(windowEditTeachingMaterial);
txtTmName.focus();
}
});
/**
* Closes the popup window
*
*/
btnWindowCancel.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
windowEditTeachingMaterial.close();
clearWindowFields();
}
});
/**
* Saves the teachingMaterial and closes the popup-window
*
*/
btnWindowSave.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
if (FormFieldsValid()) {
try {
binder.commit();
teachingMaterialViewModel.doUpdateTeachingMaterial(binder
.getItemDataSource().getBean());
windowEditTeachingMaterial.close();
eventBus.post(new MessageEvent(
"Lehrmittel gespeichert."));
} catch (CommitException e) {
eventBus.post(new MessageEvent(e.getLocalizedMessage()));
}
}
}
});
/**
* Show a confirm popup and delete the teaching material on confirmation
*/
btnDelete.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
final TeachingMaterial item = (TeachingMaterial) materialsTable
.getValue();
if (item != null) {
Runnable runnable = new Runnable() {
@Override
public void run() {
teachingMaterialViewModel
.doDeleteTeachingMaterial(item);
materialsTable.select(null);
}
};
eventBus.post(new ConfirmEvent.Builder(
"Wollen Sie das Lehrmittel wirklich löschen?")
.caption("Löschen").confirmRunnable(runnable)
.build());
}
}
});
/**
* Provides the live search of the teaching material table by adding a
* filter after every keypress in the search field. Currently the
* publisher and title search are supported.
*/
filter.addTextChangeListener(new TextChangeListener() {
private static final long serialVersionUID = -1684545652234105334L;
@Override
public void textChange(TextChangeEvent event) {
String text = event.getText();
Filter filter = new Or(new SimpleStringFilter(TABLE_NAME, text, true, false),
new SimpleStringFilter(TABLE_PRODUCER, text, true, false),
new SimpleStringFilter(TABLE_CATEGORY,text,true,false),
new SimpleStringFilter(TABLE_FROMGRADE,text,true,false),
new SimpleStringFilter(TABLE_TOGRADE,text,true,false),
new SimpleStringFilter(TABLE_IDENTNR,text,true,false));
tableData.removeAllContainerFilters();
tableData.addContainerFilter(filter);
}
});
/**
* Allows to dismiss the filter by hitting ESCAPE
*/
filter.addShortcutListener(new ShortcutListener("Clear",
KeyCode.ESCAPE, null) {
@Override
public void handleAction(Object sender, Object target) {
filter.setValue("");
tableData.removeAllContainerFilters();
}
});
/**
* Fills the category combobox
*/
categories.addStateChangeListener(new StateChangeListener() {
@Override
public void stateChange(Object arg0) {
cbCategory.removeAllItems();
for (Category cat : categories.get()) {
cbCategory.addItem(cat);
cbCategory.setItemCaption(cat, cat.getName());
}
}
});
}
/**
* Validates the fields in the edit teaching materials window.
*
* @return Whether or not the fields in the editor are valid
*/
private boolean FormFieldsValid() {
// Validate if a field is empty
if (txtIdentNr.getValue() == null || txtIdentNr.getValue().isEmpty()
|| txtTmName.getValue() == null
|| txtTmName.getValue().isEmpty()
|| cbCategory.getValue() == null
|| dfValidFrom.getValue() == null
|| cbProfiles.getValue() == null) {
eventBus.post(new MessageEvent(
"Bitte füllen Sie alle Pflicht-Felder aus."));
return false;
} else {
// No field is empty, validate now for right values and lengths
if (txtTmName.getValue().length() < 2) {
eventBus.post(new MessageEvent(
"Der Titel muss mindestens 2 Zeichen enthalten."));
return false;
}
try {
if (txtToGrade.getValue() != null)
Integer.parseInt(txtToGrade.getValue());
if (txtFromGrade.getValue() != null)
Integer.parseInt(txtFromGrade.getValue());
} catch (NumberFormatException e) {
eventBus.post(new MessageEvent(
"Die Klassenstufen dürfen nur Zahlen enthalten"));
return false;
}
try {
dfValidFrom.validate();
dfValidUntil.validate();
} catch (InvalidValueException e) {
eventBus.post(new MessageEvent(
"Mindestens ein Datumsfeld ist nicht korrekt."));
return false;
}
return true;
}
}
/**
* Builds the layout by adding all components in their specific order.
*/
private void buildLayout() {
setMargin(true);
setSpacing(true);
setSizeFull();
addComponent(head);
addComponent(materialsTable);
setExpandRatio(materialsTable, 1);
}
/**
* Empties the fields of the popup-window to prevent that TextFields already
* have content form previous edits.
*/
private void clearWindowFields() {
txtTmName.setValue("");
txtIdentNr.setValue("");
txtProducer.setValue("");
txtFromGrade.setValue("");
txtToGrade.setValue("");
textAreaComment.setValue("");
txtProducer.setValue("");
cbFromTerm.setValue(Term.FIRST);
cbToTerm.setValue(Term.SECOND);
}
@Override
public void enter(ViewChangeEvent event) {
teachingMaterialViewModel.refresh();
}
private void bindViewModel(ViewModelComposer viewModelComposer,
Object... viewModels) {
try {
viewModelComposer.bind(this, viewModels);
} catch (IllegalAccessException | NoSuchElementException
| UnsupportedOperationException e) {
e.printStackTrace();
}
}
@Override
public String getTitle() {
return TITLE;
}
}
|
package net.java.sip.communicator.impl.protocol.sip;
import gov.nist.javax.sip.stack.*;
import java.util.*;
import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;
import net.java.sip.communicator.util.*;
/**
* An implementation of the <tt>Router</tt> interface wrapping around JAIN-SIP
* RI <tt>DefaultRouter</tt> in order to be able to change the outbound
* proxy depending on the account which sent the request.
*
* @author Sebastien Mazy
*/
public class ProxyRouter
implements Router
{
/**
* Logger for this class.
*/
private static final Logger logger =
Logger.getLogger(ProxyRouter.class);
/**
* The running JAIN-SIP stack.
*/
private final SipStack stack;
/**
* Used to cache the <tt>DefaultRouter</tt>s. One <tt>DefaultRouter</tt> per
* outbound proxy.
*/
Map<String, Router> routers = new HashMap<String, Router>();
/**
* The jain-sip router to use for accounts that do not have a proxy.
*/
Router defaultRouter = null;
/**
* Simple contructor. Ignores the <tt>defaultRoute</tt> parameter.
*
* @param stack the currently running stack.
* @param defaultRoute ignored parameter.
*/
public ProxyRouter(SipStack stack, String defaultRoute)
{
if(stack == null)
throw new IllegalArgumentException("stack shouldn't be null!");
this.stack = stack;
// we don't care about the provided default route
}
/**
* Returns the next hop for this <tt>Request</tt>.
*
* @param request <tt>Request</tt> to find the next hop.
* @return the next hop for the <tt>request</tt>.
*/
public Hop getNextHop(Request request)
throws SipException
{
logger.debug("Trying to get a router for req: " + request);
Router router =
this.getRouterFor(request);
if(router != null)
return router.getNextHop(request);
logger.warn(
"Hmm we are returning a null router. This doesn't look good",
new Exception());
return null;
}
/**
* Returns the next hops for this <tt>Request</tt>.
*
* @param request <tt>Request</tt> to find the next hops.
* @return the next hops for the <tt>request</tt>.
*/
@Deprecated
public ListIterator getNextHops(Request request)
{
Router router =
this.getRouterFor(request);
if(router != null)
return router.getNextHops(request);
return null;
}
/**
* Returns the outbound proxy for this <tt>Router</tt>.
*
* @return the outbound proxy for this <tt>Router</tt>.
*/
public Hop getOutboundProxy()
{
// we can't tell our outbound proxy without a request
// Emil: we are not quite certain in which cases this method is needed
// so we are logging a stack trace here.
logger.fatal("If you see this then please please describe your SIP "
+"setup and send the following stack trace to"
+"dev@sip-communicator.dev.java.net",
new Exception());
return null;
}
/**
* Creates a DefaultRouter whose default route is the outbound proxy of the
* account which sent the <tt>request</tt>.
*
* @param request the <tt>Request</tt> which to build a <tt>Router</tt> for.
* @return a <tt>Router</tt> with the oubound proxy set for this
* <tt>request</tt>.
*/
private Router getRouterFor(Request request)
{
Address address =
((FromHeader) request.getHeader(FromHeader.NAME)).getAddress();
Set<ProtocolProviderServiceSipImpl> services =
ProtocolProviderServiceSipImpl.getAllInstances();
for(ProtocolProviderServiceSipImpl service : services)
{
if(request.getRequestURI().isSipURI() &&
service.getOurSipAddress((SipURI) request.getRequestURI()).
equals(address))
{
String proxy = service.getOutboundProxyString();
if(proxy == null) // no registrar mode
{
logger.debug("Returning a router for outbound proxy: "
+ service.getOutboundProxyString());
//no proxy for this account, we need to return the default
//router.
if( defaultRouter == null)
defaultRouter = new DefaultRouter(this.stack, null);
return defaultRouter;
}
else if(this.routers.containsKey(proxy))
return this.routers.get(proxy);
else
{
Router router = new DefaultRouter(
this.stack
, service.getOutboundProxyString());
this.routers.put(proxy, router);
logger.debug("Returning a router for outbound proxy: "
+ service.getOutboundProxyString());
return router;
}
}
}
logger.error("couldn't build a router for this request");
return null;
}
}
|
package net.sf.jaer.graphics;
import java.util.Iterator;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GL2ES2;
import com.jogamp.opengl.GL3;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.util.PMVMatrix;
import eu.seebetter.ini.chips.davis.DavisDisplayConfigInterface;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.util.EngineeringFormat;
import com.jogamp.opengl.util.gl2.GLUT;
import eu.seebetter.ini.chips.DavisChip;
import eu.seebetter.ini.chips.davis.imu.IMUSample;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Scanner;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.aemonitor.AEConstants;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.graphics.ChipCanvas.ClipArea;
@Description("Displays events in space time using a rolling view where old events are\n"
+ " * erased and new ones are added to the front.")
@DevelopmentStatus(DevelopmentStatus.Status.InDevelopment)
public class SpaceTimeRollingEventDisplayMethod extends DisplayMethod implements DisplayMethod3D {
EngineeringFormat engFmt = new EngineeringFormat();
private DavisDisplayConfigInterface config;
private boolean displayEvents = true;
private boolean displayFrames = true;
boolean spikeListCreated = false;
private GLUT glut = null;
private GLU glu = null;
private boolean shadersInstalled = false;
private int shaderprogram;
private int vertexShader;
private int fragmentShader;
private int vao;
private int vbo;
final int v_vert = 0;
private int BUF_INITIAL_SIZE_EVENTS = 20000;
private int BUF_SIZE_INCREMENT_FACTOR = 2;
ByteBuffer eventVertexBuffer;
int sx, sy, smax;
float tfac;
private int timeSlice = 0;
private FloatBuffer mv = FloatBuffer.allocate(16);
private FloatBuffer proj = FloatBuffer.allocate(16);
private int idMv, idProj, idt0, idt1;
private ArrayList<BasicEvent> eventList = new ArrayList(BUF_INITIAL_SIZE_EVENTS), eventListTmp = new ArrayList(BUF_INITIAL_SIZE_EVENTS);
private int timeWindowUs = 100000, t0;
private static int EVENT_SIZE_BYTES = (Float.SIZE / 8) * 3;// size of event in shader ByteBuffer
private int axesDisplayListId = -1;
private boolean regenerateAxesDisplayList = true;
private int aspectRatio = 4; // depth of 3d cube compared to max of x and y chip dimension
/**
* Creates a new instance of SpaceTimeEventDisplayMethod
*/
public SpaceTimeRollingEventDisplayMethod(final ChipCanvas chipCanvas) {
super(chipCanvas);
this.eventVertexBuffer = ByteBuffer.allocateDirect(BUF_INITIAL_SIZE_EVENTS * EVENT_SIZE_BYTES);
eventVertexBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
private void installShaders(GL2 gl) throws IOException {
if (shadersInstalled) {
return;
}
gl.glEnable(GL3.GL_PROGRAM_POINT_SIZE);
shadersInstalled = true;
IntBuffer b = IntBuffer.allocate(8); // buffer to hold return values
shaderprogram = gl.glCreateProgram();
vertexShader = gl.glCreateShader(GL2ES2.GL_VERTEX_SHADER);
fragmentShader = gl.glCreateShader(GL2ES2.GL_FRAGMENT_SHADER);
checkGLError(gl, "creating shaders and shader program");
String vsrc = readFromStream(SpaceTimeRollingEventDisplayMethod.class
.getResourceAsStream("SpaceTimeRollingEventDisplayMethod_Vertex.glsl"));
gl.glShaderSource(vertexShader, 1, new String[]{vsrc}, (int[]) null, 0);
gl.glCompileShader(vertexShader);
b.clear();
gl.glGetShaderiv(vertexShader, GL2ES2.GL_COMPILE_STATUS, b);
if (b.get(0) != GL.GL_TRUE) {
log.warning("error compiling vertex shader");
printShaderLog(gl);
}
checkGLError(gl, "compiling vertex shader");
String fsrc = readFromStream(SpaceTimeRollingEventDisplayMethod.class
.getResourceAsStream("SpaceTimeRollingEventDisplayMethod_Fragment.glsl"));
gl.glShaderSource(fragmentShader, 1, new String[]{fsrc}, (int[]) null, 0);
gl.glCompileShader(fragmentShader);
b.clear();
gl.glGetShaderiv(fragmentShader, GL2ES2.GL_COMPILE_STATUS, b);
if (b.get(0) != GL.GL_TRUE) {
log.warning("error compiling fragment shader");
printShaderLog(gl);
}
checkGLError(gl, "compiling fragment shader");
gl.glAttachShader(shaderprogram, vertexShader);
gl.glAttachShader(shaderprogram, fragmentShader);
gl.glLinkProgram(shaderprogram);
b.clear();
// gl.glGetShaderiv(shaderprogram, GL2ES2.GL_COMPILE_STATUS, b);
// if (b.get(0) != GL.GL_TRUE) {
// log.warning("error linking shader program");
// printShaderLog(gl);
checkGLError(gl, "linking shader program");
b.clear();
gl.glGenVertexArrays(1, b);
vao = b.get(0);
gl.glBindVertexArray(vao);
b.clear();
gl.glGenBuffers(1, b);
vbo = b.get(0);
checkGLError(gl, "setting up vertex array and vertex buffer");
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo);
// gl.glBindAttribLocation(shaderprogram, polarity_vert, "polarity"); // symbolic names in vertex and fragment shaders
gl.glBindAttribLocation(shaderprogram, v_vert, "v");
// gl.glBindAttribLocation(shaderprogram, polarity_frag, "frag_polarity");
checkGLError(gl, "binding shader attributes");
gl.glVertexAttribPointer(v_vert, 3, GL.GL_FLOAT, false, EVENT_SIZE_BYTES, 0);
// gl.glVertexAttribPointer(polarity_vert, 1, GL.GL_FLOAT, false, EVENT_SIZE_BYTES, 3);
checkGLError(gl, "setting vertex attribute pointers");
idMv = gl.glGetUniformLocation(shaderprogram, "mv");
idProj = gl.glGetUniformLocation(shaderprogram, "proj");
idt0 = gl.glGetUniformLocation(shaderprogram, "t0");
idt1 = gl.glGetUniformLocation(shaderprogram, "t1");
if (idMv < 0 || idProj < 0 || idt0 < 0 || idt1 < 0) {
throw new RuntimeException("cannot locate uniform variable idMv, idProj, idt0 or idt1 in shader program");
}
checkGLError(gl, "getting IDs for uniform modelview and projection matrices in shaders");
}
private void checkEventBufferAllocation(int sizeEvents) {
if (eventVertexBuffer.capacity() <= sizeEvents * EVENT_SIZE_BYTES) {
eventVertexBuffer = ByteBuffer.allocateDirect(eventList.size() * EVENT_SIZE_BYTES);
eventVertexBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
}
@Override
public void display(final GLAutoDrawable drawable) {
if (!(chip instanceof AEChip)) {
throw new RuntimeException("Can only render AEChip outputs: chip=" + chip);
}
final AEChip chip = (AEChip) getChipCanvas().getChip();
if (glut == null) {
glut = new GLUT();
}
final GL2 gl = drawable.getGL().getGL2();
if (gl == null) {
log.warning("null GL context - not displaying");
return;
}
try {
installShaders(gl);
} catch (IOException ex) {
log.warning("could not load shaders: " + ex.toString());
return;
}
// render events
final EventPacket packet = (EventPacket) chip.getLastData();
if (packet == null) {
log.warning("null packet to render");
return;
}
final int n = packet.getSize();
if (n == 0) {
return;
}
final int t0ThisPacket = packet.getFirstTimestamp();
final int t1 = packet.getLastTimestamp();
// final int dtThisPacket = t1 - t0ThisPacket + 1;
// the time that is displayed in rolling window is some multiple of either current frame duration (for live playback) or timeslice (for recorded playback)
int colorScale = getRenderer().getColorScale(); // use color scale to determine multiple, up and down arrows set it then
int newTimeWindowUs;
if (chip.getAeViewer().getPlayMode() == AEViewer.PlayMode.LIVE) {
int frameDurationUs = (int) (1e6f / chip.getAeViewer().getFrameRater().getDesiredFPS());
newTimeWindowUs = frameDurationUs * (1 << colorScale);
} else if (chip.getAeViewer().getPlayMode() == AEViewer.PlayMode.PLAYBACK) {
newTimeWindowUs = chip.getAeViewer().getAePlayer().getTimesliceUs() * (1 << colorScale);
} else {
newTimeWindowUs = 100000;
}
if (newTimeWindowUs != timeWindowUs) {
regenerateAxesDisplayList = true;
}
timeWindowUs = newTimeWindowUs;
t0 = t1 - timeWindowUs;
pruneOldEvents(t0);
sx = chip.getSizeX();
sy = chip.getSizeY();
smax = chip.getMaxSize();
tfac = (float) (smax * aspectRatio) / timeWindowUs;
addEventsToEventList(packet);
checkEventBufferAllocation(eventList.size());
eventVertexBuffer.clear();// TODO should not really clear, rather should erase old events
for (BasicEvent ev : eventList) {
eventVertexBuffer.putFloat(ev.x);
eventVertexBuffer.putFloat(ev.y);
eventVertexBuffer.putFloat(tfac * (ev.timestamp - t1)); // negative z
}
eventVertexBuffer.flip();
checkGLError(gl, "set uniform t0 and t1");
renderEvents(gl, drawable, eventVertexBuffer, eventList.size(), 1e-6f * timeWindowUs, smax * aspectRatio);
}
private void addEventsToEventList(final EventPacket<BasicEvent> packet) {
for (BasicEvent e : packet) {
// BasicEvent e = (BasicEvent) o;
if (e.isSpecial() || e.isFilteredOut()) {
continue;
}
BasicEvent ne = new BasicEvent();
ne.copyFrom(e);
eventList.add(ne); // must do this unfortunately because otherwise the original event object in this list will be reused for a later packet
}
}
private void pruneOldEvents(final int startTimeUs) {
eventListTmp.clear();
for (BasicEvent ev : eventList) {
if (ev.timestamp >= startTimeUs) {
eventListTmp.add(ev);
}
}
eventList.clear();
eventList.addAll(eventListTmp);
}
void renderEvents(GL2 gl, GLAutoDrawable drawable, ByteBuffer b, int nEvents, float dtS, float zmax) {
gl.glClearColor(0, 0, 0, 0);
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
// axes
gl.glColor3f(0, 0, 1);
gl.glLineWidth(1f);
if (glu == null) {
glu = new GLU();
}
if (regenerateAxesDisplayList) {
regenerateAxesDisplayList = false;
if (axesDisplayListId > 0) {
gl.glDeleteLists(axesDisplayListId, 1);
}
axesDisplayListId = gl.glGenLists(1);
gl.glNewList(axesDisplayListId, GL2.GL_COMPILE);
// gl.glTranslatef(0, 0, -timeWindowUs);
// glu.gluLookAt(0, 0, 0,
// 0, 0, -1,
// 0, 1, 0);
// gl.glTranslatef(-sx,0,0);
// gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
// gl.glPushMatrix();
// axes
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(0, 0, 0);
gl.glVertex3f(sx, 0, 0);
gl.glVertex3f(0, 0, 0);
gl.glVertex3f(0, sy, 0);
gl.glVertex3f(sx, 0, 0);
gl.glVertex3f(sx, sy, 0);
gl.glVertex3f(sx, sy, 0);
gl.glVertex3f(0, sy, 0);
gl.glVertex3f(0, 0, 0);
gl.glVertex3f(0, 0, -zmax);
gl.glVertex3f(sx, 0, 0);
gl.glVertex3f(sx, 0, -zmax);
gl.glVertex3f(0, sy, 0);
gl.glVertex3f(0, sy, -zmax);
gl.glVertex3f(sx, sy, 0);
gl.glVertex3f(sx, sy, -zmax);
gl.glVertex3f(0, 0, -zmax);
gl.glVertex3f(sx, 0, -zmax);
gl.glVertex3f(0, 0, -zmax);
gl.glVertex3f(0, sy, -zmax);
gl.glVertex3f(sx, 0, -zmax);
gl.glVertex3f(sx, sy, -zmax);
gl.glVertex3f(sx, sy, -zmax);
gl.glVertex3f(0, sy, -zmax);
gl.glEnd();
final int font = GLUT.BITMAP_TIMES_ROMAN_24;
final int FS = 1; // distance in pixels of text from endZoom of axis
gl.glRasterPos3f(sx, 0, 0);
glut.glutBitmapString(font, "x=" + sx);
gl.glRasterPos3f(0, sy, 0);
glut.glutBitmapString(font, "y=" + sy);
gl.glRasterPos3f(0, 0, -zmax);
glut.glutBitmapString(font, "t=" + engFmt.format(-dtS) + "s");
gl.glRasterPos3f(0, 0, 0);
glut.glutBitmapString(font, "t=0");
checkGLError(gl, "drawing axes labels");
gl.glEndList();
}
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
gl.glLoadIdentity();
// gl.glPushMatrix();
ClipArea clip = getChipCanvas().getClipArea();
// gl.glRotatef(15, 1, 1, 0); // rotate viewpoint by angle deg around the y axis
gl.glOrtho(clip.left, clip.right, clip.bottom, clip.top, -zmax * 4, zmax * 4);
gl.glRotatef(getChipCanvas().getAngley(), 0, 1, 0); // rotate viewpoint by angle deg around the y axis
gl.glRotatef(getChipCanvas().getAnglex(), 1, 0, 0); // rotate viewpoint by angle deg around the x axis
gl.glTranslatef(getChipCanvas().getOrigin3dx(), getChipCanvas().getOrigin3dy(), 0);
// gl.glTranslatef(sx/2, sy/2, zmax);
// glu.gluPerspective(33, (float)drawable.getSurfaceWidth()/drawable.getSurfaceHeight(), .1, zmax*9);
// gl.glTranslatef(-sx/2, -sy/2, -zmax);
// glu.gluPerspective(30, (float)sx/sy, .1, timeWindowUs*1.1f);
// gl.glFrustumf(clip.left, clip.right, clip.bottom, clip.top, .1f, timeWindowUs*20);
// gl.glFrustumf(0,sx, 0, sy, .1f, timeWindowUs*20);
// gl.glFrustumf(clip.left, clip.right, clip.bottom, clip.top, .1f, timeWindowUs * 10);
// gl.glTranslatef(sx, sy, 1);
checkGLError(gl, "setting projection");
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, 0);
// gl.glScalef(1, 1, 1);
gl.glCallList(axesDisplayListId);
// getChipCanvas().setDefaultProjection(gl, drawable);
// draw points using shaders
gl.glUseProgram(shaderprogram);
gl.glValidateProgram(shaderprogram);
// pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
// pmvMatrix.glLoadIdentity();
// pmvMatrix.glOrthof(-10, sx / zoom + 10, -10, sy / zoom + 10, 10, -10); // clip area has same aspect ratio as screen!
// pmvMatrix.glRotatef(getChipCanvas().getAngley(), 0, 1, 0); // rotate viewpoint by angle deg around the y axis
// pmvMatrix.glRotatef(getChipCanvas().getAnglex(), 1, 0, 0); // rotate viewpoint by angle deg around the x axis
// pmvMatrix.glTranslatef(getChipCanvas().getOrigin3dx(), getChipCanvas().getOrigin3dy(), 0);
// pmvMatrix.glGetFloatv(GL2.GL_PROJECTION_MATRIX, proj);
// pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
// pmvMatrix.glLoadIdentity();
// pmvMatrix.glGetFloatv(GL2.GL_MODELVIEW_MATRIX, mv);
// checkGLError(gl, "using shader program");
gl.glGetFloatv(GL2.GL_PROJECTION_MATRIX, proj);
// gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
// gl.glLoadIdentity();
gl.glGetFloatv(GL2.GL_MODELVIEW_MATRIX, mv);
gl.glUniformMatrix4fv(idMv, 1, false, mv);
gl.glUniformMatrix4fv(idProj, 1, false, proj);
checkGLError(gl, "setting model/view matrix");
gl.glUniform1f(idt0, (float) -zmax);
gl.glUniform1f(idt1, (float) 0);
checkGLError(gl, "setting t0 or t1 for buffer");
gl.glBindVertexArray(vao);
// gl.glEnableVertexAttribArray(polarity_vert);
gl.glEnableVertexAttribArray(v_vert);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo);
gl.glBufferData(GL.GL_ARRAY_BUFFER, b.limit(), b, GL2ES2.GL_STREAM_DRAW);
checkGLError(gl, "binding vertex buffers");
// gl.glEnable(GL.GL_DEPTH_TEST);
// gl.glDepthMask(true);
// gl.glEnable(GL.GL_BLEND);
// gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE);
// gl.glBlendEquation(GL.GL_FUNC_ADD);
// checkGLError(gl, "setting blend function");
// draw
gl.glDrawArrays(GL.GL_POINTS, 0, nEvents);
checkGLError(gl, "drawArrays");
gl.glUseProgram(0);
checkGLError(gl, "disable program");
// gl.glPopMatrix(); // pop out so that shader uses matrix without applying it twice
// gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
// gl.glPopMatrix(); // pop out so that shader uses matrix without applying it twice
// gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
// re-enable depth sorting for everything else
// gl.glDepthMask(true);
}
boolean checkGLError(final GL2 gl, String msg) {
boolean r = false;
int error = gl.glGetError();
int nerrors = 10;
while ((error != GL.GL_NO_ERROR) && (nerrors
if (glu == null) {
glu = new GLU();
}
StackTraceElement[] st = Thread.currentThread().getStackTrace();
log.warning("GL error number " + error + " " + glu.gluErrorString(error) + "\n");
new RuntimeException("GL error number " + error + " " + glu.gluErrorString(error)).printStackTrace();
error = gl.glGetError();
r = true;
}
return r;
}
private void printShaderLog(GL2 gl) {
IntBuffer b = IntBuffer.allocate(8);
gl.glGetProgramiv(shaderprogram, GL2ES2.GL_INFO_LOG_LENGTH, b);
int logLength = b.get(0);
ByteBuffer bb = ByteBuffer.allocate(logLength);
b.clear();
gl.glGetProgramInfoLog(shaderprogram, logLength, b, bb);
String v = new String(bb.array(), java.nio.charset.StandardCharsets.UTF_8);
log.info(v);
}
private String readFromStream(InputStream ins) throws IOException {
if (ins == null) {
throw new IOException("Could not read from stream.");
}
StringBuffer buffer = new StringBuffer();
Scanner scanner = new Scanner(ins);
try {
while (scanner.hasNextLine()) {
buffer.append(scanner.nextLine() + "\n");
}
} finally {
scanner.close();
}
return buffer.toString();
}
}
|
package com.esuta.fidm.model;
import com.esuta.fidm.infra.exception.DatabaseCommunicationException;
import com.esuta.fidm.infra.exception.ObjectAlreadyExistsException;
import com.esuta.fidm.infra.exception.ObjectNotFoundException;
import com.esuta.fidm.model.util.IProvisioningService;
import com.esuta.fidm.model.util.JsonUtil;
import com.esuta.fidm.repository.schema.core.*;
import com.esuta.fidm.repository.schema.support.AttributeModificationType;
import com.esuta.fidm.repository.schema.support.ObjectModificationType;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This service serves as a simple provisioning engine that takes care about change
* processing. It works with a list of modifications that are provided by other services
* (this list should already be filtered by sharing policies since this will not be
* done here) that are processed and applied based on provisioning rules defined
* for an org. unit.
*
* @author shood
* */
public class ProvisioningService implements IProvisioningService{
private static final Logger LOGGER = Logger.getLogger(ProvisioningService.class);
/**
* Single ObjectChangeProcessor instance
* */
private static ProvisioningService instance = null;
/**
* Change processor instance - applies changes on org. units after provisioning
* policy is applied
* */
private ObjectChangeProcessor changeProcessor;
/**
* Model service instance for all kinds of support operations
* */
private IModelService modelService;
/**
* A special map of changes for individual org. units (represented by uid of org. unit).
* This list is populated with modifications (multi-value attribute modifications in
* most cases) that are evaluated when certain actions are triggered - these are the actions,
* which processing may be affected by the change in this list - e.g. user trying to access
* a relying party.
* */
private Map<String, List<AttributeModificationType>> jitModificationList = new HashMap<>();
private ProvisioningService(){
changeProcessor = ObjectChangeProcessor.getInstance();
modelService = ModelService.getInstance();
}
public static ProvisioningService getInstance(){
if(instance == null){
instance = new ProvisioningService();
}
return instance;
}
/**
* Applies provisioning policy on a set of rules on a certain org. unit. These rules are processed
* based on provisioning policy of org. unit and specific provisioning rules defined for attributes
* that are changes. There are basically 3 scenarios for changes:
* * A change is processed immediately, if PRO-ACTIVE provisioning rule is specified
* * A change is added to jitModificationList and checked every-time when actions requiring
* change processing are triggered if JUST-IN-TIME provisioning rule is defined
* * A special task is created for CONSTANT provisioning changes - this task will be
* performed when the time specified in provisioning rule is met
* */
public void applyProvisioningPolicy(OrgType org, List<AttributeModificationType> modifications)
throws DatabaseCommunicationException, ObjectNotFoundException, NoSuchFieldException, IllegalAccessException {
if(org == null || modifications == null || modifications.isEmpty()){
return;
}
FederationProvisioningPolicyType policy = modelService.readObject(FederationProvisioningPolicyType.class,
org.getProvisioningPolicy().getUid());
if(policy == null){
return;
}
for(AttributeModificationType modification: modifications){
FederationProvisioningRuleType rule = findRuleForModification(modification, policy);
List<AttributeModificationType> constantUpdateModifications = new ArrayList<>();
if(rule == null){
//Apply default provisioning behavior
switch (policy.getDefaultRule()){
case PRO_ACTIVE:
changeProcessor.applyModificationsOnOrg(org, wrapModification(modification));
recomputeInducementsIfNeeded(org, modification);
break;
case JUST_IN_TIME:
changeProcessor.applyModificationsOnOrg(org, wrapModification(modification));
insertChangeIntoJitModificationList(org.getUid(), modification);
break;
case CONSTANT:
constantUpdateModifications.add(modification);
break;
default:
LOGGER.error("Invalid provisioning behavior type encountered. Processing not completed correctly.");
}
} else {
//Find out, if there is a specific rule for this modification and act accordingly
switch (rule.getProvisioningType()){
case PRO_ACTIVE:
changeProcessor.applyModificationsOnOrg(org, wrapModification(modification));
recomputeInducementsIfNeeded(org, modification);
break;
case JUST_IN_TIME:
changeProcessor.applyModificationsOnOrg(org, wrapModification(modification));
insertChangeIntoJitModificationList(org.getUid(), modification);
break;
case CONSTANT:
constantUpdateModifications.add(modification);
break;
default:
LOGGER.error("Invalid provisioning behavior type encountered. Processing not completed correctly.");
}
}
if(!constantUpdateModifications.isEmpty()){
createConstantProvisioningUpdateTask(org, constantUpdateModifications, policy);
}
OrgType oldOrg = modelService.readObject(OrgType.class, org.getUid());
//And finally, save the changes, if there is anything to save at the moment
if(!oldOrg.equals(org)){
modelService.updateObject(org);
}
}
}
/**
* This method will check the existing list with just-in-time provisioning changes and will apply
* (if there are any) modifications for the user that triggered the action.
* */
public void checkJitProvisioningList(UserType user, ResourceType resource){
if(user == null){
LOGGER.debug("Can't apply any changes on non-existing user");
return;
}
for(AssignmentType orgRef: user.getOrgUnitAssignments()){
if(jitModificationList.containsKey(orgRef.getUid())){
List<AttributeModificationType> modifications = jitModificationList.get(orgRef.getUid());
for(AttributeModificationType modification: modifications){
if(modification.getAttribute().equals("resourceInducements")){
ObjectReferenceType newResourceRef = (ObjectReferenceType)JsonUtil
.jsonToObject(modification.getNewValue(), ObjectReferenceType.class);
ObjectReferenceType oldResourceRef = (ObjectReferenceType)JsonUtil
.jsonToObject(modification.getOldValue(), ObjectReferenceType.class);
switch (modification.getModificationType()){
case ADD:
addAccountToUser(user, newResourceRef);
break;
case MODIFY:
removeAccountFromUser(user, oldResourceRef);
addAccountToUser(user, newResourceRef);
break;
case DELETE:
removeAccountFromUser(user, oldResourceRef);
break;
default:
LOGGER.error("Invalid modification type. Could not process Just-In-Time provisioning modification.");
break;
}
} else if (modification.getAttribute().equals("roleInducements")){
ObjectReferenceType newRoleRef = (ObjectReferenceType)JsonUtil
.jsonToObject(modification.getNewValue(), ObjectReferenceType.class);
ObjectReferenceType oldRoleRef = (ObjectReferenceType)JsonUtil
.jsonToObject(modification.getOldValue(), ObjectReferenceType.class);
switch (modification.getModificationType()) {
case ADD:
addRoleToUser(user, newRoleRef);
break;
case MODIFY:
removeRoleFromUser(user, oldRoleRef);
addRoleToUser(user, newRoleRef);
break;
case DELETE:
removeRoleFromUser(user, oldRoleRef);
break;
default:
LOGGER.error("Invalid modification type. Could not process Just-In-Time provisioning modification.");
break;
}
}
}
//Save user, if there were any changes
}
}
}
/**
* This method performs an evaluation of all modifications in just-in-time provisioning list
* and throws away the modifications that have been applied for all possible situations -
* there is no reason to store these changes anymore since it causes unwanted processing.
* This should be performed once upon a time (periodicity depends on the rate of modification
* generation) and should be preferably performed at night - or any other time when system is
* not highly used.
* */
public void cleanJitProvisioningList(){
//TODO
}
/**
* Creates a special task according to configured times options for changes contained
* in provided list. It also groups changes according to attributes and may create
* multiple tasks according to time options set in specific provisioning rules.
* */
public void createConstantProvisioningUpdateTask(OrgType org, List<AttributeModificationType> modifications, FederationProvisioningPolicyType policy){
//TODO
}
/**
* Simply adds a new role reference to the user, if it already does not exist
* */
private void addRoleToUser(UserType user, ObjectReferenceType roleReference){
if(user == null || roleReference == null){
return;
}
//Check, if role assignment already exists for this user
for(AssignmentType roleAssignment: user.getRoleAssignments()){
if(roleAssignment.getUid().equals(roleReference.getUid())){
LOGGER.debug("Could not add role assignment with uid: " + roleReference.getUid()
+ ". Such assignment already exists");
return;
}
}
//Create new role assignment
AssignmentType roleAssignment = new AssignmentType(roleReference.getUid());
roleAssignment.setAssignedByInducement(true);
user.getRoleAssignments().add(roleAssignment);
LOGGER.debug("New role assignment added to role: " + roleReference.getUid());
}
/**
* Simply removes a role assignment, if such assignment exists.
* */
private void removeRoleFromUser(UserType user, ObjectReferenceType roleReference){
if(user == null || roleReference == null){
return;
}
AssignmentType assignmentToRemove = null;
for(AssignmentType roleAssignment: user.getRoleAssignments()){
if(roleAssignment.getUid().equals(roleReference.getUid())){
assignmentToRemove = roleAssignment;
}
}
if(assignmentToRemove != null && assignmentToRemove.isAssignedByInducement()){
user.getRoleAssignments().remove(assignmentToRemove);
LOGGER.debug("Removing role assignment to role: " + assignmentToRemove.getUid());
return;
}
LOGGER.debug("Could not remove role assignment. Assignment to role with uid: "
+ roleReference.getUid() + " does not exists.");
}
/**
* Adds an account to the user, if account on such resource does not exist
* */
private void addAccountToUser(UserType user, ObjectReferenceType resourceReference){
if(user == null || resourceReference == null){
return;
}
//Check, if user has an account on provided resource and add it, if not
try {
for(AssignmentType accountAssignment: user.getAccounts()){
AccountType account = modelService.readObject(AccountType.class, accountAssignment.getUid());
if(account != null && resourceReference.getUid().equals(account.getResource().getUid())){
//Account exists, log this information and return to provisioning processing without
//new account addition
LOGGER.debug("Account not added. Account on provided resource already exists.");
return;
}
}
AccountType account = new AccountType();
account.setOwner(new ObjectReferenceType(user.getUid()));
account.setResource(new ObjectReferenceType(resourceReference.getUid()));
account = modelService.createObject(account);
AssignmentType assignment = new AssignmentType(account.getUid());
assignment.setAssignedByInducement(true);
user.getAccounts().add(assignment);
LOGGER.debug("Creating new user account: " + assignment.getUid());
} catch (DatabaseCommunicationException | ObjectAlreadyExistsException e) {
LOGGER.error("Could not create new account. Reason: ", e);
}
}
/**
* Removes an account from user, if it exists
* */
private void removeAccountFromUser(UserType user, ObjectReferenceType resourceReference){
if(user == null || resourceReference == null){
return;
}
//Check, if user has an account that is to be removed and remove it, if it exists
AssignmentType accountToRemove = null;
try {
for(AssignmentType accountAssignment: user.getAccounts()){
AccountType account = modelService.readObject(AccountType.class, accountAssignment.getUid());
if(account != null && resourceReference.getUid().equals(account.getResource().getUid())){
accountToRemove = accountAssignment;
modelService.deleteObject(account);
break;
}
}
if (accountToRemove != null && accountToRemove.isAssignedByInducement()){
user.getAccounts().remove(accountToRemove);
LOGGER.debug("Removing user account with uid: " + accountToRemove.getUid());
}
} catch (DatabaseCommunicationException | ObjectNotFoundException e) {
LOGGER.error("Could not remove an account from the user. Reason: ", e);
}
}
/**
* Recomputes inducements of users of selected org. unit using inducement processor instance.
* Adds accounts, if needed
* */
private void recomputeInducementsIfNeeded(OrgType org, AttributeModificationType modification)
throws DatabaseCommunicationException, ObjectNotFoundException {
if(modification.getAttribute().equals("resourceInducements") || modification.getAttribute().equals("roleInducements")) {
modelService.updateObject(org);
modelService.recomputeOrganizationalUnit(org);
}
}
private FederationProvisioningRuleType findRuleForModification(AttributeModificationType modification, FederationProvisioningPolicyType policy){
String attributeName = modification.getAttribute();
ModificationType modificationType = modification.getModificationType();
for(FederationProvisioningRuleType rule: policy.getRules()){
if(attributeName.equals(rule.getAttributeName()) && modificationType.equals(rule.getModificationType())){
return rule;
}
}
return null;
}
private ObjectModificationType wrapModification(AttributeModificationType modification){
ObjectModificationType modificationObject = new ObjectModificationType();
modificationObject.getModificationList().add(modification);
return modificationObject;
}
private void insertChangeIntoJitModificationList(String uid, AttributeModificationType modification){
if(jitModificationList.containsKey(uid)){
jitModificationList.get(uid).add(modification);
} else {
List<AttributeModificationType> modificationList = new ArrayList<>();
modificationList.add(modification);
jitModificationList.put(uid, modificationList);
}
}
}
|
//CHECKSTYLE:OFF
package org.efaps.esjp.ci;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsNoUpdate;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.ci.CIMsgPhrase;
/**
* This class is only used in case that the HumanResource App is not installed
* to be able to compile the classes.
* @author The eFaps Team
*/
@EFapsUUID("e8633952-4b53-4000-a66c-2ee62e99966e")
@EFapsApplication("eFapsApp-Sales")
@EFapsNoUpdate
public final class CIMsgHumanResource
{
public static final _EmployeeWithNumberMsgPhrase EmployeeWithNumberMsgPhrase = new _EmployeeWithNumberMsgPhrase("c6686d34-f9d7-4bf4-b9f1-80dad440eac4");
public static class _EmployeeWithNumberMsgPhrase extends CIMsgPhrase
{
protected _EmployeeWithNumberMsgPhrase(final String _uuid)
{
super(_uuid);
}
}
}
|
package de.mxro.maven.tools;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import de.mxro.process.Spawn;
public class MavenRemoteRepository {
/**
* <p>
* Downloads the <code>maven-metadata.xml</code> from a remote repository.
*
* @param repositoryUrl
* @param destFolder
* @param groupId
* @param artifactId
* @return true if xml file could be downloaded, false otherwise.
* @throws IOException
*/
public static boolean downloadRepositoryXml(final String repositoryUrl, final Path destFolder,
final String groupId, final String artifactId) throws IOException {
if (Files.exists(destFolder.resolve("maven-metadata.xml"))) {
throw new RuntimeException("maven-metadata.xml file already existed in folder: " + destFolder);
}
final String path = repositoryUrl + groupId.replaceAll("\\.", "/") + "/" + artifactId + "/maven-metadata.xml";
final String output = Spawn.runBashCommand("wget " + path, destFolder.toFile());
if (output.contains("ERROR 404") || output.contains("Not Found")) {
return false;
}
if (output.contains("ERROR")) {
System.out.println(output);
throw new RuntimeException("Error while downloading repository index file from: " + path);
}
return true;
}
public static void createRepository(final String repositoryUrl, final Path destFolder, final String groupId,
final String artifactId) throws IOException {
final Path file = Files.createFile(destFolder.resolve("maven-metadata.xml"));
String xml = "";
xml += "<metadata>\n";
xml += " <groupId>" + groupId + "</groupId>\n";
xml += " <artifactId>" + artifactId + "</artifactId>\n";
xml += " <versioning>\n";
xml += " <release>0.0.0</release>\n";
xml += " <versions>\n";
xml += " </versions>\n";
xml += " <lastUpdated>00000</lastUpdated>\n";
xml += " </versioning>\n";
xml += "</metadata>";
Files.write(file, xml.getBytes("UTF-8"));
}
public static void assertVersionInRepositoryXml(final Path destFolder, final String newVersion) throws Exception {
final Path mavenMetadata = destFolder.resolve("maven-metadata.xml");
final byte[] mavenMetadataBytes = Files.readAllBytes(mavenMetadata);
String mavenMetadataString = new String(mavenMetadataBytes, "UTF-8");
if (!mavenMetadataString.contains(newVersion)) {
final int versionsEndTagIndex = mavenMetadataString.indexOf("</versions>");
mavenMetadataString = mavenMetadataString.substring(0, versionsEndTagIndex) + "\n <version>"
+ newVersion + "</version>\n" + mavenMetadataString.substring(versionsEndTagIndex);
}
final String lastChanged = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
mavenMetadataString = mavenMetadataString.replaceAll("<lastUpdated>[^<]*</lastUpdated>", "<lastUpdated>"
+ lastChanged + "</lastUpdated>");
mavenMetadataString = mavenMetadataString.replaceAll("<release>[^<]*</release>", "<release>" + newVersion
+ "</release>");
Files.write(mavenMetadata, mavenMetadataString.getBytes("UTF-8"));
}
}
|
package org.appwork.swing.components.searchcombo;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.ComboBoxEditor;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.ComboPopup;
import org.appwork.app.gui.MigPanel;
import org.appwork.scheduler.SingleSchedule;
import org.appwork.utils.logging.Log;
import org.appwork.utils.swing.EDTRunner;
/**
* this component extends a normal combobox and implements a editable
* filter/autocompletion feature. <b> make sure that you model is sorted</b>
*
* @author thomas
*
* @param <T>
*/
public abstract class SearchComboBox<T> extends JComboBox {
class Editor implements ComboBoxEditor {
private final JTextField tf;
private final MigPanel panel;
private final JLabel icon;
private T value;
private final SingleSchedule sheduler;
private final Color defaultForeground;
private boolean setting;
public Editor() {
this.tf = new JTextField();
this.icon = new JLabel();
// editor panel
this.panel = new MigPanel("ins 0", "[][grow,fill]", "[grow,fill]");
this.panel.add(this.icon);
this.panel.setOpaque(true);
this.panel.setBackground(this.tf.getBackground());
this.tf.setBackground(null);
this.tf.setOpaque(false);
this.tf.putClientProperty("Synthetica.opaque", Boolean.FALSE);
this.defaultForeground = this.tf.getForeground();
this.panel.add(this.tf);
this.sheduler = new SingleSchedule(50);
// this.panel.setBorder(this.tf.getBorder());
this.tf.setBorder(null);
this.tf.addFocusListener(new FocusListener() {
@Override
public void focusGained(final FocusEvent e) {
Editor.this.tf.selectAll();
}
@Override
public void focusLost(final FocusEvent e) {
if (!Editor.this.autoComplete(false)) {
Editor.this.tf.setText(Editor.this.value == null ? "" : SearchComboBox.this.getText(Editor.this.value));
Editor.this.autoComplete(false);
}
}
});
this.tf.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(final DocumentEvent e) {
Editor.this.auto();
}
@Override
public void insertUpdate(final DocumentEvent e) {
Editor.this.auto();
}
@Override
public void removeUpdate(final DocumentEvent e) {
// this would avoid usuage of backspace
// Editor.this.auto();
}
});
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxEditor#addActionListener(java.awt.event.
* ActionListener)
*/
@Override
public void addActionListener(final ActionListener l) {
this.tf.addActionListener(l);
}
private void auto() {
if (this.setting) { return; }
// scheduler executes at least 50 ms after this submit.
this.sheduler.submit(new Runnable() {
@Override
public void run() {
Editor.this.autoComplete(true);
}
});
}
/**
* finds all possible matches of the entered text and sets the selected
* object
*/
protected boolean autoComplete(final boolean showPopup) {
final String txt = Editor.this.tf.getText();
if (this.value != null && SearchComboBox.this.getText(this.value).equals(txt)) { return true; }
String text = null;
final ArrayList<T> found = new ArrayList<T>();
for (int i = 0; i < SearchComboBox.this.getModel().getSize(); i++) {
text = SearchComboBox.this.getText((T) SearchComboBox.this.getModel().getElementAt(i));
if (text != null && text.startsWith(txt)) {
found.add((T) SearchComboBox.this.getModel().getElementAt(i));
}
}
new EDTRunner() {
@Override
protected void runInEDT() {
final int pos = Editor.this.tf.getCaretPosition();
if (found.size() == 0) {
Editor.this.tf.setForeground(SearchComboBox.this.getForegroundBad());
SearchComboBox.this.hidePopup();
} else {
Editor.this.tf.setForeground(Editor.this.defaultForeground);
// Editor.this.setItem(found.get(0));
SearchComboBox.this.setSelectedItem(found.get(0));
Editor.this.setItem(found.get(0));
Editor.this.tf.setCaretPosition(pos);
Editor.this.tf.select(txt.length(), Editor.this.tf.getText().length());
// Show popup, and scroll to correct position
if (found.size() > 1 && showPopup) {
// limit popup rows
SearchComboBox.this.setMaximumRowCount(found.size());
SearchComboBox.this.setPopupVisible(true);
// Scroll popup list, so that found[0] is the first
// entry. This is a bit "dirty", so we put it in a
// try catch...just to avoid EDT Exceptions
try {
final Object popup = SearchComboBox.this.getUI().getAccessibleChild(SearchComboBox.this, 0);
if (popup instanceof Container) {
final Component scrollPane = ((Container) popup).getComponent(0);
if (popup instanceof ComboPopup) {
final JList jlist = ((ComboPopup) popup).getList();
if (scrollPane instanceof JScrollPane) {
final Rectangle cellBounds = jlist.getCellBounds(SearchComboBox.this.getSelectedIndex(), SearchComboBox.this.getSelectedIndex() + found.size() - 1);
if (cellBounds != null) {
jlist.scrollRectToVisible(cellBounds);
}
}
}
}
} catch (final Throwable e) {
Log.exception(e);
}
} else {
SearchComboBox.this.hidePopup();
}
}
}
};
return found.size() > 0;
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxEditor#getEditorComponent()
*/
@Override
public Component getEditorComponent() {
// TODO Auto-generated method stub
return this.panel;
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxEditor#getItem()
*/
@Override
public Object getItem() {
// TODO Auto-generated method stub
return this.value;
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxEditor#removeActionListener(java.awt.event.
* ActionListener)
*/
@Override
public void removeActionListener(final ActionListener l) {
this.tf.removeActionListener(l);
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxEditor#selectAll()
*/
@Override
public void selectAll() {
this.tf.selectAll();
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxEditor#setItem(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public void setItem(final Object anObject) {
// if (this.value == anObject) { return; }
this.setting = true;
this.tf.setText(SearchComboBox.this.getText((T) anObject));
this.icon.setIcon(SearchComboBox.this.getIcon((T) anObject));
this.value = (T) anObject;
this.setting = false;
}
}
private Color foregroundBad = Color.red;
public SearchComboBox() {
super((ComboBoxModel) null);
this.setEditor(new Editor());
this.setEditable(true);
// we extends the existing renderer. this avoids LAF incompatibilities
final ListCellRenderer org = this.getRenderer();
this.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuCanceled(final PopupMenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {
SearchComboBox.this.setMaximumRowCount(8);
}
@Override
public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
}
});
this.setRenderer(new ListCellRenderer() {
@SuppressWarnings("unchecked")
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) {
try {
final JLabel ret = (JLabel) org.getListCellRendererComponent(list, SearchComboBox.this.getText((T) value), index, isSelected, cellHasFocus);
ret.setIcon(SearchComboBox.this.getIcon((T) value));
// ret.setOpaque(false);
return ret;
} catch (final Throwable e) {
// org might not be a JLabel (depending on the LAF)
// fallback here
return org.getListCellRendererComponent(list, SearchComboBox.this.getText((T) value), index, isSelected, cellHasFocus);
}
}
});
}
public Color getForegroundBad() {
return this.foregroundBad;
}
/**
* @param value
* @return
*/
abstract protected Icon getIcon(T value);
/**
* @param value
* @return
*/
abstract protected String getText(T value);
public void setForegroundBad(final Color forgroundGood) {
this.foregroundBad = forgroundGood;
}
/**
* Sets the Model for this combobox
*
* @param listModel
*/
public void setList(final ArrayList<T> listModel) {
super.setModel(new DefaultComboBoxModel(listModel.toArray(new Object[] {})));
}
/**
* Do not use this method. For Type Safty, please use
* {@link #setList(ArrayList)} instead
*
* @deprecated use {@link #setList(ArrayList)}
*/
@Deprecated
public void setModel(final ComboBoxModel aModel) {
if (aModel == null) {
super.setModel(new DefaultComboBoxModel());
return;
}
throw new RuntimeException("Use setList()");
}
}
|
package tracker_java.Utilities;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
/**
* returns JSON replies from the specified Object
*/
public enum JsonResponseHandler {
INSTANCE;
public void replyWithJsonFromObject(HttpExchange httpExchange, Object theObject) {
ObjectMapper om = new ObjectMapper();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS.MSZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
om.setDateFormat(df);
com.fasterxml.jackson.databind.ObjectWriter ow = om.writer().withDefaultPrettyPrinter();
String resultAsJson = null;
try {
resultAsJson = ow.writeValueAsString(theObject);
} catch (IOException e) {
e.printStackTrace();
}
if (resultAsJson != null) {
Headers headers = httpExchange.getResponseHeaders();
headers.add("Content-type", "text/json");
try {
httpExchange.sendResponseHeaders(200, resultAsJson.getBytes().length);
} catch (IOException e) {
e.printStackTrace();
}
OutputStream res = httpExchange.getResponseBody();
try {
System.out.format("Replying with %s", resultAsJson);
res.write(resultAsJson.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
res.close();
} catch (IOException e) {
e.printStackTrace();
}
httpExchange.close();
}
else {
System.out.format("ERROR 500: resultAsJson was null when requesting %s%n", httpExchange.getRequestURI().toString());
errorHandler.INSTANCE.returnServerError(httpExchange);
}
}
}
|
package edu.umd.cs.findbugs;
/**
* Format the message for a BugInstance.
* This class works in much the same way as <code>java.text.MessageFormat</code>;
* however, each placeholder may have an optional "key" which specifies
* how the object at that position should be formatted.
* <p/>
* <p> Example:
* <pre>
* new FindBugsMessageFormat("BUG: {1} does something bad to field {2.fullField}")
* </pre>
* In this example, the method annotation at position 1 is formatted using
* the empty (default) key. The field annotation at position 2 is formatted
* using the "fullField" key, which uses the long format for the field rather
* than the usual "class.fieldname" format.
*
* @author David Hovemeyer
* @see BugInstance
*/
public class FindBugsMessageFormat {
private String pattern;
/**
* Constructor.
*
* @param pattern the pattern for the message
*/
public FindBugsMessageFormat(String pattern) {
this.pattern = pattern;
}
/**
* Format the message using the given array of BugAnnotations as arguments
* to bind to the placeholders in the pattern string.
*
* @param args the BugAnnotations used as arguments
* @param primaryClass TODO
* @return the formatted message
*/
public String format(BugAnnotation[] args, ClassAnnotation primaryClass) {
String pat = pattern;
StringBuffer result = new StringBuffer();
while (pat.length() > 0) {
int subst = pat.indexOf('{');
if (subst < 0) {
result.append(pat);
break;
}
result.append(pat.substring(0, subst));
pat = pat.substring(subst + 1);
int end = pat.indexOf('}');
if (end < 0)
throw new IllegalStateException("bad pattern " + pattern);
String substPat = pat.substring(0, end);
int dot = substPat.indexOf('.');
String key = "";
if (dot >= 0) {
key = substPat.substring(dot + 1);
substPat = substPat.substring(0, dot);
}
int fieldNum;
try {
fieldNum = Integer.parseInt(substPat);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("bad pattern " + pattern);
}
// System.out.println("fn: " + fieldNum);
if (fieldNum < 0) {
result.append("?<?" + fieldNum + "/" + args.length + "???");
} else if (fieldNum > args.length) {
result.append("?>?" + fieldNum + "/" + args.length + "???");
} else {
BugAnnotation field = args[fieldNum];
String formatted = "";
try { formatted = field.format(key, primaryClass);
} catch (IllegalArgumentException iae) {
// unknown key -- not unprecedented when reading xml generated by older versions of findbugs
formatted = "\u00BF"+fieldNum+".(key="+key+")?"; // "\u00BF" is inverted question mark
// System.err.println(iae.getMessage()+" in FindBugsMessageFormat"); // FIXME: log this error better
}
result.append(formatted);
}
pat = pat.substring(end + 1);
}
return result.toString();
}
}
// vim:ts=4
|
package de.retest.recheck.report;
import static de.retest.recheck.persistence.xml.util.XmlUtil.clean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import de.retest.recheck.NoGoldenMasterActionReplayResult;
import de.retest.recheck.ignore.Filter;
import de.retest.recheck.ui.diff.LeafDifference;
@XmlRootElement( name = "test" )
@XmlAccessorType( XmlAccessType.FIELD )
public class TestReplayResult implements Serializable {
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger( TestReplayResult.class );
@XmlAttribute
private final String name;
@XmlAttribute
private final int testNr;
@XmlElement( name = "action" )
private List<ActionReplayResult> actionReplayResults;
@XmlElement
private long testDuration;
@SuppressWarnings( "unused" )
private TestReplayResult() {
// for JAXB
testNr = 0;
name = null;
}
public TestReplayResult( final String testName, final int testNr ) {
name = testName == null ? "Test no. " + testNr : clean( testName );
if ( testName == null ) {
logger.info( "No test name given, using {}.", name );
}
this.testNr = testNr;
// Don't use here a list without a fix ordering, because we need the exact order
// for applyChanges in review module!!
actionReplayResults = new ArrayList<>();
}
public int getTestNr() {
return testNr;
}
public long getDuration() {
return testDuration;
}
public void addAction( final ActionReplayResult newReplayResult ) {
testDuration += newReplayResult.getDuration();
actionReplayResults.add( newReplayResult );
}
public String getName() {
return name;
}
public List<ActionReplayResult> getActionReplayResults() {
return Collections.unmodifiableList( actionReplayResults );
}
public int getCheckedUiElementsCount() {
int uiElementsCount = 0;
for ( final ActionReplayResult actionReplayResult : actionReplayResults ) {
uiElementsCount += actionReplayResult.getCheckedUiElementsCount();
}
return uiElementsCount;
}
@Deprecated
public Set<LeafDifference> getDifferences( final Filter filter ) {
final Set<LeafDifference> diffs = new HashSet<>();
for ( final ActionReplayResult actionReplayResult : actionReplayResults ) {
diffs.addAll( actionReplayResult.getDifferencesWithout( filter ) );
}
return diffs;
}
public Set<LeafDifference> getDifferences() {
final Set<LeafDifference> diffs = new HashSet<>();
for ( final ActionReplayResult actionReplayResult : actionReplayResults ) {
diffs.addAll( actionReplayResult.getDifferences() );
}
return diffs;
}
public int getDifferencesCount() {
int differences = 0;
for ( final ActionReplayResult actionReplayResult : actionReplayResults ) {
differences += actionReplayResult.getAllElementDifferences().size();
}
return differences;
}
public boolean hasNoGoldenMaster() {
return actionReplayResults.stream().allMatch( NoGoldenMasterActionReplayResult.class::isInstance );
}
@Override
public String toString() {
return "TestReplayResult('" + getName() + "'"
+ ", Actions: " + getActionReplayResults().size()
+ ", Checked Elements: " + getCheckedUiElementsCount()
+ ", Differences: " + getDifferencesCount()
+ ")";
}
public boolean isEmpty() {
return getDifferencesCount() == 0;
}
}
|
package tw.kewang.logback.appender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import com.taskadapter.redmineapi.IssueManager;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineManager;
import com.taskadapter.redmineapi.RedmineManagerFactory;
import com.taskadapter.redmineapi.bean.Issue;
import com.taskadapter.redmineapi.bean.IssueFactory;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
public class RedmineAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private static final String DEFAULT_TITLE = "Logback Redmine Appender";
private static final boolean DEFAULT_ONLY_ERROR = true;
private static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private LayoutWrappingEncoder<ILoggingEvent> encoder;
private Layout<ILoggingEvent> layout;
private String url;
private String apiKey;
private int projectId = -1;
private String title = DEFAULT_TITLE;
private boolean onlyError = DEFAULT_ONLY_ERROR;
private MessageDigest md;
private RedmineManager redmineManager;
private IssueManager issueManager;
private HashMap<String, Integer> maps; // <stacktrace hash, issue_id>, like <0d612fc42ec7b7f02cb5affcbb20d531, 25>
private SimpleDateFormat dateFormat = DEFAULT_DATE_FORMAT;
@Override
public void start() {
if (!checkProperty()) {
addError("No set url / apiKey / projectId [" + name + "].");
return;
}
if (encoder == null) {
addError("No encoder set for the appender named [" + name + "].");
return;
}
try {
encoder.init(System.out);
transformDateFormat();
layout = encoder.getLayout();
md = MessageDigest.getInstance("MD5");
} catch (Exception e) {
addError("Exception", e);
}
redmineManager = RedmineManagerFactory.createWithApiKey(url, apiKey);
issueManager = redmineManager.getIssueManager();
maps = new HashMap<String, Integer>();
super.start();
}
private void transformDateFormat() {
if (encoder instanceof PatternLayoutEncoder) {
String encoderPattern = ((PatternLayoutEncoder) encoder).getPattern();
int startPos = encoderPattern.indexOf("%d{");
int endPos = encoderPattern.indexOf("}", startPos);
String pattern = encoderPattern.substring(startPos + 3, endPos);
dateFormat = new SimpleDateFormat(pattern);
}
}
private boolean checkProperty() {
return url != null && url.length() != 0 && apiKey != null && apiKey.length() != 0 && projectId != -1;
}
@Override
public void append(ILoggingEvent event) {
if (event.getLevel() != Level.ERROR && onlyError == true) {
return;
}
try {
createIssue(event);
} catch (RedmineException e) {
addError("Exception", e);
}
showEvent(event);
}
private void showEvent(ILoggingEvent event) {
IThrowableProxy throwable = event.getThrowableProxy();
for (StackTraceElementProxy stackTrace : throwable.getStackTraceElementProxyArray()) {
StackTraceElement elem = stackTrace.getStackTraceElement();
System.out.println("
convertClassToNavigate(elem);
System.out.println("
}
}
/**
* Convert com.example.Test(Test.java: 15) class to com/example/Test.java#L15
*/
private String convertClassToNavigate(StackTraceElement elem) {
String[] classNameArray = elem.getClassName().split("\\.");
classNameArray[classNameArray.length - 1] = elem.getFileName();
String result = "";
for (String className : classNameArray) {
result += className + "/";
}
result = result.substring(0, result.length() - 1);
result += "#L" + elem.getLineNumber();
return result;
}
private void createIssue(ILoggingEvent event) throws RedmineException {
String hash = convertStackTracesToHash(event);
Integer issueId = maps.get(hash);
if (issueId == null) {
createNewIssue(event, hash);
} else {
appendToOldIssue(issueId);
}
}
private String convertStackTracesToHash(ILoggingEvent event) {
IThrowableProxy throwable = event.getThrowableProxy();
StringBuffer sb = new StringBuffer();
for (StackTraceElementProxy stackTrace : throwable.getStackTraceElementProxyArray()) {
StackTraceElement elem = stackTrace.getStackTraceElement();
sb.append(elem.toString());
}
return hash(sb.toString());
}
private String hash(String source) {
md.update(source.getBytes());
byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
private void createNewIssue(ILoggingEvent event, String hash) throws RedmineException {
Issue issue = IssueFactory.create(projectId, title + " - " + event.getTimeStamp());
issue.setDescription(layout.doLayout(event));
issue = issueManager.createIssue(issue);
maps.put(hash, issue.getId());
}
private void appendToOldIssue(int issueId) throws RedmineException {
Issue issue = issueManager.getIssueById(issueId);
issue.setNotes(dateFormat.format(new Date()) + " again");
issueManager.update(issue);
}
public LayoutWrappingEncoder<ILoggingEvent> getEncoder() {
return encoder;
}
public void setEncoder(LayoutWrappingEncoder<ILoggingEvent> encoder) {
this.encoder = encoder;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKey() {
return apiKey;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public int getProjectId() {
return projectId;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public boolean isOnlyError() {
return onlyError;
}
public void setOnlyError(boolean onlyError) {
this.onlyError = onlyError;
}
}
|
package be.ibad;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import be.ibad.floatingactionmenu.R;
import be.ibad.listener.OnMenuItemClickListener;
import be.ibad.listener.OnMenuToggleListener;
@CoordinatorLayout.DefaultBehavior(FloatingActionMenu.Behavior.class)
public class FloatingActionMenu extends ViewGroup {
private static final TimeInterpolator DEFAULT_OPEN_INTERPOLATOR = new OvershootInterpolator();
private static final TimeInterpolator DEFAULT_CLOSE_INTERPOLATOR = new AnticipateInterpolator();
private FloatingActionButton menuButton;
private List<FloatingActionButton> menuItems;
private List<View> menuLabels;
private List<ChildAnimator> itemAnimators;
private View backgroundView;
private AnimatorSet openSet = new AnimatorSet();
private AnimatorSet closeSet = new AnimatorSet();
private Animator openOverlay;
private Animator closeOverlay;
private List<OnMenuItemClickListener> clickListeners;
private List<OnMenuToggleListener> openListeners;
private boolean isOpen;
private boolean isAnimating;
private boolean displayLabels;
private boolean isCloseOnTouchOutside = true;
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return isCloseOnTouchOutside && isOpened();
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
close();
return true;
}
});
private long actionsDuration;
private int menuButtonBackground;
private int menuButtonRipple;
private int menuButtonSrc;
@ColorInt
private int overlayBackground;
private int buttonSpacing;
private int maxButtonWidth;
@ColorInt
private int labelBackgroundColor;
@ColorInt
private int labelTextColor;
private int menuMarginEnd;
private int menuMarginBottom;
private int overlayDuration;
private int labelMarginEnd;
private float labelTextSize;
private OnClickListener onItemClickListener = new OnClickListener() {
@Override
public void onClick(final View view) {
closeSet.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
closeSet.removeListener(this);
if (view instanceof FloatingActionButton) {
int i = menuItems.indexOf(view);
triggerClickListeners(i, (FloatingActionButton) view);
} else if (view != backgroundView) {
int i = menuLabels.indexOf(view);
triggerClickListeners(i, menuItems.get(i));
}
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
close();
}
};
public FloatingActionMenu(Context context) {
this(context, null, 0);
}
public FloatingActionMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FloatingActionMenu(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray attributes = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.FloatingActionMenu, 0, 0);
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
int colorAccent = typedValue.data;
try {
overlayBackground = attributes
.getColor(R.styleable.FloatingActionMenu_overlay_color, Color.parseColor("#7F2a3441"));
buttonSpacing = attributes
.getDimensionPixelSize(R.styleable.FloatingActionMenu_item_spacing, dpToPx(context, 4f));
menuButtonBackground = attributes.getColor(R.styleable.FloatingActionMenu_base_background, colorAccent);
menuButtonRipple = attributes
.getColor(R.styleable.FloatingActionMenu_base_ripple, Color.parseColor("#66ffffff"));
menuButtonSrc = attributes
.getResourceId(R.styleable.FloatingActionMenu_base_src, R.drawable.ic_positive);
menuMarginEnd = attributes
.getDimensionPixelSize(R.styleable.FloatingActionMenu_base_marginEnd, dpToPx(context, 8f));
menuMarginBottom = attributes
.getDimensionPixelSize(R.styleable.FloatingActionMenu_base_marginBottom, dpToPx(context, 8f));
overlayDuration = attributes
.getInteger(R.styleable.FloatingActionMenu_overlay_duration, getResources().getInteger(android.R.integer.config_shortAnimTime));
actionsDuration = attributes
.getInteger(R.styleable.FloatingActionMenu_actions_duration, getResources().getInteger(android.R.integer.config_shortAnimTime));
labelBackgroundColor = attributes
.getColor(R.styleable.FloatingActionMenu_label_background, ContextCompat.getColor(getContext(), android.R.color.white));
labelTextColor = attributes
.getColor(R.styleable.FloatingActionMenu_label_fontColor, Color.BLACK);
labelTextSize = attributes
.getFloat(R.styleable.FloatingActionMenu_label_fontSize, 12f);
displayLabels = attributes
.getBoolean(R.styleable.FloatingActionMenu_enable_labels, true);
labelMarginEnd = attributes
.getDimensionPixelSize(R.styleable.FloatingActionMenu_label_marginEnd, dpToPx(context, 4f));
} finally {
attributes.recycle();
}
menuItems = new ArrayList<>();
menuLabels = new ArrayList<>();
itemAnimators = new ArrayList<>();
clickListeners = new ArrayList<>();
openListeners = new ArrayList<>();
menuButton = new FloatingActionButton(getContext());
menuButton.setSize(FloatingActionButton.SIZE_AUTO);
menuButton.setBackgroundTintList(ColorStateList.valueOf(menuButtonBackground));
menuButton.setRippleColor(menuButtonRipple);
menuButton.setImageResource(menuButtonSrc);
menuButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
toggle();
}
});
backgroundView = new View(getContext());
backgroundView.setBackgroundColor(overlayBackground);
backgroundView.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
createDefaultIconAnimation();
}
@Override
public void onViewDetachedFromWindow(View v) {
}
});
addViewInLayout(menuButton, -1, new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(backgroundView);
}
static int dpToPx(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return Math.round(dp * scale);
}
@Override
protected void onFinishInflate() {
bringChildToFront(menuButton);
super.onFinishInflate();
}
@Override
public void addView(@NonNull View child, int index, LayoutParams params) {
super.addView(child, index, params);
if (child instanceof FloatingActionButton) {
child.setLayoutParams(params);
addMenuItem((FloatingActionButton) child);
}
}
public void addMenuItem(FloatingActionButton item) {
menuItems.add(item);
if (displayLabels) {
buildLabelButton(item);
}
itemAnimators.add(new ChildAnimator(item));
item.setOnClickListener(onItemClickListener);
}
private void buildLabelButton(FloatingActionButton item) {
View label = View.inflate(getContext(), R.layout.label_layout, null);
label.setBackgroundResource(R.drawable.label_background);
label.getBackground().mutate().setColorFilter(labelBackgroundColor, PorterDuff.Mode.SRC_IN);
TextView textView = (TextView) label.findViewById(R.id.label_text);
textView.setText(item.getContentDescription());
textView.setTextColor(labelTextColor);
textView.setTextSize(labelTextSize);
addView(label);
menuLabels.add(label);
item.setTag(label);
label.setOnClickListener(onItemClickListener);
}
public void toggle() {
if (!isOpen) {
open();
} else {
close();
}
}
public void open() {
startOpenAnimator();
isOpen = true;
triggerOpenListeners(true);
}
public void close() {
startCloseAnimator();
isOpen = false;
triggerOpenListeners(false);
}
private void triggerOpenListeners(boolean state) {
if (openListeners.size() > 0) {
for (OnMenuToggleListener listener : openListeners) {
listener.onMenuToggle(state);
}
}
}
private void triggerClickListeners(int index, FloatingActionButton button) {
if (clickListeners.size() > 0) {
for (OnMenuItemClickListener listener : clickListeners) {
listener.onMenuItemClick(this, index, button);
}
}
}
private void createOverlayRippleAnimation() {
WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int radius = menuButton.getHeight() / 2;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
closeOverlay = ViewAnimationUtils.createCircularReveal(backgroundView,
menuButton.getLeft() + radius, menuButton.getTop() + radius,
Math.max(size.x, size.y), radius);
} else {
closeOverlay = ObjectAnimator.ofFloat(backgroundView, "alpha", 1f, 0f);
}
closeOverlay.setDuration(overlayDuration);
closeOverlay.setInterpolator(new AccelerateDecelerateInterpolator());
closeOverlay.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
backgroundView.setVisibility(GONE);
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
openOverlay = ViewAnimationUtils.createCircularReveal(backgroundView,
menuButton.getLeft() + radius, menuButton.getTop() + radius, radius,
Math.max(size.x, size.y));
} else {
openOverlay = ObjectAnimator.ofFloat(backgroundView, "alpha", 0f, 1f);
}
openOverlay.setDuration(overlayDuration);
openOverlay.setInterpolator(new AccelerateDecelerateInterpolator());
openOverlay.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
backgroundView.setVisibility(VISIBLE);
}
});
}
protected void startCloseAnimator() {
closeSet.start();
closeOverlay.start();
for (ChildAnimator anim : itemAnimators) {
anim.startCloseAnimator();
}
}
protected void startOpenAnimator() {
createOverlayRippleAnimation();
openOverlay.start();
openSet.start();
for (ChildAnimator anim : itemAnimators) {
anim.startOpenAnimator();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int width;
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int height;
final int count = getChildCount();
maxButtonWidth = 0;
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
for (int i = 0; i < menuItems.size(); i++) {
FloatingActionButton fab = menuItems.get(i);
if (menuLabels.size() > 0) {
View label = menuLabels.get(i);
maxButtonWidth = Math.max(maxButtonWidth, label.getMeasuredWidth() + fab.getMeasuredWidth()
+ ViewCompat.getPaddingEnd(fab) + ViewCompat.getPaddingStart(fab));
}
}
maxButtonWidth = Math.max(menuButton.getMeasuredWidth(), maxButtonWidth);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
width = maxButtonWidth;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
int heightSum = 0;
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
heightSum += child.getMeasuredHeight() + child.getPaddingBottom();
}
height = heightSum;
}
setMeasuredDimension(resolveSize(width, widthMeasureSpec),
resolveSize(height, heightMeasureSpec));
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (isCloseOnTouchOutside) {
return gestureDetector.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed) {
backgroundView.layout(l, 0, r, b);
int buttonsHorizontalCenter = r - l - menuButton.getMeasuredWidth() / 2 - getPaddingRight() - menuMarginEnd;
int menuButtonTop = b - t - menuButton.getMeasuredHeight() - getPaddingBottom() - menuMarginBottom;
int menuButtonLeft = buttonsHorizontalCenter - menuButton.getMeasuredWidth() / 2;
menuButton.layout(menuButtonLeft, menuButtonTop,
menuButtonLeft + menuButton.getMeasuredWidth(),
menuButtonTop + menuButton.getMeasuredHeight());
int nextY = menuButtonTop;
int itemCount = menuItems.size();
for (int i = 0; i < itemCount; i++) {
FloatingActionButton item = menuItems.get(i);
if (item.getVisibility() != GONE) {
int childX = buttonsHorizontalCenter - item.getMeasuredWidth() / 2;
int childY = nextY - item.getMeasuredHeight() - buttonSpacing;
item.layout(childX, childY, childX + item.getMeasuredWidth(), childY + item.getMeasuredHeight());
View label = (View) item.getTag();
if (label != null) {
int labelsOffset = item.getMeasuredWidth() / 2 + labelMarginEnd;
int labelXEnd = buttonsHorizontalCenter - labelsOffset;
int labelXStart = labelXEnd - label.getMeasuredWidth();
int labelTop = childY + (item.getMeasuredHeight() - label.getMeasuredHeight()) / 2;
label.layout(labelXStart, labelTop, labelXEnd, labelTop + label.getMeasuredHeight());
if (!isAnimating) {
if (!isOpen) {
label.setVisibility(INVISIBLE);
}
}
}
nextY = childY;
if (!isAnimating) {
if (!isOpen) {
item.setTranslationY(menuButton.getTop() - item.getTop());
item.setVisibility(INVISIBLE);
backgroundView.setVisibility(INVISIBLE);
}
}
}
}
if (!isAnimating && getBackground() != null) {
if (!isOpen) {
getBackground().setAlpha(0);
} else {
getBackground().setAlpha(0xff);
}
}
}
}
private void createDefaultIconAnimation() {
Animator.AnimatorListener listener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
isAnimating = true;
}
@Override
public void onAnimationEnd(Animator animation) {
isAnimating = false;
}
@Override
public void onAnimationCancel(Animator animation) {
isAnimating = false;
}
@Override
public void onAnimationRepeat(Animator animation) {
}
};
ObjectAnimator collapseAnimator = ObjectAnimator.ofFloat(menuButton, "rotation", 135f, 0f);
ObjectAnimator expandAnimator = ObjectAnimator.ofFloat(menuButton, "rotation", 0f, 135f);
openSet.playTogether(expandAnimator);
closeSet.playTogether(collapseAnimator);
openSet.setInterpolator(DEFAULT_OPEN_INTERPOLATOR);
closeSet.setInterpolator(DEFAULT_CLOSE_INTERPOLATOR);
openSet.setDuration(actionsDuration);
closeSet.setDuration(actionsDuration);
openSet.addListener(listener);
closeSet.addListener(listener);
}
public boolean isOpened() {
return isOpen;
}
@Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.onSaveInstanceState());
bundle.putBoolean("openState", isOpen);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
isOpen = bundle.getBoolean("openState");
state = bundle.getParcelable("instanceState");
}
super.onRestoreInstanceState(state);
}
public void addOnMenuItemClickListener(OnMenuItemClickListener listener) {
this.clickListeners.add(listener);
}
public void addOnMenuToggleListener(OnMenuToggleListener listener) {
this.openListeners.add(listener);
}
public boolean removeOnMenuItemClickListener(OnMenuItemClickListener listener) {
return this.clickListeners.remove(listener);
}
public boolean removeOnMenuToggleListener(OnMenuToggleListener listener) {
return this.openListeners.remove(listener);
}
/**
* Behavior designed for use with {@link FloatingActionMenu} instances. It's main function
* is to move all {@link FloatingActionButton}s views inside {@link FloatingActionMenu} so
* that any displayed {@link Snackbar}s do not cover them.
*/
public static class Behavior extends CoordinatorLayout.Behavior<FloatingActionMenu> {
/**
* Default constructor for instantiating Behaviors.
*/
public Behavior() {
}
public Behavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionMenu child, View dependency) {
return dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionMenu child, View dependency) {
float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
child.setTranslationY(translationY);
return true;
}
}
class ChildAnimator implements Animator.AnimatorListener {
private View view;
private View label;
private AlphaAnimation openAnimation;
private AlphaAnimation closeAnimation;
private boolean playingOpenAnimator;
ChildAnimator(View view) {
view.animate().setListener(this);
if (displayLabels) {
label = (View) view.getTag();
openAnimation = new AlphaAnimation(0f, 1f);
openAnimation.setDuration(250);
closeAnimation = new AlphaAnimation(1f, 0f);
closeAnimation.setDuration(250);
}
this.view = view;
}
void startOpenAnimator() {
view.animate().cancel();
playingOpenAnimator = true;
view.animate()
.translationY(0)
.setInterpolator(DEFAULT_OPEN_INTERPOLATOR)
.start();
}
void startCloseAnimator() {
view.animate().cancel();
playingOpenAnimator = false;
if (displayLabels) {
label.startAnimation(closeAnimation);
}
view.animate()
.translationY((menuButton.getTop() - view.getTop()))
.setInterpolator(DEFAULT_CLOSE_INTERPOLATOR)
.start();
}
@Override
public void onAnimationStart(Animator animation) {
if (playingOpenAnimator) {
view.setVisibility(VISIBLE);
} else {
if (displayLabels) {
label.setVisibility(GONE);
}
}
}
@Override
public void onAnimationEnd(Animator animation) {
if (!playingOpenAnimator) {
view.setVisibility(GONE);
} else {
if (displayLabels) {
label.setVisibility(VISIBLE);
label.startAnimation(openAnimation);
}
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
}
|
package edu.ucdenver.ccp.common.string;
import static edu.ucdenver.ccp.common.string.RegExPatterns.HAS_NUMBERS_ONLY_OPT_NEG;
import static edu.ucdenver.ccp.common.string.RegExPatterns.HAS_NUMBERS_ONLY_OPT_NEG_ZERO_START;
import static edu.ucdenver.ccp.common.string.RegExPatterns.HAS_NUMBERS_ONLY;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
public class StringUtil {
/**
* Returns true if the input string is an integer, false otherwise.
*
* @param inputStr
* @return
*/
public static boolean isInteger(String inputStr) {
if (inputStr != null && inputStr.equals(StringConstants.DIGIT_ZERO))
return true;
return inputStr == null ? false : (inputStr.matches(HAS_NUMBERS_ONLY_OPT_NEG) && !inputStr
.matches(HAS_NUMBERS_ONLY_OPT_NEG_ZERO_START));
}
/**
* Returns true if the input string is a non-negative integer, false otherwise.
*
* @param inputStr
* @return
*/
public static boolean isNonNegativeInteger(String inputStr) {
if (inputStr != null && inputStr.equals(StringConstants.DIGIT_ZERO))
return true;
return inputStr == null ? false : (inputStr.matches(HAS_NUMBERS_ONLY) && !inputStr
.matches(HAS_NUMBERS_ONLY_OPT_NEG_ZERO_START));
}
public static String removeSuffix(String inputStr, String suffix) throws IllegalArgumentException {
if (inputStr != null && suffix != null) {
if (inputStr.endsWith(suffix)) {
return removeNTrailingCharacters(inputStr, suffix.length());
}
}
throw new IllegalArgumentException(String.format(
"Invalid input. Cannot remove suffix. Input String \"%s\" does not end with suffix \"%s\"", inputStr,
suffix));
}
/**
* Returns a String after removing n characters at the end of the input String
*
* @param inputStr
* @param n
* @return
*/
public static String removeNTrailingCharacters(String inputStr, int n) {
return inputStr.substring(0, inputStr.length() - n);
}
/**
* Returns a String after removing the final character of the input String
*
* @param inputStr
* @return
*/
public static String removeLastCharacter(String inputStr) {
return removeNTrailingCharacters(inputStr, 1);
}
/**
* Replaces one suffix with another on the input String
*
* @param inputStr
* @param suffix
* @param replacementSuffix
* @return
*/
public static String replaceSuffix(String inputStr, String suffix, String replacementSuffix) {
return removeSuffix(inputStr, suffix) + replacementSuffix;
}
/**
* Returns true if the beginning of the inputStr matches the regular expression, false
* otherwise.
*
* @param inputStr
* @param regexStr
* @return
*/
public static boolean startsWithRegex(String inputStr, String regexStr) {
if (!regexStr.startsWith("^")) {
regexStr = "^" + regexStr;
}
return containsRegex(inputStr, regexStr);
}
public static boolean containsRegex(String inputStr, String regexStr) {
Pattern p = Pattern.compile(regexStr);
return p.matcher(inputStr).find();
}
/**
* Converts the input InputStream to a String
*
* @param is
* @param encoding
* @return
* @throws IOException
*/
public static String convertStream(InputStream is, String encoding) throws IOException {
StringWriter sw = new StringWriter();
try {
IOUtils.copy(is, sw, encoding);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(sw);
}
return sw.toString();
}
/**
* Splits the input string, but ignores any delimiters inside a field. For example, you might be
* splitting a comma-delimited line but have a field indicated by quotation marks that can
* contain a comma. e.g. token 1,token 2,"token, 3 has a comma",token 4
*
* @param inputStr
* @param delimiters
* @return
*/
public static String[] splitWithFieldEnclosure(String inputStr, String delimiterRegex,
String optionalFieldEnclosureRegex) {
if (optionalFieldEnclosureRegex == null || !containsRegex(inputStr, optionalFieldEnclosureRegex))
return inputStr.split(delimiterRegex,-1);
String copyOfInputStr = normalizeInputFields(inputStr, delimiterRegex, optionalFieldEnclosureRegex);
List<String> tokens = new ArrayList<String>();
int previousDelimiterEndIndex = 0;
Matcher matcher = Pattern.compile(delimiterRegex).matcher(copyOfInputStr);
while (matcher.find()) {
int delimiterStartIndex = matcher.start();
int delimiterEndIndex = matcher.end();
tokens.add(inputStr.substring(previousDelimiterEndIndex, delimiterStartIndex));
previousDelimiterEndIndex = delimiterEndIndex;
}
if (previousDelimiterEndIndex == 0)
tokens.add(inputStr);
else
tokens.add(inputStr.substring(previousDelimiterEndIndex));
return tokens.toArray(new String[tokens.size()]);
}
/**
* Given an inputStr with possible delimiters hidden inside fields, this method returns a String
* where the fields have been normalized (turned into a string of zero's)
*
* @param inputStr
* @param delimiterRegex
* @param optionalFieldEnclosureCharacter
* @return
*/
private static String normalizeInputFields(String inputStr, String delimiterRegex,
String optionalFieldEnclosureRegex) {
String tempReplacementStr = StringConstants.DIGIT_ZERO;
if (delimiterRegex.contains(tempReplacementStr))
throw new IllegalArgumentException(
"Warning. Potential error exists in current use of splitWithFieldDelimiter(). "
+ "This method uses the character '%s' internally during a split procedure. The "
+ "input delimiter contains the character '%s'. Therefore there is a potential conflict. "
+ "Please use a different delimiter. Exiting...");
String copyOfInputStr = inputStr;
Pattern fieldPattern = Pattern.compile(optionalFieldEnclosureRegex + ".*?"
+ optionalFieldEnclosureRegex);
Matcher matcher = fieldPattern.matcher(inputStr);
while (matcher.find()) {
copyOfInputStr = copyOfInputStr.replace(matcher.group(), createRepeatingString(StringConstants.DIGIT_ZERO,
matcher.group().length()));
}
return copyOfInputStr;
}
/**
* Returns a sequence of the input string repeated length times.
*
* @param inputStr
* @param length
* @return
*/
public static String createRepeatingString(String inputStr, int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(inputStr);
}
return sb.toString();
}
/**
* Delimit values with provided delimiter and strip surrounding single characters (ex: double-quotes) .
*
* @param values to delimit
* @param delim delimiter.
*
* @return converted values.
*/
public static Collection<String> delimitAndTrim(String values, String delim) {
List<String> list = Arrays.asList(values.split(delim));
List<String> trimmed = new ArrayList<String>();
for (String v : list)
if (v.trim().length() > 0)
trimmed.add(v.substring(1, v.length() - 1));
return trimmed;
}
}
|
package io.dindinw.cmdline.tool;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.dindinw.cmdline.CmdLine;
import io.dindinw.cmdline.Option;
import io.dindinw.cmdline.Parser;
public final class JGrep {
private static boolean show_line_number = false;
private static boolean show_file_name = false;
public static void main(String[] args) throws Exception{
Parser parser = new Parser();
parser.addOption(new Option("-n","--line-number","print the matched line number"));
parser.addOption(new Option("-H","Always print filename headers with output lines."));
CmdLine cmd = parser.parse(args);
if (cmd.getArgs().length < 1) {
System.err.println("Usage: JGrep pattern [file]|System.in "); System.exit(1);
System.exit(1);
}
Pattern p= Pattern.compile(cmd.getArgs()[0]);
if (cmd.hasOption("-n")){
show_line_number = true;
}
if (cmd.hasOption("-H")){
show_file_name = true;
}
if (cmd.getArgs().length == 1) {
process(p,"SYSTEM.IN");
}else{
for (int i=1; i<cmd.getArgs().length; i++)
process(p, cmd.getArgs()[i]);
}
}
static void process(Pattern pattern, String fileName) throws IOException {
BufferedReader br = null;
if ("SYSTEM.IN".equals(fileName)){
br = new BufferedReader(new InputStreamReader(System.in));
}else{
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
}
Matcher m = pattern.matcher("");
String line = null;
int lineNum = 0;
String line_number = "";
String file ="";
if (show_file_name){
file=fileName+":";
}
while ((line = br.readLine()) !=null){
lineNum++;
m.reset(line);
if (m.find()){
if (show_line_number){
line_number = ""+lineNum+":";
}
System.out.printf("%s%s%s\n",file,line_number,line);
}
}
}
}
|
package vista;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class DialogoCrearAutor extends JDialog{
private static final long serialVersionUID = 1L;
private JLabel lbNombre;
private JTextField txNombre;
private JButton btnCrearLibro;
private JButton btnCancelar;
public DialogoCrearAutor() {
setTitle(ConstantesGUI.T_CREAR_AUTOR);
setSize(ConstantesGUI.ANCHO_DIALOGO, ConstantesGUI.ALTO_DIALOGO);
setLayout(null);
setLocationRelativeTo(null);
setModal(true);
lbNombre = new JLabel(ConstantesGUI.T_NOMBRE);
lbNombre.setBounds(30, 100, 100, 50);
add(lbNombre);
txNombre = new JTextField();
txNombre.setBounds(100, 110, 100, 25);
add(txNombre);
btnCrearLibro = new JButton(ConstantesGUI.T_CREAR_AUTOR);
btnCrearLibro.setBounds(350, 500, 100, 30);
add(btnCrearLibro);
btnCancelar = new JButton(ConstantesGUI.T_CANCELAR);
btnCancelar.setBounds(50, 500, 100, 30);
add(btnCancelar);
}
public static void main(String[] args) {
DialogoCrearAutor di = new DialogoCrearAutor();
di.setVisible(true);
}
}
|
package org.eprotectioneers.panacea.contactmanagement.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.LayoutManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import org.eprotectioneers.panacea.contactmanagement.design.DesignDatabase;
import org.eprotectioneers.panacea.contactmanagement.design.ProjectPanaceaTemplates;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JToolTip;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JTextField;
import java.awt.Dimension;
import javax.swing.JMenuBar;
import java.awt.List;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class test extends JFrame {
//DevelopmentLifeFeed Simsen3142
private JPanel contentPane;
static test frame;
private org.eprotectioneers.panacea.contactmanagement.components.RoundTextField rndtxtfldTest;
private Contactbar contactbar;
private Component item_group;
private Contactbar contactbar_1;
private static JPanel panel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new Thread(new Runnable(){
public void run() {
DesignDatabase.loadDesign();
System.out.println(ProjectPanaceaTemplates.getCbg_contacts());
/*for(int i=1;i<658;i++){
DatabaseC.addContact(new Contact(i, "Contact "+i, "", "", "Email.c"+i+"@Eprotection.com", i+""+i+""+i+""+i, i+" Street", "", false));
DatabaseG.addGroup(new Group(i, "Group "+i, "The "+i+" Group", ""));
System.out.println(i);
}*/
}
}).start();
frame=new test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void setPanel(JPanel pnl){
frame.remove(panel);
panel=pnl;
frame.add(panel,BorderLayout.CENTER);
frame.setVisible(true);
}
/**
* Create the frame.
*/
public test() {
initialize();
}
private void initialize(){
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 450);
UIManager.put("ToolTip.background",new Color(10,10,10));
UIManager.put("ToolTip.foreground",Color.WHITE);
Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
UIManager.put("ToolTip.border", border);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
//Contact c=new Contact(2, "", "Simon", "Simon", "Simon", "Simon", "Simon", "s", false);
//Group g=new Group(1, "GROUP1", "MY FIRST CAPS GROUP", "");
//panel = new Page_Group(DatabaseG.getGroups().get(0));
//panel =new Page_AddContact();
//panel = new Page_Contact(DatabaseC.getContacts().get(4));
//item_group= new Item_contact(DatabaseC.getContacts().get(2));
//contentPane.add(item_group, BorderLayout.NORTH);
contactbar_1 = new Contactbar();
contactbar_1.setPreferredSize(new Dimension(300, 84));
contactbar_1.setMinimumSize(new Dimension(300, 70));
contentPane.add(contactbar_1, BorderLayout.EAST);
panel = new JPanel();
panel.setBackground(ProjectPanaceaTemplates.getCbg_contacts());
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
contentPane.add(panel, BorderLayout.CENTER);
try {
TwitterPanel twitterPanel1 = new TwitterPanel(new URL("https://twitter.com"),
"C:\\Users\\Katschtaler\\Desktop\\PPNCA_Images\\Twitter-icon.png", "Twitter", "@Twitter",
"Hello, my name is Twitter,\nPossibly, you ask yourself, why the person who wrote this wrote this... UND WIESO DER TYP DES NIT IN SEINER MUTTERSPRACHE GSCHRIEBN HAT, but there is no reason why...\nHe just wanted to write random Bullshit.\nSome of you will think, that this guy isn't normal into his brain. These people are possibly right.\nBut the writer of this tricked you. He told you, that there's no reason for writing this, but there is.\nThe real reason for writing this is, that the writer wanted to test, if you can read this anymore, or if there are already the 3 dots, the writer thinks, that there are already, because he is a great programmer.",
"C:\\Users\\Katschtaler\\Desktop\\PPNCA_Images\\typo-twitter-background.jpg");
panel.add(twitterPanel1);
TwitterPanel twitterPanel2 = new TwitterPanel(null,
"C:\\Users\\Katschtaler\\Desktop\\PPNCA_Images\\ep.jpg", "eProtectioneers", "@eProtectioneers",
"We protect your electronic communication",
new Color(234,101,65));
panel.add(twitterPanel2);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package uk.org.cowgill.james.jircd.commands;
import uk.org.cowgill.james.jircd.ConfigBlock;
import uk.org.cowgill.james.jircd.ModuleLoadException;
import uk.org.cowgill.james.jircd.ModuleManager;
import uk.org.cowgill.james.jircd.Server;
public class Module implements uk.org.cowgill.james.jircd.Module
{
@Override
public boolean startup(ConfigBlock config) throws ModuleLoadException
{
//Add commands
ModuleManager modMan = Server.getServer().getModuleManager();
modMan.registerCommand(new Nick());
modMan.registerCommand(new User());
modMan.registerCommand(new Quit());
modMan.registerCommand(new Oper());
modMan.registerCommand(new Mode());
modMan.registerCommand(new Join());
modMan.registerCommand(new Part());
modMan.registerCommand(new Part.Leave());
modMan.registerCommand(new Topic());
modMan.registerCommand(new Kick());
modMan.registerCommand(new Invite());
modMan.registerCommand(new Names());
modMan.registerCommand(new Msg.PrivMsg());
modMan.registerCommand(new Msg.Notice());
modMan.registerCommand(new List());
return true;
}
@Override
public void rehash(ConfigBlock config)
{
//I have no config
}
@Override
public void shutdown()
{
//Don't care
}
}
|
/*
* @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.portlets.core.login;
import org.gridlab.gridsphere.portlet.*;
import org.gridlab.gridsphere.provider.portletui.beans.*;
import org.gridlab.gridsphere.provider.portlet.ActionPortlet;
import org.gridlab.gridsphere.provider.event.FormEvent;
import org.gridlab.gridsphere.services.core.user.LoginService;
import org.gridlab.gridsphere.services.core.security.auth.LoginAuthModule;
import javax.servlet.UnavailableException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class LoginPortlet extends ActionPortlet {
public static final String LOGIN_ERROR_FLAG = "LOGIN_FAILED";
public static final Integer LOGIN_ERROR_UNKNOWN = new Integer(-1);
public void init(PortletConfig config) throws UnavailableException {
super.init(config);
DEFAULT_VIEW_PAGE = "doViewUser";
DEFAULT_CONFIGURE_PAGE = "doConfigModules";
}
public void initConcrete(PortletSettings settings) throws UnavailableException {
super.initConcrete(settings);
}
public void doViewUser(FormEvent event) throws PortletException {
log.debug("in LoginPortlet: doViewUser");
PortletRequest request = event.getPortletRequest();
User user = request.getUser();
request.setAttribute("user", user);
setNextState(request, "login/login.jsp");
}
public void doConfigModules(FormEvent event) throws PortletException {
log.debug("in LoginPortlet: doConfigure");
PortletRequest request = event.getPortletRequest();
LoginService loginService = (LoginService)getPortletConfig().getContext().getService(LoginService.class, request.getUser());
List supportedModules = loginService.getSupportedAuthModules();
List activeModules = loginService.getActiveAuthModules();
log.debug(supportedModules.size() + " " + activeModules.size());
request.setAttribute("activeModules", activeModules);
request.setAttribute("supportedModules", supportedModules);
setNextState(request, "login/configure.jsp");
}
public void doTitle(PortletRequest request, PortletResponse response) throws PortletException, IOException {
User user = request.getUser();
PrintWriter out = response.getWriter();
if (user instanceof GuestUser) {
out.println(getPortletSettings().getTitle(request.getLocale(), null));
} else {
getPortletConfig().getContext().include("/jsp/login/login_title.jsp", request, response);
}
/*
ResourceBundle resBundle = ResourceBundle.getBundle("Portlet", locale);
String welcome = resBundle.getString("LOGIN_SUCCESS");
out.println(welcome + ", " + user.getFullName());
*/
}
public void gs_login(FormEvent event) throws PortletException {
log.debug("in LoginPortlet: gs_login");
PortletRequest req = event.getPortletRequest();
String errorKey = (String)req.getAttribute(LoginPortlet.LOGIN_ERROR_FLAG);
System.err.println("in gs_login! errorkey=" + errorKey);
if (errorKey != null) {
FrameBean frame = event.getFrameBean("errorFrame");
frame.setKey(LoginPortlet.LOGIN_ERROR_FLAG);
frame.setStyle("error");
}
setNextState(req, "doViewUser");
}
public void configAuthModules(FormEvent event) throws PortletException {
PortletRequest req = event.getPortletRequest();
LoginService loginService = (LoginService)getConfig().getContext().getService(LoginService.class, req.getUser());
CheckBoxBean passCheck = event.getCheckBoxBean("passCheck");
CheckBoxBean ldapCheck = event.getCheckBoxBean("ldapCheck");
CheckBoxBean myproxyCheck = event.getCheckBoxBean("myproxyCheck");
List authModules = new ArrayList();
Iterator it = loginService.getSupportedAuthModules().iterator();
while (it.hasNext()) {
LoginAuthModule authModule = (LoginAuthModule)it.next();
String modName = authModule.getModuleName();
if (modName.equals("PASSWORD_AUTH_MODULE")) {
if (passCheck.isSelected()) {
log.debug("adding PASSWORD_AUTH_MODULE");
authModules.add(authModule);
}
}
if (modName.equals("LDAP_AUTH_MODULE")) {
if (ldapCheck.isSelected()) {
log.debug("adding LDAP_AUTH_MODULE");
authModules.add(authModule);
}
}
if (modName.equals("MYPROXY_AUTH_MODULE")) {
if (myproxyCheck.isSelected()) {
log.debug("adding MYPROXY_AUTH_MODULE");
authModules.add(authModule);
}
}
}
if (!authModules.isEmpty()) {
log.debug("auth modules not empty!");
loginService.setActiveAuthModules(authModules);
}
//setNextState(req, "login/configure.jsp");
}
public void configLdapModule(FormEvent event) throws PortletException {
TextFieldBean ldapHost = event.getTextFieldBean("ldapHost");
TextFieldBean baseDN = event.getTextFieldBean("baseDN");
LoginService loginService = (LoginService)getConfig().getContext().getService(LoginService.class, event.getPortletRequest().getUser());
Iterator it = loginService.getActiveAuthModules().iterator();
boolean isFound = false;
while (it.hasNext()) {
LoginAuthModule authModule = (LoginAuthModule)it.next();
String modName = authModule.getModuleName();
if (modName.equals("LDAP_AUTH_MODULE")) {
isFound = true;
String host = authModule.getEnvironmentVariable("LDAP_HOST");
ldapHost.setValue(host);
String base = authModule.getEnvironmentVariable("BASE_DN");
baseDN.setValue(base);
}
}
if (isFound) {
setNextState(event.getPortletRequest(), "login/module/configLDAPModule.jsp");
} else {
setNextState(event.getPortletRequest(), "login/module/moduleNotActive.jsp");
}
}
public void saveLdapModule(FormEvent event) throws PortletException {
log.debug("in saveLdapModule");
String ldapHost = event.getTextFieldBean("ldapHost").getValue();
String baseDN = event.getTextFieldBean("baseDN").getValue();
LoginService loginService = (LoginService)getConfig().getContext().getService(LoginService.class, event.getPortletRequest().getUser());
Iterator it = loginService.getActiveAuthModules().iterator();
List newModules = new ArrayList();
while (it.hasNext()) {
LoginAuthModule authModule = (LoginAuthModule)it.next();
String modName = authModule.getModuleName();
if (modName.equals("LDAP_AUTH_MODULE")) {
log.debug("Configuring LDAP auth module host: " + ldapHost + " base DN: " + baseDN);
authModule.setEnvironmentVariable("BASE_DN", baseDN);
authModule.setEnvironmentVariable("LDAP_HOST", ldapHost);
}
newModules.add(authModule);
}
log.debug("Saving active login auth modules");
loginService.setActiveAuthModules(newModules);
//setNextState(event.getPortletRequest(), "login/configure.jsp");
}
}
|
package ai.elimu.web.project;
import ai.elimu.dao.AppCategoryDao;
import ai.elimu.dao.AppCollectionDao;
import ai.elimu.dao.AppGroupDao;
import ai.elimu.dao.LicenseDao;
import ai.elimu.dao.ProjectDao;
import ai.elimu.model.Contributor;
import ai.elimu.model.enums.Environment;
import ai.elimu.model.project.AppCategory;
import ai.elimu.model.project.AppCollection;
import ai.elimu.model.project.AppGroup;
import ai.elimu.model.project.License;
import ai.elimu.model.project.Project;
import ai.elimu.web.context.EnvironmentContextLoaderListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* List custom projects.
* <p />
* Only projects where the current contributer is added as a manager will be listed.
*/
@Controller
@RequestMapping("/project")
public class ProjectListController {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private ProjectDao projectDao;
@Autowired
private AppCategoryDao appCategoryDao;
@Autowired
private AppGroupDao appGroupDao;
@Autowired
private AppCollectionDao appCollectionDao;
@Autowired
private LicenseDao licenseDao;
/**
* Redirect to list of projects.
*/
@RequestMapping(method = RequestMethod.GET)
public String handleRequest(Model model, HttpSession session) {
logger.info("handleRequest");
return "redirect:/project/list";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String handleListRequest(Model model, HttpSession session) {
logger.info("handleListRequest");
Contributor contributor = (Contributor) session.getAttribute("contributor");
List<Project> projects = projectDao.read(contributor);
if (EnvironmentContextLoaderListener.env == Environment.DEV) {
if (projects.isEmpty()) {
// To ease development, auto-generate Projects
projects = generateProjects(contributor);
}
}
model.addAttribute("projects", projects);
return "project/list";
}
/**
* Redirect to specific project.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String handleProjectRequest(Model model, @PathVariable Long id, HttpSession session) {
logger.info("handleProjectRequest");
return "redirect:/project/" + id + "/app-category/list";
}
private List<Project> generateProjects(Contributor contributor) {
logger.info("generateProjects");
List<Project> projects = new ArrayList<>();
Project project1 = new Project();
project1.setName("Project
project1.setManagers(Arrays.asList(contributor));
projectDao.create(project1);
projects.add(project1);
AppCategory appCategory1 = new AppCategory();
appCategory1.setName("App category
appCategoryDao.create(appCategory1);
List<AppCategory> appCategories = new ArrayList<>();
appCategories.add(appCategory1);
project1.setAppCategories(appCategories);
projectDao.update(project1);
AppGroup appGroup1 = new AppGroup();
appGroup1.setAppCategory(appCategory1);
appGroupDao.create(appGroup1);
List<AppGroup> appGroups = new ArrayList<>();
appGroups.add(appGroup1);
appCategory1.setAppGroups(appGroups);
appCategoryDao.update(appCategory1);
AppCollection appCollection1 = new AppCollection();
appCollection1.setName("App collection
appCollection1.setProject(project1);
appCollection1.setAppCategories(Arrays.asList(appCategory1));
appCollectionDao.create(appCollection1);
License license1 = new License();
license1.setAppCollection(appCollection1);
license1.setLicenseEmail("info@elimu.ai");
license1.setLicenseNumber("bddf-d8f4-2adf-a365");
license1.setFirstName("Test");
license1.setLastName("Contributor");
licenseDao.create(license1);
return projects;
}
}
|
package org.intermine.dwr;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.mail.MessagingException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.bag.TypeConverter;
import org.intermine.api.bag.UnknownBagTypeException;
import org.intermine.api.mines.FriendlyMineManager;
import org.intermine.api.mines.FriendlyMineQueryRunner;
import org.intermine.api.mines.Mine;
import org.intermine.api.profile.BagDoesNotExistException;
import org.intermine.api.profile.BagState;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileAlreadyExistsException;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.profile.SavedQuery;
import org.intermine.api.profile.TagManager;
import org.intermine.api.profile.UserAlreadyShareBagException;
import org.intermine.api.profile.UserNotFoundException;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebTable;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.search.SearchResults;
import org.intermine.api.search.SearchTarget;
import org.intermine.api.search.TagFilter;
import org.intermine.api.search.WebSearchable;
import org.intermine.api.tag.TagNames;
import org.intermine.api.tag.TagTypes;
import org.intermine.api.template.ApiTemplate;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplateSummariser;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.template.TemplateQuery;
import org.intermine.util.MailUtils;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.displayer.InterMineLinkGenerator;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.PortalHelper;
import org.intermine.web.logic.bag.BagConverter;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.profile.UpgradeBagList;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
* @author Daniela Butano
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
private static final Set<String> NON_WS_TAG_TYPES = new HashSet<String>(Arrays.asList(
TagTypes.CLASS, TagTypes.COLLECTION, TagTypes.REFERENCE));
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
String nameCopy = name.replaceAll("#039;", "'");
try {
// already a favourite. turning off.
if (isFavourite) {
AjaxServices.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type);
// not a favourite. turning on.
} else {
AjaxServices.addTag(TagNames.IM_FAVOURITE, nameCopy, type);
}
} catch (Exception e) {
processException(e);
}
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, ApiTemplate> templates = profile.getSavedTemplates();
TemplateQuery t = templates.get(templateName);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
try {
session.setAttribute("precomputing_" + templateName, "true");
executor.precomputeTemplate(t);
} catch (ObjectStoreException e) {
LOG.error("Error while precomputing", e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, ApiTemplate> templates = profile.getSavedTemplates();
ApiTemplate template = templates.get(templateName);
TemplateSummariser summariser = im.getTemplateSummariser();
try {
session.setAttribute("summarising_" + templateName, "true");
summariser.summarise(template);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!NameUtil.isValidName(newName)) {
return "<i>" + NameUtil.INVALID_NAME_MSG + "</i>";
}
if ("history".equals(type)) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if ("saved".equals(type)) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if ("bag".equals(type)) {
try {
profile.renameBag(name, newName);
} catch (IllegalArgumentException e) {
return "<i>" + name + " does not exist</i>";
} catch (ProfileAlreadyExistsException e) {
return "<i>" + newName + " already exists</i>";
}
} else if ("invalid.bag.type".equals(type)) {
try {
profile.fixInvalidBag(name, newName);
InterMineAPI im = SessionMethods.getInterMineAPI(session);
new Thread(new UpgradeBagList(profile, im.getBagQueryRunner()))
.start();
} catch (UnknownBagTypeException e) {
return "<i>" + e.getMessage() + "</i>";
} catch (ObjectStoreException e) {
return "<i>Error fixing type</i>";
}
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Generate a new API key for a given user.
* @param username the user to generate the key for.
* @return A new API key, or null if something untoward happens.
* @throws Exception an exception.
*/
public String generateApiKey(String username) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
return pm.generateApiKey(p);
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Delete a user's API key, thus disabling webservice access. A message "deleted"
* is returned to confirm success.
* @param username The user whose key we should delete.
* @return A confirmation string.
* @throws Exception if somethign bad happens
*/
public String deleteApiKey(String username)
throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
p.setApiKey(null);
return "deleted";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
Path path = query.makePath(pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
// setting to null removes the description
query.setDescription(prefixPath.getNoConstraintsString(), null);
} else {
query.setDescription(prefixPath.getNoConstraintsString(), descr);
}
if (descr == null) {
return null;
}
return descr.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
} catch (RuntimeException e) {
processException(e);
return null;
} catch (PathException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* This method gets a map of ids of elements that were in the past (during session) toggled and
* returns them in JSON
* @return JSON serialized to a String
* @throws JSONException
*/
public static String getToggledElements() {
HttpSession session = WebContextFactory.get().getSession();
WebState webState = SessionMethods.getWebState(session);
Collection<JSONObject> lists = new HashSet<JSONObject>();
try {
for (Map.Entry<String, Boolean> entry : webState.getToggledElements().entrySet()) {
JSONObject list = new JSONObject();
list.put("id", entry.getKey());
list.put("opened", entry.getValue().toString());
lists.add(list);
}
} catch (JSONException jse) {
LOG.error("Errors generating json objects", jse);
}
return lists.toString();
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
List<ResultsRow> results = (List) webResultsExecutor.summariseQuery(pathQuery,
summaryPath);
// Start the count of results
Query countQuery = webResultsExecutor.makeSummaryQuery(pathQuery, summaryPath);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>();
int rowCount = 0;
for (ResultsRow row : results) {
rowCount++;
if (rowCount > 10) {
break;
}
pageSizeResults.add(row);
}
return Arrays.asList(new Object[] {pageSizeResults, qid, new Integer(rowCount)});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript.
* <p>
* Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* <p>
* ie - search for "<code>me</code>":
* <pre>
* [
* [ "Some name", 0.123, "So<i>me</i> name" ],
* ...
* ]
* </pre>
*
* @param scope the scope (either Scope.GLOBAL or Scope.USER).
* @param type the type (from TagTypes).
* @param tags the tags to filter on.
* @param filterText the text to pass to Lucene.
* @param filterAction toggles favourites filter off and on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
final HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
final Profile profile = SessionMethods.getProfile(session);
final SearchRepository userRepository = profile.getSearchRepository();
final SearchTarget target = new SearchTarget(scope, type);
final SearchResults results;
try {
results = SearchResults.runLuceneSearch(filterText, target, userRepository);
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) {
aspectTags.add(tag);
} else {
if (profile.getUsername() != null) {
// Only allow filtering from registered users.
userTags.add(tag);
}
}
}
TagFilter aspects = new TagFilter(aspectTags, pm.getSuperuserProfile(), type);
TagFilter requiredTags = new TagFilter(userTags, profile, type);
List returnList = new ArrayList();
returnList.add(callId);
for (org.intermine.api.search.SearchResult sr: results) {
WebSearchable ws = sr.getItem();
if (SearchResults.isInvalidTemplate(ws)) {
continue;
}
if (!(aspects.hasAllTags(ws) && requiredTags.hasAllTags(ws))) {
continue;
}
returnList.add(sr.asList());
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
String pckName = im.getModel().getPackageName();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
TemplateManager templateManager = im.getTemplateManager();
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
int count = 0;
InterMineBag imBag = bagManager.getBag(profile, bagName);
List<ApiTemplate> conversionTemplates = templateManager.getConversionTemplates();
PathQuery pathQuery = TypeConverter.getConversionQuery(conversionTemplates,
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
count = webResultsExecutor.count(pathQuery);
return count;
} catch (Exception e) {
LOG.error("failed to get type converted counts", e);
return 0;
}
}
/**
* For a list and a converter, return types and related counts
*
* @param bagName the name of the bag
* @param converterName Java class that processes the data
* @return the number of converted objects
*/
public static String getCustomConverterCounts(String bagName, String converterName) {
try {
final HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final Profile profile = SessionMethods.getProfile(session);
final BagManager bagManager = im.getBagManager();
final InterMineBag imBag = bagManager.getBag(profile, bagName);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
final BagConverter bagConverter = PortalHelper.getBagConverter(im, webConfig,
converterName);
// should be ordered
Map<String, String> results = bagConverter.getCounts(profile, imBag);
List<JSONObject> jsonResults = new LinkedList<JSONObject>();
for (Map.Entry<String, String> entry : results.entrySet()) {
JSONObject organism = new JSONObject();
organism.put("name", entry.getKey());
organism.put("count", entry.getValue());
jsonResults.add(organism);
}
return jsonResults.toString();
} catch (Exception e) {
LOG.error("failed to get custom converter counts", e);
return null;
}
}
/**
* used on REPORT page
*
* For a gene, generate links to other intermines. Include gene and orthologues.
*
* Returns NULL if no values found. It's possible that the identifier in the local mine will
* match more than one entry in the remote mine but this will be handled by the portal of the
* remote mine.
*
* @param mineName name of mine to query
* @param organisms gene.organism
* @param identifiers identifiers for gene
* @return the links to friendly intermines
*/
public static String getFriendlyMineLinks(String mineName, String organisms,
String identifiers) {
if (StringUtils.isEmpty(mineName) || StringUtils.isEmpty(organisms)
|| StringUtils.isEmpty(identifiers)) {
return null;
}
final HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager fmm = FriendlyMineManager.getInstance(im, webProperties);
InterMineLinkGenerator linkGen = null;
Constructor<?> constructor;
try {
Class<?> clazz = TypeUtil.instantiate(
"org.intermine.bio.web.displayer.FriendlyMineLinkGenerator");
constructor = clazz.getConstructor(new Class[] {});
linkGen = (InterMineLinkGenerator) constructor.newInstance(new Object[] {});
} catch (Exception e) {
LOG.error("Failed to instantiate FriendlyMineLinkGenerator because: " + e);
return null;
}
Collection<JSONObject> results = linkGen.getLinks(fmm, mineName, organisms, identifiers);
if (results == null || results.isEmpty()) {
return null;
}
return results.toString();
}
/**
* used on REPORT page
*
* For a gene, display pathways found in other mines for orthologous genes
*
* @param mineName mine to query
* @param orthologues list of genes to query for
* @return the links to friendly intermines
*/
public static String getFriendlyMinePathways(String mineName, String orthologues) {
if (StringUtils.isEmpty(orthologues)) {
return null;
}
Mine mine;
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager linkManager = FriendlyMineManager.getInstance(im, webProperties);
mine = linkManager.getMine(mineName);
if (mine == null || mine.getReleaseVersion() == null) {
// mine is dead
return null;
}
final String xmlQuery = getXMLQuery("FriendlyMinesPathways.xml", orthologues);
try {
JSONObject results = FriendlyMineQueryRunner.runJSONWebServiceQuery(mine, xmlQuery);
if (results == null) {
LOG.error("Couldn't query " + mine.getName() + " for pathways");
return null;
}
results.put("mineURL", mine.getUrl());
return results.toString();
} catch (IOException e) {
LOG.error("Couldn't query " + mine.getName() + " for pathways", e);
return null;
} catch (JSONException e) {
LOG.error("Error adding Mine URL to pathways results", e);
return null;
} catch (Throwable t) {
LOG.error(t);
return null;
}
}
private static String getXMLQuery(String filename, Object... positionalArgs) {
try {
return String.format(
IOUtils.toString(
AjaxServices.class.getResourceAsStream(filename)), positionalArgs);
} catch (IOException e) {
LOG.error(e);
throw new RuntimeException("Could not read " + filename, e);
} catch (NullPointerException npe) {
LOG.error(npe);
throw new RuntimeException(filename + " not found", npe);
} catch (Throwable e) {
LOG.error(e);
throw new RuntimeException("Unexpected exception", e);
}
}
/**
* Return list of disease ontology terms associated with list of provided rat genes. Returns
* JSONObject as string with ID (intermine ID) and name (ontologyTerm.name)
*
* @param orthologues list of rat genes
* @return JSONobject.toString of JSON object
*/
@SuppressWarnings("unchecked")
public static String getRatDiseases(String orthologues) {
if (StringUtils.isEmpty(orthologues)) {
return null;
}
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager linkManager = FriendlyMineManager.getInstance(im, webProperties);
Mine mine = linkManager.getMine("RatMine");
HashMap<String, Object> map = new HashMap<String, Object>();
if (mine == null || mine.getReleaseVersion() == null) {
// mine is dead
map.put("status", "offline");
return new JSONObject(map).toString();
}
final String xmlQuery = getXMLQuery("RatDiseases.xml", orthologues);
try {
JSONObject results = FriendlyMineQueryRunner.runJSONWebServiceQuery(mine, xmlQuery);
if (results != null) {
results.put("mineURL", mine.getUrl());
results.put("status", "online");
return results.toString();
}
} catch (IOException e) {
LOG.error("Couldn't query ratmine for diseases", e);
} catch (JSONException e) {
LOG.error("Couldn't process ratmine disease results", e);
}
return null;
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
bagName = bagName.trim();
// TODO get message text from the properties file
if ("".equals(bagName)) {
return "You cannot save a list with a blank name";
}
if (!NameUtil.isValidName(bagName)) {
return TagManager.INVALID_NAME_MSG;
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
if (bagManager.getGlobalBag(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new list
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = SessionMethods.getProfile(session);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if ("delete".equals(operation)) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(), selectedBags[i]));
if (queries.size() > 0) {
// TODO the javascript method relies on the content of this message.
// which is dumb and should be fixed. in the meantime, don't change this.
final String msg = "You are trying to delete the list: `"
+ selectedBags[i] + "`, which is used by these queries: "
+ queries + ". Select OK to delete the list and queries or Cancel "
+ "to cancel this operation.";
return msg;
}
}
} else if (!"copy".equals(operation)) {
Properties properties = SessionMethods.getWebProperties(servletContext);
String defaultName = properties.getProperty("lists.input.example");
if (bagName.equalsIgnoreCase(defaultName)) {
return "New list name is required";
} else if (!NameUtil.isValidName(bagName)) {
return NameUtil.INVALID_NAME_MSG;
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
private static List<String> queriesThatMentionBag(Map<String, SavedQuery> savedQueries,
String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator<String> i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
/**
* AJAX request - reorder view.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
List<String> view = SessionMethods.getEditingView(session);
ArrayList<String> newView = new ArrayList<String>();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
PathQuery query = SessionMethods.getQuery(session);
query.clearView();
query.addViews(newView);
}
/**
* AJAX request - reorder the constraints.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorderConstraints(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
PathQuery query = SessionMethods.getQuery(session);
if (query instanceof TemplateQuery) {
TemplateQuery template = (TemplateQuery) query;
for (int index = 0; index < newOrderList.size() - 1; index++) {
String newi = newOrderList.get(index);
int oldi = oldOrderList.indexOf(newi);
if (index != oldi) {
List<PathConstraint> editableConstraints =
template.getModifiableEditableConstraints();
PathConstraint editableConstraint = editableConstraints.remove(oldi);
editableConstraints.add(index, editableConstraint);
template.setEditableConstraints(editableConstraints);
break;
}
}
}
}
/**
* Add a Node from the sort order
* @param path the Path as a String
* @param direction the direction to sort by
* @exception Exception if the application business logic throws
*/
public void addToSortOrder(String path, String direction)
throws Exception {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = SessionMethods.getQuery(session);
OrderDirection orderDirection = OrderDirection.ASC;
if ("DESC".equals(direction.toUpperCase())) {
orderDirection = OrderDirection.DESC;
}
query.clearOrderBy();
query.addOrderBy(path, orderDirection);
}
/**
* Work as a proxy for fetching remote file (RSS)
* @param rssURL the url
* @return String representation of a file
*/
public static String getNewsPreview(String rssURL) {
try {
URL url = new URL(rssURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuffer sb = new StringBuffer();
// append to string buffer
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
} catch (MalformedURLException e) {
return "";
} catch (IOException e) {
return "";
}
}
/**
* Adds tag and assures that there is only one tag for this combination of tag name, tagged
* Object and type.
* @param tag tag name
* @param taggedObject object id that is tagged by this tag
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String addTag(String tag, String taggedObject, String type) {
String tagName = tag;
LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:"
+ taggedObject + " type: " + type);
if (StringUtils.isBlank(tagName)) {
LOG.error("Adding tag failed");
return "tag must not be blank";
}
if (StringUtils.isBlank(taggedObject)) {
LOG.error("Adding tag failed");
return "object to tag must not be blank";
}
try {
final HttpServletRequest request = getRequest();
final Profile profile = getProfile(request);
final InterMineAPI im = SessionMethods.getInterMineAPI(request);
tagName = tagName.trim();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
if (tagExists(tagName, taggedObject, type)) {
return "Already tagged with this tag.";
}
TagManager tagManager = getTagManager();
BagManager bm = im.getBagManager();
TemplateManager tm = im.getTemplateManager();
if (NON_WS_TAG_TYPES.contains(type)) {
if (TagTypes.CLASS.equals(type)) {
ClassDescriptor cd = im.getModel().getClassDescriptorByName(taggedObject);
tagManager.addTag(tagName, cd, profile);
} else {
String[] bits = taggedObject.split("\\.");
ClassDescriptor cd = im.getModel().getClassDescriptorByName(bits[0]);
FieldDescriptor fd = cd.getFieldDescriptorByName(bits[1]);
if (fd.isCollection() || fd.isReference()) {
tagManager.addTag(tagName, (ReferenceDescriptor) fd, profile);
}
}
} else {
WebSearchable ws = null;
if (TagTypes.BAG.equals(type)) {
ws = bm.getBag(profile, taggedObject);
} else if (TagTypes.TEMPLATE.equals(type)) {
ws = tm.getUserOrGlobalTemplate(profile, taggedObject);
}
if (ws == null) {
throw new RuntimeException("Could not find " + type + " " + taggedObject);
} else {
tagManager.addTag(tagName, ws, profile);
}
}
return "ok";
}
LOG.error("Adding tag failed: tag='" + tag + "', taggedObject='" + taggedObject
+ "', type='" + type + "'");
return "Adding tag failed.";
} catch (TagManager.TagNamePermissionException e) {
LOG.error("Adding tag failed", e);
return e.getMessage();
} catch (TagManager.TagNameException e) {
LOG.error("Adding tag failed", e);
return e.getMessage();
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return "Adding tag failed.";
}
}
/**
* Deletes tag.
* @param tagName tag name
* @param tagged id of tagged object
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String deleteTag(String tagName, String tagged, String type) {
LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:"
+ tagged + " type: " + type);
try {
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = getProfile(request);
TagManager manager = im.getTagManager();
BagManager bm = im.getBagManager();
if (NON_WS_TAG_TYPES.contains(type)) {
if (TagTypes.CLASS.equals(type)) {
ClassDescriptor cd = im.getModel().getClassDescriptorByName(tagged);
manager.deleteTag(tagName, cd, profile);
} else {
String[] bits = tagged.split("\\.");
ClassDescriptor cd = im.getModel().getClassDescriptorByName(bits[0]);
FieldDescriptor fd = cd.getFieldDescriptorByName(bits[1]);
if (fd.isCollection() || fd.isReference()) {
manager.deleteTag(tagName, (ReferenceDescriptor) fd, profile);
}
}
return "ok";
} else {
WebSearchable ws = null;
if (TagTypes.BAG.equals(type)) {
ws = bm.getUserBag(profile, tagged);
} else if (TagTypes.TEMPLATE.equals(type)) {
ws = profile.getTemplate(tagged);
}
if (ws == null) {
throw new RuntimeException("Could not find " + type + " " + tagged);
}
manager.deleteTag(tagName, ws, profile);
}
return "ok";
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return "Deleting tag failed.";
}
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param type tag type
* @return tags
*/
public static Set<String> getTags(String type) {
final HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
final TagManager tagManager = im.getTagManager();
final Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getUserTagNames(type, profile.getUsername());
}
return new TreeSet<String>();
}
/**
* Returns all tags by which is specified object tagged.
* @param type tag type
* @param tagged id of tagged object
* @return tags
*/
public static Set<String> getObjectTags(String type, String tagged) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getObjectTagNames(tagged, type, profile.getUsername());
}
return new TreeSet<String>();
}
private static boolean tagExists(String tag, String taggedObject, String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
String userName = getProfile(request).getUsername();
return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag);
}
private static Profile getProfile(HttpServletRequest request) {
return SessionMethods.getProfile(request.getSession());
}
/**
* Return the single use API key for the current profile
* @return the single use APi key
*/
public static String getSingleUseKey() {
HttpServletRequest request = getRequest();
Profile profile = SessionMethods.getProfile(request.getSession());
return profile.getSingleUseKey();
}
/**
* Return the request retrieved from the web contest
* @return the request
*/
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
/**
* Return the TagManager
* @return the tag manager
*/
private static TagManager getTagManager() {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
return im.getTagManager();
}
/**
* Set the constraint logic on a query to be the given expression.
*
* @param expression the constraint logic for the query
* @return messages to display in the jsp page
* @throws PathException if the query is invalid
*/
public static String setConstraintLogic(String expression) throws PathException {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
query.setConstraintLogic(expression);
List<String> messages = query.fixUpForJoinStyle();
StringBuffer messagesToDisplay = new StringBuffer();
for (String message : messages) {
messagesToDisplay.append(message);
//SessionMethods.recordMessage(message, session);
}
return messagesToDisplay.toString();
}
/**
* Get the grouped constraint logic
* @return a list representing the grouped constraint logic
*/
public static String getConstraintLogic() {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
return (query.getConstraintLogic());
}
/**
* @param suffix string of input before request for more results
* @param wholeList whether or not to show the entire list or a truncated version
* @param field field name from the table for the lucene search
* @param className class name (table in the database) for lucene search
* @return an array of values for this classname.field
*/
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = SessionMethods.getAutoCompleter(servletContext);
ac.createRAMIndex(className + "." + field);
// swap "-" for spaces, ticket #2357
suffix = suffix.replace("-", " ");
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
/**
* This method gets the latest bags from the session (SessionMethods) and returns them in JSON
* @return JSON serialized to a String
* @throws JSONException json exception
*/
@SuppressWarnings("unchecked")
public String getSavedBagStatus() throws JSONException {
HttpSession session = WebContextFactory.get().getSession();
@SuppressWarnings("unchecked")
Map<String, InterMineBag> savedBags = SessionMethods.getProfile(session).getSavedBags();
// this is where my lists go
Collection<JSONObject> lists = new HashSet<JSONObject>();
try {
for (Map.Entry<String, InterMineBag> entry : savedBags.entrySet()) {
InterMineBag bag = entry.getValue();
// save to the resulting JSON object only if these are 'actionable' lists
if (bag.isCurrent() || bag.isToUpgrade()) {
JSONObject list = new JSONObject();
list.put("name", entry.getKey());
list.put("status", bag.getState());
if (bag.isCurrent()) {
try {
list.put("size", bag.getSize());
} catch (ObjectStoreException os) {
LOG.error("Problems retrieving size of bag " + bag.getName(), os);
}
} else {
list.put("size", 0);
}
lists.add(list);
}
}
} catch (JSONException jse) {
LOG.error("Errors generating json objects", jse);
}
return lists.toString();
}
/**
* Update with the value given in input the field of the previous template
* saved into the session
* @param field the field to update
* @param value the value
*/
public void updateTemplate(String field, String value) {
HttpSession session = WebContextFactory.get().getSession();
boolean isNewTemplate = (session.getAttribute(Constants.NEW_TEMPLATE) != null)
? true : false;
TemplateQuery templateQuery = (TemplateQuery) SessionMethods.getQuery(session);
if (!isNewTemplate && session.getAttribute(Constants.PREV_TEMPLATE_NAME) == null) {
session.setAttribute(Constants.PREV_TEMPLATE_NAME, templateQuery.getName());
}
try {
PropertyUtils.setSimpleProperty(templateQuery, field, value);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Share the bag given in input with the user which userName is input and send email
* @param userName the user which the bag has to be shared with
* @param bagName the bag name to share
* @return 'ok' string if succeeded else error string
*/
public String addUserToShareBag(String userName, String bagName) {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
if (profile.getUsername().equals(userName)) {
return "The user already shares the bag.";
}
try {
bagManager.shareBagWithUser(bagName, profile.getUsername(), userName);
} catch (UserNotFoundException e1) {
return "User not found.";
} catch (UserAlreadyShareBagException e2) {
return "The user already shares the bag.";
}
Properties webProperties = SessionMethods.getWebProperties(session.getServletContext());
InterMineBag bag = profile.getSavedBags().get(bagName);
try {
MailUtils.emailSharingList(userName, profile.getUsername(), bag, webProperties);
} catch (Exception ex) {
LOG.warn("Problems sending sharing list mail.", ex);
}
return "ok";
}
/**
* Un-share the bag given in input with the user which userName is input
* @param userName the user which the bag has to be un-shared with
* @param bagName the bag name to un-share
* @return 'ok' string if succeeded else error string
*/
public String deleteUserToShareBag(String userName, String bagName) {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
try {
bagManager.unshareBagWithUser(bagName, profile.getUsername(), userName);
} catch (UserNotFoundException unfe) {
return "User not found.";
} catch (BagDoesNotExistException bnee) {
return "That list does not exist.";
}
return "ok";
}
/**
* Return the list of userssharign the bag in input
* @param bagName the bag name that the users share
* @return the list of users
*/
public Collection<String> getUsersSharingBag(String bagName) {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
return bagManager.getUsersSharingBag(bagName, profile.getUsername());
}
}
|
package vorquel.mod.simpleskygrid.helper;
import net.minecraft.nbt.*;
import vorquel.mod.simpleskygrid.SimpleSkyGrid;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NBTString {
public static void sanitizeNBT(NBTTagCompound tag) {
tag.removeTag("x");
tag.removeTag("y");
tag.removeTag("z");
}
public static void localizeNBT(NBTTagCompound tag, int x, int y, int z) {
tag.setInteger("x", x);
tag.setInteger("y", y);
tag.setInteger("z", z);
}
public static NBTTagCompound getNBTFromString(String in) {
ArrayList<Token> tokens = tokenize(in);
return readTokens(tokens);
}
private static ArrayList<Token> tokenize(String in) {
String goodIn = in.replaceAll("\\s+", "");
Pattern pattern = Pattern.compile("[:,\\{\\}\\]]|[bi]?\\[|[bsil]-?(0|[1-9]\\d*)|[fd]-?(0?|[1-9]\\d*)\\.\\d*|\".+?\"");
Matcher matcher = pattern.matcher(goodIn);
ArrayList<Token> out = new ArrayList<Token>();
try {
int end = 0;
while(matcher.find()) {
end = matcher.end();
String temp = goodIn.substring(matcher.start(), end);
if(temp.equals(":"))
out.add(new Token(Type.COLON));
else if(temp.equals(","))
out.add(new Token(Type.COMMA));
else if(temp.equals("{"))
out.add(new Token(Type.LEFT_BRACE));
else if(temp.equals("}"))
out.add(new Token(Type.RIGHT_BRACE));
else if(temp.equals("["))
out.add(new Token(Type.LEFT_SQUARE));
else if(temp.equals("]"))
out.add(new Token(Type.RIGHT_SQUARE));
else if(temp.equals("b["))
out.add(new Token(Type.OPEN_BYTE_ARRAY));
else if(temp.equals("i["))
out.add(new Token(Type.OPEN_INT_ARRAY));
else if(temp.startsWith("b"))
out.add(new Token(Type.LIT_BYTE, Byte.decode(temp.substring(1))));
else if(temp.startsWith("s"))
out.add(new Token(Type.LIT_SHORT, Short.decode(temp.substring(1))));
else if(temp.startsWith("i"))
out.add(new Token(Type.LIT_INT, Integer.decode(temp.substring(1))));
else if(temp.startsWith("l"))
out.add(new Token(Type.LIT_LONG, Long.decode(temp.substring(1))));
else if(temp.startsWith("f"))
out.add(new Token(Type.LIT_FLOAT, Float.valueOf(temp.substring(1))));
else if(temp.startsWith("d"))
out.add(new Token(Type.LIT_DOUBLE, Double.valueOf(temp.substring(1))));
else if(temp.startsWith("\"") && temp.endsWith("\""))
out.add(new Token(Type.LIT_STRING, temp.substring(1, temp.length() - 1)));
else
throw new IllegalArgumentException("type1");
}
if(end != goodIn.length())
throw new IllegalArgumentException("type2");
} catch(NumberFormatException e) {
SimpleSkyGrid.logger.error("Syntax error in NBT data: malformed numeric data.");
out.clear();
out.add(new Token(Type.LEFT_BRACE));
out.add(new Token(Type.RIGHT_BRACE));
} catch(IllegalArgumentException e) {
if(e.getMessage().equals("type1")) {
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("Go complain to Vorquel. His NBT parser broke");
SimpleSkyGrid.logger.fatal("Input string could not be properly tokenized");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
} else if(e.getMessage().equals("type2")) {
SimpleSkyGrid.logger.error("Syntax error in NBT data: unrecognized tokens.");
} else {
SimpleSkyGrid.logger.fatal("Unrecognized error in NBT data.");
}
out.clear();
out.add(new Token(Type.LEFT_BRACE));
out.add(new Token(Type.RIGHT_BRACE));
}
return out;
}
private static NBTTagCompound readTokens(ArrayList<Token> tokens) {
if(tokens.isEmpty())
return null;
Iterator<Token> iterator = tokens.iterator();
}
public static String getStringFromNBT(NBTTagCompound in) {
StringBuilder out = new StringBuilder();
appendCompound(out, in);
return out.toString();
}
private static void appendTag(StringBuilder out, NBTBase in) {
switch(in.getId()) {
case 1: appendByte( out, (NBTTagByte) in); break;
case 2: appendShort( out, (NBTTagShort) in); break;
case 3: appendInt( out, (NBTTagInt) in); break;
case 4: appendLong( out, (NBTTagLong) in); break;
case 5: appendFloat( out, (NBTTagFloat) in); break;
case 6: appendDouble( out, (NBTTagDouble) in); break;
case 7: appendByteArray(out, (NBTTagByteArray) in); break;
case 8: appendString( out, (NBTTagString) in); break;
case 9: appendList( out, (NBTTagList) in); break;
case 10: appendCompound( out, (NBTTagCompound) in); break;
case 11: appendIntArray( out, (NBTTagIntArray) in); break;
}
}
private static void appendByte(StringBuilder out, NBTTagByte in) {
out.append('b');
out.append(in.func_150290_f());
}
private static void appendShort(StringBuilder out, NBTTagShort in) {
out.append('s');
out.append(in.func_150289_e());
}
private static void appendInt(StringBuilder out, NBTTagInt in) {
out.append('i');
out.append(in.func_150287_d());
}
private static void appendLong(StringBuilder out, NBTTagLong in) {
out.append('l');
out.append(in.func_150291_c());
}
private static void appendFloat(StringBuilder out, NBTTagFloat in) {
out.append('f');
out.append(in.func_150288_h());
}
private static void appendDouble(StringBuilder out, NBTTagDouble in) {
out.append('d');
out.append(in.func_150286_g());
}
private static void appendByteArray(StringBuilder out, NBTTagByteArray in) {
out.append("b[");
for(byte b : in.func_150292_c()) {
out.append(b);
out.append(',');
}
out.setCharAt(out.length() - 1, ']');
}
private static void appendString(StringBuilder out, NBTTagString in) {
out.append('"');
out.append(in.func_150285_a_());
out.append('"');
}
private static void appendList(StringBuilder out, NBTTagList in) {
try {
Field field = NBTTagList.class.getDeclaredField("tagList");
field.setAccessible(true);
List<NBTBase> tags = (List<NBTBase>)field.get(in);
out.append('[');
for(NBTBase tag : tags) {
appendTag(out, tag);
out.append(',');
}
out.setCharAt(out.length() - 1, ']');
} catch(Exception e) {
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("Go complain to Vorquel. His NBT parser broke");
SimpleSkyGrid.logger.fatal("His reflection didnt account for obfuscation");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
SimpleSkyGrid.logger.fatal("********************************************");
}
}
private static void appendCompound(StringBuilder out, NBTTagCompound in) {
out.append('{');
for(String key : (Set<String>)in.func_150296_c()) {
out.append('"');
out.append(key);
out.append('"');
out.append(':');
appendTag(out, in.getTag(key));
out.append(',');
}
out.setCharAt(out.length() - 1, '}');
}
private static void appendIntArray(StringBuilder out, NBTTagIntArray in) {
out.append("i[");
for(int i : in.func_150302_c()) {
out.append(i);
out.append(',');
}
out.setCharAt(out.length()-1, ']');
}
private static class Token {
public Type type;
public Object value;
public Token(Type type, Object value) {
this.type = type;
this.value = value;
}
public Token(Type type) {
this(type, null);
}
}
private enum Type {
LIT_BYTE, LIT_SHORT, LIT_INT, LIT_LONG, LIT_FLOAT, LIT_DOUBLE, LIT_STRING, COLON, COMMA,
LEFT_BRACE, RIGHT_BRACE, LEFT_SQUARE, RIGHT_SQUARE, OPEN_BYTE_ARRAY, OPEN_INT_ARRAY
}
}
|
package org.jetbrains.plugins.scala.compiler;
import com.intellij.compiler.OutputParser;
import com.intellij.openapi.compiler.CompilerMessageCategory;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.jetbrains.annotations.NonNls;
import static org.jetbrains.plugins.scala.compiler.ScalacOutputParser.MESSAGE_TYPE.*;
import java.io.File;
import java.util.ArrayList;
/**
* @author ilyas
*/
class ScalacOutputParser extends OutputParser {
@NonNls
private static final String ourErrorMarker = " error:";
@NonNls
private static final String ourWarningMarker = " warning:";
private static final String ourInfoMarkerStart = "[";
private static final String ourInfoMarkerEnd = "]";
@NonNls
private static final String ourWroteMarker = "wrote ";
private static final String ourColumnMarker = "^";
@NonNls
private static final String ourParsingMarker = "parsing";
@NonNls
private static final String ourScalaInternalErrorMsg = "Scalac internal error";
// Phases
@NonNls
private static final String PHASE = "running phase ";
private boolean mustProcessMsg = false;
private boolean fullCrash = false;
private boolean stopProcessing = false;
private int myMsgColumnMarker;
private MESSAGE_TYPE myMsgType = PLAIN;
@NonNls
private static final String PARSER_ON = "parser on ";
private ArrayList<String> myWrittenList = new ArrayList<String>();
static enum MESSAGE_TYPE {
ERROR, WARNING, PLAIN
}
private Integer myLineNumber;
private String myMessage;
private String myUrl;
@Override
public boolean processMessageLine(Callback callback) {
final String line = callback.getNextLine();
if (line == null) {
//ensure that all "written" files are really written
for (String s : myWrittenList) {
callback.fileGenerated(s);
}
myWrittenList.clear();
return false;
}
String text = line.trim();
if (fullCrash && text.length( ) > 0) {
callback.message(CompilerMessageCategory.ERROR, text, "", 0, 0);
return true;
}
if (text.endsWith("\r\n")) text = text.substring(0, text.length() - 2);
if (text.startsWith(ourScalaInternalErrorMsg)) {
callback.message(CompilerMessageCategory.ERROR, text, "", 0, 0);
fullCrash = true;
return true;
}
// Add error message to output
if (myMessage != null && stopMsgProcessing(text) && (mustProcessMsg || stopProcessing)) {
myMsgColumnMarker = myMsgColumnMarker > 0 ? myMsgColumnMarker : 1;
if (myMsgType == ERROR) {
callback.message(CompilerMessageCategory.ERROR, myMessage, myUrl, myLineNumber, myMsgColumnMarker);
} else if (myMsgType == WARNING) {
callback.message(CompilerMessageCategory.WARNING, myMessage, myUrl, myLineNumber, myMsgColumnMarker);
}
myMessage = null;
myMsgType = PLAIN;
mustProcessMsg = false;
stopProcessing = false;
}
if (text.indexOf(ourErrorMarker) > 0) { // new error occurred
processErrorMesssage(text, text.indexOf(ourErrorMarker), ERROR, callback);
} else if (text.indexOf(ourWarningMarker) > 0) {
processErrorMesssage(text, text.indexOf(ourWarningMarker), WARNING, callback);
} else if (!text.startsWith(ourInfoMarkerStart)) { // continuing process [error | warning] message
if (mustProcessMsg) {
if (ourColumnMarker.equals(text.trim())) {
myMsgColumnMarker = line.indexOf(ourColumnMarker) + 1;
stopProcessing = true;
} else if (myMessage != null) {
if (myMsgType != WARNING) {
myMessage += "\n" + text;
}
} else {
mustProcessMsg = false;
}
}
} else { //verbose compiler output
mustProcessMsg = false;
if (text.endsWith(ourInfoMarkerEnd)) {
String info = text.substring(ourInfoMarkerStart.length(), text.length() - ourInfoMarkerEnd.length());
if (info.startsWith(ourParsingMarker)) { //parsing
callback.setProgressText(info);
} else if (info.startsWith(PHASE)) { // typechecker phase
if (info.startsWith(PHASE + PARSER_ON)) {
callback.fileProcessed(info.substring(info.indexOf(PARSER_ON) + PARSER_ON.length()));
}
callback.setProgressText(info);
} else if (info.startsWith(ourWroteMarker)) {
callback.setProgressText(info);
String outputPath = info.substring(ourWroteMarker.length());
final String path = outputPath.replace(File.separatorChar, '/');
// callback.fileGenerated(path);
myWrittenList.add(path);
}
}
}
return true;
}
private boolean stopMsgProcessing(String text) {
return text.startsWith(ourInfoMarkerStart) && !text.trim().equals(ourColumnMarker) ||
text.indexOf(ourErrorMarker) > 0 ||
text.indexOf(ourWarningMarker) > 0 ||
stopProcessing;
}
/*
Collect information about error occurrence
*/
private void processErrorMesssage(String text, int errIndex, MESSAGE_TYPE msgType, Callback callback) {
String errorPlace = text.substring(0, errIndex);
if (errorPlace.endsWith(":"))
errorPlace = errorPlace.substring(0, errorPlace.length() - 1); //hack over compiler output
int j = errorPlace.lastIndexOf(':');
if (j > 0) {
myUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, errorPlace.substring(0, j).replace(File.separatorChar, '/'));
try {
myLineNumber = Integer.valueOf(errorPlace.substring(j + 1, errorPlace.length()));
myMessage = text.substring(errIndex + 1).trim();
mustProcessMsg = true;
myMsgType = msgType;
} catch (NumberFormatException e) {
callback.message(CompilerMessageCategory.INFORMATION, "", text, -1, -1);
myMessage = null;
mustProcessMsg = false;
myMsgType = PLAIN;
}
} else {
callback.message(CompilerMessageCategory.INFORMATION, "", text, -1, -1);
myMsgType = PLAIN;
}
}
}
|
package main.java.author.view.tabs.wave_editor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import main.java.author.controller.TabController;
import main.java.author.controller.tabbed_controllers.EnemyController;
import main.java.author.controller.tabbed_controllers.WaveController;
import main.java.author.util.ArrayUtil;
import main.java.author.util.JTableUtil;
import main.java.author.view.components.ColumnRemovableTableModel;
import main.java.author.view.tabs.EditorTab;
import main.java.schema.WaveSpawnSchema;
/**
* Used in the authoring environment to specify attributes of the wave
*/
public class WaveEditorTab extends EditorTab {
private static final String WAVE_STRING = "Waves";
private List<WaveSpawnSchema> myWaves;
private JButton removeWaveButton;
private String[] columnNames = {};
private Object[][] data = {};
private JTable table;
private ColumnRemovableTableModel tableModel;
private WaveTabContentCreator tabCreator = new WaveTabContentCreator();
/**
* @param tabController
* Constructor for the WaveEditorTab
*/
public WaveEditorTab(TabController tabController) {
super(tabController);
add(tabCreator.createWaveEditorContent(), BorderLayout.CENTER);
}
private void addNewEnemyColumn(String columnName) {
List<Integer> zeroesColumnList = new ArrayList<Integer>();
for (int i = 0; i < tableModel.getRowCount(); i++) {
zeroesColumnList.add(0);
}
tableModel.addColumn(columnName, zeroesColumnList.toArray());
}
private void updateWaveColumn() {
for (int i = 0; i < tableModel.getRowCount(); i++) {
int rowNum = i + 1;
tableModel.setValueAt("Wave " + rowNum, i, 0);
}
}
/**
* Updates the Enemy List in the table every time a new enemy is added in
* EnemyEditorTab
*/
public void updateEnemyList() {
WaveController waveController = (WaveController) myController;
String[] newColumns = waveController.getEnemyNames();
String[] oldColumns = JTableUtil.getColumnNames(tableModel);
List<String> columnsToAdd = ArrayUtil.getElementsToAdd(newColumns,
oldColumns, WAVE_STRING);
List<String> columnsToRemove = ArrayUtil.getElementsToRemove(
newColumns, oldColumns, WAVE_STRING);
for (String columnToAdd : columnsToAdd) {
addNewEnemyColumn(columnToAdd);
}
for (String columnToRemove : columnsToRemove) {
tableModel.removeColumnAndData(table, JTableUtil
.getColumnIndexFromName(tableModel, columnToRemove));
}
}
@Override
public void saveTabData() {
// TODO CODY
}
/**
* Creates the content of the Wave Editor Tab
*/
private class WaveTabContentCreator {
// Need to refactor all of the action listeners in the Button Maker
// class
/**
* @return Creates the panel with all of the Wave Editor Content
*/
public JComponent createWaveEditorContent() {
ButtonMaker buttonMaker = new ButtonMaker();
JPanel content = new JPanel(new BorderLayout());
content.add(createTable(), BorderLayout.WEST);
content.add(buttonMaker.makeButtons(), BorderLayout.EAST);
return content;
}
/**
* @return Creates a table used to specify the attributes of each wave
*/
public JComponent createTable() {
WaveController waveController = (WaveController) myController;
columnNames = waveController.getEnemyNames();
String[] columnNamesAndWave = new String[columnNames.length + 1];
columnNamesAndWave[0] = WAVE_STRING;
for (int i = 0; i < columnNames.length; i++) {
columnNamesAndWave[i + 1] = columnNames[i];
}
tableModel = new ColumnRemovableTableModel(data, columnNamesAndWave){
public boolean isCellEditable(int row, int col){
if(col == 0){
return false;
}
return true;
}
};
table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
removeWaveButton.setEnabled(false);
}
}, 100);
}
@Override
public void focusGained(FocusEvent e) {
removeWaveButton.setEnabled(true);
}
});
JScrollPane sp = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp.setPreferredSize(new Dimension(1000, 550));
return sp;
}
private class ButtonMaker {
/**
* @return Makes a JPanel that contains all of the buttons used by
* the Wave Editor Tab
*/
private JComponent makeButtons() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(makeAddNewWaveButton(), BorderLayout.NORTH);
panel.add(makeRemoveMostRecentWaveButton(), BorderLayout.CENTER);
panel.add(makeRemoveWaveButton(), BorderLayout.CENTER);
panel.add(makeClearAllWavesButton(), BorderLayout.SOUTH);
panel.add(makeAddEnemyColumnTestButton(), BorderLayout.SOUTH);
return panel;
}
private JComponent makeAddEnemyColumnTestButton() {
JButton addEnemyColumn = new JButton("Add Enemy");
addEnemyColumn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WaveController controller = (WaveController) myController;
controller.shiftToEnemyTab();
}
});
return addEnemyColumn;
}
/**
* @return Makes a button that adds a new wave to the table
*/
private JComponent makeAddNewWaveButton() {
JButton addNewWaveButton = new JButton("Add New Wave");
addNewWaveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ColumnRemovableTableModel model = (ColumnRemovableTableModel) table
.getModel();
int newWaveNum = tableModel.getRowCount() + 1;
List<Object> zeroesRowList = new ArrayList<Object>();
for (int i = 0; i < tableModel.getColumnCount(); i++) {
if (i != 0) {
zeroesRowList.add(0);
} else
zeroesRowList.add(WAVE_STRING + " "
+ newWaveNum);
}
model.addRow(zeroesRowList.toArray());
}
});
return addNewWaveButton;
}
// Just here to test simpler case of removing rows
/**
* @return Makes a button that removes the last wave
*/
private JComponent makeRemoveMostRecentWaveButton() {
JButton removeMostRecentWaveButton = new JButton(
"Remove Last Wave");
removeMostRecentWaveButton
.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ColumnRemovableTableModel model = (ColumnRemovableTableModel) table
.getModel();
if (tableModel.getRowCount() > 0) {
model.removeRow(tableModel.getRowCount() - 1);
}
}
});
return removeMostRecentWaveButton;
}
/**
* @return Makes a button to remove a wave chosen by the user
*/
private JComponent makeRemoveWaveButton() {
removeWaveButton = new JButton("Remove Wave");
removeWaveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tableModel.removeRow(table.getSelectedRow());
updateWaveColumn();
}
});
return removeWaveButton;
}
/**
* @return Makes a button that clears all of the waves
*/
private JComponent makeClearAllWavesButton() {
JButton clearAllWavesButton = new JButton("Clear All Waves");
clearAllWavesButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int numberOfWaves = tableModel.getRowCount();
while (numberOfWaves > 0) {
numberOfWaves
tableModel.removeRow(numberOfWaves);
}
}
});
return clearAllWavesButton;
}
}
}
}
|
package org.intermine.dwr;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QuerySelectable;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.WebUtil;
import org.intermine.web.logic.bag.BagConversionHelper;
import org.intermine.web.logic.bag.BagHelper;
import org.intermine.web.logic.bag.BagQueryConfig;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.bag.TypeConverter;
import org.intermine.web.logic.config.Type;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.profile.Profile;
import org.intermine.web.logic.profile.ProfileManager;
import org.intermine.web.logic.profile.TagManager;
import org.intermine.web.logic.query.MainHelper;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.query.SavedQuery;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.results.WebTable;
import org.intermine.web.logic.search.SearchFilterEngine;
import org.intermine.web.logic.search.SearchRepository;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.tagging.TagNames;
import org.intermine.web.logic.tagging.TagTypes;
import org.intermine.web.logic.template.TemplateHelper;
import org.intermine.web.logic.template.TemplateQuery;
import org.intermine.web.logic.widget.EnrichmentWidget;
import org.intermine.web.logic.widget.GraphWidget;
import org.intermine.web.logic.widget.GridWidget;
import org.intermine.web.logic.widget.TableWidget;
import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig;
import org.intermine.web.logic.widget.config.GraphWidgetConfig;
import org.intermine.web.logic.widget.config.GridWidgetConfig;
import org.intermine.web.logic.widget.config.TableWidgetConfig;
import org.intermine.web.logic.widget.config.WidgetConfig;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
private static final String INVALID_NAME_MSG = "Invalid name. Names may only contain letters, "
+ "numbers, spaces, and underscores.";
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
String nameCopy = name.replaceAll("#039;", "'");
TagManager tagManager = getTagManager();
// already a favourite. turning off.
if (isFavourite) {
tagManager.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
// not a favourite. turning on.
} else {
tagManager.addTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
}
} catch (RuntimeException e) {
processException(e);
}
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery template = templates.get(templateName);
ObjectStoreInterMineImpl os = (ObjectStoreInterMineImpl) servletContext
.getAttribute(Constants.OBJECTSTORE);
List indexes = new ArrayList();
Query query = TemplateHelper.getPrecomputeQuery(template, indexes, null);
try {
if (!os.isPrecomputed(query, "template")) {
session.setAttribute("precomputing_" + templateName, "true");
os.precompute(query, indexes, "template");
}
} catch (ObjectStoreException e) {
LOG.error("Error while precomputing", e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery template = templates.get(templateName);
ObjectStoreInterMineImpl os = (ObjectStoreInterMineImpl) servletContext
.getAttribute(Constants.OBJECTSTORE);
ObjectStoreWriter osw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getProfileObjectStoreWriter();
try {
session.setAttribute("summarising_" + templateName, "true");
template.summarise(os, osw);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
ServletContext servletContext = ctx.getServletContext();
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getProfileObjectStoreWriter();
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!WebUtil.isValidName(newName)) {
return INVALID_NAME_MSG;
}
if (type.equals("history")) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if (type.equals("saved")) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if (type.equals("bag")) {
if (profile.getSavedBags().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedBags().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
InterMineBag bag = profile.getSavedBags().get(name);
bag.setName(newName, uosw);
TagManager tagManager = getTagManager();
moveTagsToNewObject(name, newName, TagTypes.BAG,
profile.getUsername(), tagManager);
profile.deleteBag(name);
profile.saveBag(newName, bag);
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Moves tags from one object to another.
* @param oldTaggedObj name of original tagged object
* @param newTaggedObj name of new tagged object
* @param type tag type
* @param userName user name
* @param tagManager tag manager
*/
public static void moveTagsToNewObject(String oldTaggedObj, String newTaggedObj, String type,
String userName, TagManager tagManager) {
List<Tag> tags = tagManager.getTags(null, oldTaggedObj, type, userName);
for (Tag tag : tags) {
tagManager.addTag(tag.getTagName(), newTaggedObj, type, userName);
tagManager.deleteTag(tag);
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
ServletContext servletContext = ctx.getServletContext();
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getProfileObjectStoreWriter();
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description, uosw);
profile.getSearchRepository().descriptionChanged(bag);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
Path path = PathQuery.makePath(query.getModel(), query, pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
query.getPathDescriptions().remove(prefixPath);
} else {
query.getPathDescriptions().put(prefixPath, descr);
}
return descr.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = session.getServletContext();
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
SearchRepository globalRepository =
(SearchRepository) servletContext.getAttribute(Constants.
GLOBAL_SEARCH_REPOSITORY);
Profile currentProfile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository userSearchRepository = currentProfile.getSearchRepository();
Map<String, InterMineBag> userWsMap =
(Map<String, InterMineBag>) userSearchRepository.getWebSearchableMap(TagTypes.BAG);
Map<String, InterMineBag> globalWsMap =
(Map<String, InterMineBag>) globalRepository.getWebSearchableMap(TagTypes.BAG);
Map<String, InterMineBag> allBags = new HashMap<String, InterMineBag>(userWsMap);
allBags.putAll(globalWsMap);
Query distinctQuery = MainHelper.makeSummaryQuery(pathQuery, allBags,
new HashMap<String, QuerySelectable>(), summaryPath, servletContext);
Results results = os.execute(distinctQuery);
// Start the count of results
Query countQuery = MainHelper.makeSummaryQuery(pathQuery, allBags,
new HashMap<String, QuerySelectable>(), summaryPath, servletContext);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>();
int rowCount = 0;
for (ResultsRow row : (List<ResultsRow>) results) {
pageSizeResults.add(row);
rowCount++;
if (rowCount >= Constants.DEFAULT_TABLE_SIZE) {
break;
}
}
return Arrays.asList(new Object[] {
pageSizeResults, qid, new Integer(results.size())
});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript. Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE,
* even though not all WebSearchables are templates)
* @param type the type (from TagTypes)
* @param tags the tags to filter on
* @param filterText the text to pass to Lucene
* @param filterAction toggles favourites filter off an on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
ProfileManager pm = SessionMethods.getProfileManager(servletContext);
HttpSession session = WebContextFactory.get().getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map<String, WebSearchable> wsMap;
Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>();
Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>();
if (filterText != null && filterText.length() > 1) {
wsMap = new LinkedHashMap<String, WebSearchable>();
//Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>();
SearchRepository globalSearchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
try {
long time =
SearchRepository.runLeuceneSearch(filterText, scope, type, profile,
globalSearchRepository,
hitMap, null, highlightedDescMap);
LOG.info("Lucene search took " + time + " milliseconds");
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//long time = System.currentTimeMillis();
for (WebSearchable ws: hitMap.keySet()) {
wsMap.put(ws.getName(), ws);
}
} else {
if (scope.equals("user")) {
SearchRepository searchRepository = profile.getSearchRepository();
wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
} else {
SearchRepository globalRepository =
(SearchRepository) servletContext.getAttribute(Constants.
GLOBAL_SEARCH_REPOSITORY);
if (scope.equals("global")) {
wsMap = (Map<String, WebSearchable>) globalRepository.
getWebSearchableMap(type);
} else {
// must be "all"
SearchRepository userSearchRepository = profile.getSearchRepository();
Map<String, ? extends WebSearchable> userWsMap =
userSearchRepository.getWebSearchableMap(type);
Map<String, ? extends WebSearchable> globalWsMap =
globalRepository.getWebSearchableMap(type);
wsMap = new HashMap<String, WebSearchable>(userWsMap);
wsMap.putAll(globalWsMap);
}
}
}
Map<String, ? extends WebSearchable> filteredWsMap
= new LinkedHashMap<String, WebSearchable>();
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) {
aspectTags.add(tag);
} else {
userTags.add(tag);
}
}
if (aspectTags.size() > 0) {
wsMap = new SearchFilterEngine().filterByTags(wsMap, aspectTags, type,
pm.getSuperuser(), getTagManager());
}
if (profile.getUsername() != null && userTags.size() > 0) {
filteredWsMap = new SearchFilterEngine().filterByTags(wsMap, userTags, type,
profile.getUsername(), getTagManager());
} else {
filteredWsMap = wsMap;
}
List returnList = new ArrayList<String>();
returnList.add(callId);
// We need a modifiable map so we can filter out invalid templates
LinkedHashMap<String, ? extends WebSearchable> modifiableWsMap =
new LinkedHashMap(filteredWsMap);
SearchRepository.filterOutInvalidTemplates(modifiableWsMap);
for (WebSearchable ws: modifiableWsMap.values()) {
List row = new ArrayList();
row.add(ws.getName());
if (filterText != null && filterText.length() > 1) {
row.add(highlightedDescMap.get(ws));
row.add(hitMap.get(ws));
} else {
row.add(ws.getDescription());
}
returnList.add(row);
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
String pckName = os.getModel().getPackageName();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
InterMineBag imBag = null;
int count = 0;
try {
imBag = BagHelper.getBag(profile, searchRepository, bagName);
Map<String, QuerySelectable> pathToQueryNode = new HashMap();
Map<String, InterMineBag> bagMap = new HashMap<String, InterMineBag>();
bagMap.put(imBag.getName(), imBag);
ProfileManager pm =
(ProfileManager) servletContext.getAttribute(Constants.PROFILE_MANAGER);
PathQuery pathQuery = TypeConverter.getConversionQuery(BagConversionHelper.
getConversionTemplates(pm.getSuperuserProfile()),
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
Query query = MainHelper.makeQuery(pathQuery, bagMap, pathToQueryNode,
pm, null, false,
(ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE),
getClassKeys(servletContext),
(BagQueryConfig) servletContext.getAttribute(Constants.BAG_QUERY_CONFIG));
count = os.count(query, ObjectStore.SEQUENCE_IGNORE);
} catch (Exception e) {
throw new RuntimeException(e);
}
return count;
} catch (RuntimeException e) {
processException(e);
return 0;
}
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Get state.
* @param name name of state
* @return value if state was set before during the session else null
*/
public static String getState(String name) {
try {
return (String) AjaxServices.getWebState().getState(name);
} catch (RuntimeException e) {
processException(e);
}
return null;
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
// TODO get message text from the properties file
if (bagName.equals("")) {
return "You cannot save a list with a blank name";
}
if (!WebUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
SearchRepository searchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
Map<String, ? extends WebSearchable> publicBagMap =
searchRepository.getWebSearchableMap(TagTypes.BAG);
if (publicBagMap.get(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new bag
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if (operation.equals("delete")) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(),
selectedBags[i]));
if (queries.size() > 0) {
return "List " + selectedBags[i] + " cannot be deleted as it is referenced "
+ "by other queries " + queries;
}
}
} else {
Properties properties = (Properties)
servletContext.getAttribute(Constants.WEB_PROPERTIES);
String defaultName = properties.getProperty("lists.input.example");
if (!operation.equals("copy") && (bagName.equals("")
|| (bagName.equalsIgnoreCase(defaultName)))) {
return "New list name is required";
} else if (!WebUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
public static List<String> queriesThatMentionBag(Map savedQueries, String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @param selectedExtraAttribute extra attribute (like organism)
* @return graph widget
*/
public static GraphWidget getProcessGraphWidget(String widgetId, String bagName,
String selectedExtraAttribute) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
GraphWidgetConfig graphWidgetConf = (GraphWidgetConfig) widget;
graphWidgetConf.setSession(session);
GraphWidget graphWidget = new GraphWidget(graphWidgetConf, imBag, os,
selectedExtraAttribute);
return graphWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
*
* @param widgetId unique ID for this widget
* @param bagName name of list
* @return table widget
*/
public static TableWidget getProcessTableWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Map classKeys = getClassKeys(servletContext);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig: widgets) {
if (widgetConfig.getId().equals(widgetId)) {
TableWidgetConfig tableWidgetConfig = (TableWidgetConfig) widgetConfig;
tableWidgetConfig.setClassKeys(classKeys);
tableWidgetConfig.setWebConfig(webConfig);
TableWidget tableWidget = new TableWidget(tableWidgetConfig, imBag, os, null);
return tableWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param errorCorrection error correction method to use
* @param max maximum value to display
* @param filters list of strings used to filter widget results, ie Ontology
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static EnrichmentWidget getProcessEnrichmentWidget(String widgetId, String bagName,
String errorCorrection, String max,
String filters,
String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository = SessionMethods
.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
EnrichmentWidgetConfig enrichmentWidgetConfig =
(EnrichmentWidgetConfig) widgetConfig;
enrichmentWidgetConfig.setExternalLink(externalLink);
enrichmentWidgetConfig.setExternalLinkLabel(externalLinkLabel);
EnrichmentWidget enrichmentWidget = new EnrichmentWidget(
enrichmentWidgetConfig, imBag, os, filters, max,
errorCorrection);
return enrichmentWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param highlight for highlighting
* @param pValue pValue
* @param numberOpt numberOpt
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static GridWidget getProcessGridWidget(String widgetId, String bagName,
String highlight,
String pValue,
String numberOpt,
String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository = SessionMethods
.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
GridWidgetConfig gridWidgetConfig =
(GridWidgetConfig) widgetConfig;
gridWidgetConfig.setExternalLink(externalLink);
gridWidgetConfig.setExternalLinkLabel(externalLinkLabel);
GridWidget gridWidget = new GridWidget(
gridWidgetConfig, imBag, os, null, highlight, pValue, numberOpt);
return gridWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = getClassKeys(servletContext);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = getClassKeys(servletContext);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
return pt.getFirstSelectedFields(os, classKeys);
}
/**
*
* @param servletContext
* @return
*/
@SuppressWarnings("unchecked")
private static Map<String, List<FieldDescriptor>> getClassKeys(ServletContext servletContext) {
return (Map) servletContext.getAttribute(Constants.CLASS_KEYS);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
/**
* AJAX request - reorder view.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
List<Path> view = SessionMethods.getEditingView(session);
ArrayList<Path> newView = new ArrayList<Path>();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
PathQuery pathQuery = (PathQuery) session.getAttribute(Constants.QUERY);
pathQuery.setViewPaths(newView);
}
/**
* Add a Node from the sort order
* @param path the Path as a String
* @param direction the direction to sort by
* @exception Exception if the application business logic throws
*/
public void addToSortOrder(String path, String direction)
throws Exception {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
query.setOrderBy(path, direction);
}
/**
* Reset the sort order
*/
public void clearSortOrder() {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
query.resetOrderBy();
}
/**
* Get the news
* @param rssURI the URI of the rss feed
* @return the news feed as html
*/
public static String getNewsRead(String rssURI) {
try {
URL feedUrl = new URL(rssURI);
SyndFeedInput input = new SyndFeedInput();
XmlReader reader;
try {
reader = new XmlReader(feedUrl);
} catch (Throwable e) {
// xml document at this url doesn't exist or is invalid, so the news cannot be read
return "<i>No news</i>";
}
SyndFeed feed = input.build(reader);
List<SyndEntry> entries = feed.getEntries();
StringBuffer html = new StringBuffer("<ol id=\"news\">");
int counter = 0;
for (SyndEntry syndEntry : entries) {
if (counter > 4) {
break;
}
// NB: apparently, the only accepted formats for getPublishedDate are
// Fri, 28 Jan 2008 11:02 GMT
// Fri, 8 Jan 2008 11:02 GMT
// Fri, 8 Jan 08 11:02 GMT
// an annoying error appears if the format is not followed, and news tile hangs.
// the following is used to display the date without timestamp.
// this should always work since the retrieved date has a fixed format,
// independent of the one used in the xml.
String longDate = syndEntry.getPublishedDate().toString();
String dayMonth = longDate.substring(0, 10);
String year = longDate.substring(24);
html.append("<li>");
html.append("<strong>" + syndEntry.getTitle() + "</strong>");
html.append(" - <em>" + dayMonth + " " + year + "</em><br/>");
// html.append("- <em>" + syndEntry.getPublishedDate().toString() + "</em><br/>");
html.append(syndEntry.getDescription().getValue());
html.append("</li>");
counter++;
}
html.append("</ol>");
return html.toString();
} catch (MalformedURLException e) {
return "<i>No news at specified URL</i>";
} catch (IllegalArgumentException e) {
return "<i>No news at specified URL</i>";
} catch (FeedException e) {
return "<i>No news at specified URL</i>";
}
}
/**
* Returns all objects names tagged with specified tag type and tag name.
* @param type tag type
* @param tag tag name
* @return objects names
*/
public static Set<String> filterByTag(String type, String tag) {
Profile profile = getProfile(getRequest());
SearchRepository searchRepository = profile.getSearchRepository();
Map<String, WebSearchable> map = (Map<String, WebSearchable>) searchRepository.
getWebSearchableMap(type);
if (map == null) {
return null;
}
Map<String, WebSearchable> filteredMap = new TreeMap<String, WebSearchable>();
List<String> tagList = new ArrayList<String>();
tagList.add(tag);
filteredMap.putAll(new SearchFilterEngine().filterByTags(map, tagList, type,
profile.getUsername(), getTagManager()));
return filteredMap.keySet();
}
/**
* Adds tag and assures that there is only one tag for this combination of tag name, tagged
* Object and type.
* @param tag tag name
* @param taggedObject object id that is tagged by this tag
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String addTag(String tag, String taggedObject, String type) {
String tagName = tag;
LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:"
+ taggedObject + " type: " + type);
try {
HttpServletRequest request = getRequest();
Profile profile = getProfile(request);
tagName = tagName.trim();
HttpSession session = request.getSession();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
if (tagExists(tagName, taggedObject, type)) {
return "Already tagged with this tag.";
}
if (!TagManager.isValidTagName(tagName)) {
return INVALID_NAME_MSG;
}
if (tagName.startsWith(TagNames.IM_PREFIX)
&& !SessionMethods.isSuperUser(session)) {
return "You cannot add a tag starting with " + TagNames.IM_PREFIX + ", "
+ "that is a reserved word.";
}
TagManager tagManager = getTagManager();
tagManager.addTag(tagName, taggedObject, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr = SessionMethods.
getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
}
return "Adding tag failed.";
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return "Adding tag failed.";
}
}
/**
* Deletes tag.
* @param tagName tag name
* @param tagged id of tagged object
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String deleteTag(String tagName, String tagged, String type) {
LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:"
+ tagged + " type: " + type);
try {
HttpServletRequest request = getRequest();
Profile profile = getProfile(request);
TagManager manager = SessionMethods.getTagManager(request.getSession());
manager.deleteTag(tagName, tagged, type, profile.getUsername());
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr =
SessionMethods.getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return "Deleting tag failed.";
}
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param type tag type
* @return tags
*/
public static Set<String> getTags(String type) {
HttpServletRequest request = getRequest();
TagManager tagManager = SessionMethods.getTagManager(request.getSession());
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getUserTagNames(type, profile.getUsername());
}
return new TreeSet<String>();
}
/**
* Returns all tags by which is specified object tagged.
* @param type tag type
* @param tagged id of tagged object
* @return tags
*/
public static Set<String> getObjectTags(String type, String tagged) {
HttpServletRequest request = getRequest();
TagManager tagManager = SessionMethods.getTagManager(request.getSession());
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getObjectTagNames(tagged, type, profile.getUsername());
}
return new TreeSet<String>();
}
private static boolean tagExists(String tag, String taggedObject, String type) {
HttpServletRequest request = getRequest();
TagManager tagManager = SessionMethods.getTagManager(request.getSession());
String userName = getProfile(request).getUsername();
return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag);
}
private static Profile getProfile(HttpServletRequest request) {
return (Profile) request.getSession().getAttribute(Constants.PROFILE);
}
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
private static TagManager getTagManager() {
return SessionMethods.getTagManager(getRequest().getSession());
}
/**
* Set the constraint logic on a query to be the given expression
* @param expression the constraint logic for the query
*/
public static void setConstraintLogic(String expression) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
query.setConstraintLogic(expression);
query.syncLogicExpression(SessionMethods.getDefaultOperator(session));
}
/**
* Get the grouped constraint logic
* @return a list representing the grouped constraint logic
*/
public static String getConstraintLogic() {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
return (query.getGroupedConstraintLogic().toString());
}
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = (AutoCompleter) servletContext.getAttribute(Constants.AUTO_COMPLETER);
ac.createRAMIndex(className + "." + field);
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
}
|
package org.jsecurity.web.support;
import org.jsecurity.SecurityManager;
import org.jsecurity.context.SecurityContext;
import org.jsecurity.context.support.DelegatingSecurityContext;
import org.jsecurity.context.support.InvalidSecurityContextException;
import org.jsecurity.session.Session;
import org.jsecurity.util.ThreadContext;
import org.jsecurity.web.WebInterceptor;
import org.jsecurity.web.WebStore;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.net.InetAddress;
import java.security.Principal;
import java.util.List;
/**
* Builds a {@link org.jsecurity.context.SecurityContext SecurityContext} based on a web request and makes it
* accessible via the {@link ThreadContext}.
*
* <p>Consolidates common behaviors in obtaining a SecurityContext in different
* web environments (e.g. Servlet Filters, framework specific interceptors, etc).
*
* @author Les Hazlewood
* @since 0.2
*/
public class SecurityContextWebInterceptor extends SecurityWebSupport implements WebInterceptor {
/**
* The key that is used to store subject principals in the session.
*/
public static final String PRINCIPALS_SESSION_KEY =
SecurityContextWebInterceptor.class.getName() + "_PRINCIPALS_SESSION_KEY";
/**
* The key that is used to store whether or not the user is authenticated in the session.
*/
public static final String AUTHENTICATED_SESSION_KEY =
SecurityContextWebInterceptor.class.getName() + "_AUTHENTICATED_SESSION_KEY";
protected SecurityManager securityManager = null;
protected SessionWebInterceptor sessionWebInterceptor = null;
/**
* Determines whether or not to use the HttpSession as the storage mechanism for principals or the JSecurity
* Session. The default is <tt>false</tt>, since JSecurity sessions can be accessed across multiple client
* mediums (more flexible) and HttpSessions cannot.
*/
protected boolean preferHttpSessionStorage = false;
//passthrough attributes to the underlying DefaultWebSessionFactory
protected WebStore<Serializable> sessionIdStore = null;
protected WebStore<List<Principal>> principalsStore = null;
protected WebStore<Boolean> authenticatedStore = null;
protected boolean requireSessionOnRequest = false;
public SecurityContextWebInterceptor() {
}
public SecurityManager getSecurityManager() {
return securityManager;
}
public void setSecurityManager( SecurityManager securityManager ) {
this.securityManager = securityManager;
}
public boolean isPreferHttpSessionStorage() {
return preferHttpSessionStorage;
}
public void setPreferHttpSessionStorage( boolean preferHttpSessionStorage ) {
this.preferHttpSessionStorage = preferHttpSessionStorage;
}
public WebStore<Serializable> getSessionIdStore() {
return sessionIdStore;
}
public void setSessionIdStore( WebStore<Serializable> sessionIdStore ) {
this.sessionIdStore = sessionIdStore;
}
public WebStore<List<Principal>> getPrincipalsStore() {
return principalsStore;
}
public void setPrincipalsStore( WebStore<List<Principal>> principalsStore ) {
this.principalsStore = principalsStore;
}
public WebStore<Boolean> getAuthenticatedStore() {
return authenticatedStore;
}
public void setAuthenticatedStore( WebStore<Boolean> authenticatedStore ) {
this.authenticatedStore = authenticatedStore;
}
public boolean isRequireSessionOnRequest() {
return requireSessionOnRequest;
}
public void setRequireSessionOnRequest( boolean requireSessionOnRequest ) {
this.requireSessionOnRequest = requireSessionOnRequest;
}
protected SessionWebInterceptor getSessionWebInterceptor() {
return sessionWebInterceptor;
}
protected void setSessionWebInterceptor( SessionWebInterceptor sessionWebInterceptor ) {
this.sessionWebInterceptor = sessionWebInterceptor;
}
protected void ensurePrincipalsStore() {
if ( getPrincipalsStore() == null ) {
if ( log.isDebugEnabled() ) {
log.debug( "Initializing default Principals WebStore..." );
}
AbstractWebStore<List<Principal>> store = null;
if ( isPreferHttpSessionStorage() ) {
store = new HttpSessionStore<List<Principal>>( PRINCIPALS_SESSION_KEY, false );
} else {
store = new SessionStore<List<Principal>>( PRINCIPALS_SESSION_KEY, false );
}
store.init();
setPrincipalsStore( store );
}
}
protected void ensureAuthenticatedStore() {
if ( getAuthenticatedStore() == null ) {
if ( log.isDebugEnabled() ) {
log.debug( "Initializing default Authenticated token WebStore..." );
}
AbstractWebStore<Boolean> store = null;
if ( isPreferHttpSessionStorage() ) {
store = new HttpSessionStore<Boolean>( AUTHENTICATED_SESSION_KEY, false );
} else {
store = new SessionStore<Boolean>( AUTHENTICATED_SESSION_KEY, false );
}
store.init();
setAuthenticatedStore( store );
}
}
public void init() {
SecurityManager securityManager = getSecurityManager();
if ( securityManager == null ) {
String msg = "SecurityManager property must be set.";
throw new IllegalStateException( msg );
}
if ( getSessionWebInterceptor() == null ) {
if ( log.isDebugEnabled() ) {
log.debug( "Initializing default SessionWebInterceptor instance..." );
}
SessionWebInterceptor swi = new SessionWebInterceptor();
swi.setSessionFactory( securityManager );
swi.setRequireSessionOnRequest( isRequireSessionOnRequest() );
WebStore<Serializable> sessionIdStore = getSessionIdStore();
if ( sessionIdStore != null ) {
swi.setIdStore( sessionIdStore );
}
swi.init();
setSessionWebInterceptor( swi );
}
ensurePrincipalsStore();
ensureAuthenticatedStore();
}
@SuppressWarnings( "unchecked" )
protected List<Principal> getPrincipals( ServletRequest servletRequest, ServletResponse servletResponse ) {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
return getPrincipalsStore().retrieveValue( request, response );
}
protected boolean isAuthenticated( ServletRequest servletRequest, ServletResponse servletResponse ) {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
Boolean value = getAuthenticatedStore().retrieveValue( request, response );
return value != null && value;
}
protected SecurityContext createSecurityContext( List<Principal> principals, boolean authenticated,
InetAddress inetAddress, Session session,
SecurityManager securityManager ) {
return new DelegatingSecurityContext( principals, authenticated, inetAddress, session, securityManager );
}
protected SecurityContext createSecurityContext( ServletRequest request,
ServletResponse response,
List<Principal> principals,
boolean authenticated,
Session existing ) {
SecurityContext securityContext;
SecurityManager securityManager = getSecurityManager();
if ( securityManager == null ) {
final String message = "the SecurityManager attribute must be configured. This could be " +
"done by calling setSecurityManager() on the " + getClass().getName() + " instance, or by subclassing " +
"to retrieve the SecurityManager from an application framework.";
throw new IllegalStateException( message );
}
securityContext = createSecurityContext( principals, authenticated, ThreadContext.getInetAddress(), existing, securityManager );
return securityContext;
}
public SecurityContext createSecurityContext( ServletRequest request, ServletResponse response, Session existing ) {
List<Principal> principals = getPrincipals( request, response );
boolean authenticated = isAuthenticated( request, response );
return createSecurityContext( request, response, principals, authenticated, existing );
}
protected void bindForSubsequentRequests( HttpServletRequest request, HttpServletResponse response, SecurityContext securityContext ) {
getPrincipalsStore().storeValue( securityContext.getAllPrincipals(), request, response );
getAuthenticatedStore().storeValue( securityContext.isAuthenticated(), request, response );
}
public boolean preHandle( HttpServletRequest request, HttpServletResponse response )
throws Exception {
//useful for a number of JSecurity components - do it in case this interceptor is the only one configured:
bindInetAddressToThread( request );
//enable the Session if one is associated w/ the request. This will bind it to the ThreadContext as well.
SessionWebInterceptor sessionInterceptor = getSessionWebInterceptor();
if ( sessionInterceptor == null ) {
String msg = "SessionWebInterceptor property must be set. This is done by default during the init() " +
"method. Please ensure init() is called before using this instance.";
throw new IllegalStateException( msg );
}
sessionInterceptor.preHandle( request, response );
//bind a dummy SecurityContext to the thread just to support any components that require it. This is primarily
//only here to make any existing session available to the createSecurityContext methods (and child methods)
//via SecurityContext.getSession() in case it is needed. This isn't very 'clean' per se, but it does prevent
//any children components (such as WebStores) from knowing about thread locals, which I think is 'cleaner'
//overall - Les.
Session session = getSession( request, response );
SecurityContext dummy =
new DelegatingSecurityContext( (Principal)null, false, ThreadContext.getInetAddress(), session, getSecurityManager() );
ThreadContext.bind( dummy );
//now contstruct the 'real' security context to use during the request's thread:
SecurityContext securityContext = null;
try {
securityContext = createSecurityContext( request, response, session );
} finally {
//remove the dummy in any case
ThreadContext.unbindSecurityContext();
}
if ( securityContext != null ) {
ThreadContext.bind( securityContext );
}
return true;
}
public void postHandle( HttpServletRequest request, HttpServletResponse response )
throws Exception {
SecurityContext securityContext = getSecurityContext( request, response );
if ( securityContext != null ) {
//make sure it is valid:
try {
securityContext.getAllPrincipals();
} catch ( InvalidSecurityContextException e ) {
if ( log.isTraceEnabled() ) {
log.trace( "SecurityContext was invalidated during the request - returning quietly (a new " +
"one will be created on the next request)." );
}
return;
}
bindForSubsequentRequests( request, response, securityContext );
}
getSessionWebInterceptor().postHandle( request, response );
}
public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Exception exception )
throws Exception {
getSessionWebInterceptor().afterCompletion( request, response, exception );
ThreadContext.unbindSecurityContext();
unbindInetAddressFromThread();
}
}
|
package be.ac.ulg.montefiore.run.jahmm;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Collection;
/**
* This class represents a distribution of a finite number of positive integer
* observations.
*/
public class OpdfInteger
implements Opdf<ObservationInteger>
{
private double[] probabilities;
/**
* Builds a new probability distribution which operates on integer values.
* The probabilities are initialized so that the distribution is uniformaly
* distributed.
*
* @param nbEntries The number of values to which to associate
* probabilities. Observations handled by this
* distribution have to be higher or equal than 0 and
* strictly smaller than <code>nbEntries</code>.
*/
public OpdfInteger(int nbEntries)
{
if (nbEntries <= 0)
throw new IllegalArgumentException("Argument must be strictly " +
"positive");
probabilities = new double[nbEntries];
for (int i = 0; i < nbEntries; i++)
probabilities[i] = 1. / ((double) nbEntries);
}
/**
* Builds a new probability distribution which operates on integer values.
*
* @param probabilities Array holding one probability for each possible
* argument value (<i>i.e.</i> such that
* <code>probabilities[i]</code> is the probability
* of the observation <code>i</code>.
*/
public OpdfInteger(double[] probabilities)
{
if (probabilities.length == 0)
throw new IllegalArgumentException("Invalid empty array");
this.probabilities = new double[probabilities.length];
for (int i = 0; i < probabilities.length; i++)
if ((this.probabilities[i] = probabilities[i]) < 0.)
throw new IllegalArgumentException();
}
/**
* Returns how many integers are associated to probabilities by this
* distribution.
*
* @return The number of integers are associated to probabilities.
*/
public int nbEntries()
{
return probabilities.length;
}
public double probability(ObservationInteger o)
{
if (o.value > probabilities.length-1)
throw new IllegalArgumentException("Wrong observation value");
return probabilities[o.value];
}
public ObservationInteger generate()
{
double rand = Math.random();
for (int i = 0; i < probabilities.length - 1; i++)
if ((rand -= probabilities[i]) < 0.)
return new ObservationInteger(i);
return new ObservationInteger(probabilities.length - 1);
}
public void fit(ObservationInteger... oa)
{
fit(Arrays.asList(oa));
}
public void fit(Collection<? extends ObservationInteger> co)
{
if (co.isEmpty())
throw new IllegalArgumentException("Empty observation set");
for (int i = 0; i < probabilities.length; i++)
probabilities[i] = 0.;
for (ObservationInteger o : co)
probabilities[o.value]++;
for (int i = 0; i < probabilities.length; i++)
probabilities[i] /= co.size();
}
public void fit(ObservationInteger[] o, double[] weights)
{
fit(Arrays.asList(o), weights);
}
public void fit(Collection<? extends ObservationInteger> co,
double[] weights)
{
if (co.isEmpty() || co.size() != weights.length)
throw new IllegalArgumentException();
Arrays.fill(probabilities, 0.);
int i = 0;
for (ObservationInteger o : co)
probabilities[o.value] += weights[i++];
}
public OpdfInteger clone()
{
try {
OpdfInteger opdf = (OpdfInteger)super.clone();
opdf.probabilities = probabilities.clone();
return opdf;
} catch(CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
public String toString()
{
return toString(NumberFormat.getInstance());
}
public String toString(NumberFormat numberFormat)
{
String s = "Integer distribution
for (int i = 0; i < nbEntries();) {
ObservationInteger oi = new ObservationInteger(i);
s += numberFormat.format(probability(oi)) +
((++i < nbEntries()) ? " " : "");
}
return s;
}
private static final long serialVersionUID = 1L;
}
|
package ubic.gemma.model.genome;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.type.DoubleType;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cern.colt.list.DoubleArrayList;
import cern.jet.stat.Descriptive;
import ubic.basecode.math.metaanalysis.MetaAnalysis;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressedGenesDetails;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionValueObject;
import ubic.gemma.model.common.description.ExternalDatabase;
import ubic.gemma.model.expression.arrayDesign.ArrayDesign;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.experiment.BioAssaySet;
import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject;
import ubic.gemma.model.genome.gene.GeneProduct;
import ubic.gemma.model.genome.gene.GeneValueObject;
import ubic.gemma.util.BusinessKey;
import ubic.gemma.util.CommonQueries;
import ubic.gemma.util.EntityUtils;
import ubic.gemma.util.SequenceBinUtils;
import ubic.gemma.util.TaxonUtility;
/**
* @author pavlidis
* @version $Id$
* @see ubic.gemma.model.genome.Gene
*/
@Repository
public class GeneDaoImpl extends ubic.gemma.model.genome.GeneDaoBase {
private static final int BATCH_SIZE = 100;
private static Log log = LogFactory.getLog( GeneDaoImpl.class.getName() );
private static final int MAX_RESULTS = 100;
private static final int MAX_WINDOW = 1000000;
private static final int WINDOW_INCREMENT = 500;
/*
* FIXME use a regular ehcache so we can use timeouts.
*/
private HashMap<Long, Collection<Long>> gene2CsCache = new HashMap<Long, Collection<Long>>();
@Autowired
public GeneDaoImpl( SessionFactory sessionFactory ) {
super.setSessionFactory( sessionFactory );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#find(ubic.gemma.model.genome.Gene)
*/
@SuppressWarnings("unchecked")
@Override
public Gene find( Gene gene ) {
try {
Criteria queryObject = super.getSession().createCriteria( Gene.class );
BusinessKey.checkKey( gene );
BusinessKey.createQueryObject( queryObject, gene );
java.util.List results = queryObject.list();
Object result = null;
if ( results != null ) {
if ( results.size() > 1 ) {
/*
* this can happen in semi-rare cases in queries by symbol, where the gene symbol is not unique for
* the taxon and the query did not have the gene name to further restrict the query.
*/
log.error( "Multiple genes found for " + gene + ":" );
debug( results );
Collections.sort( results, new Comparator<Gene>() {
public int compare( Gene arg0, Gene arg1 ) {
return arg0.getId().compareTo( arg1.getId() );
}
} );
result = results.iterator().next();
log.error( "Returning arbitrary gene: " + result );
} else if ( results.size() == 1 ) {
result = results.iterator().next();
}
}
return ( Gene ) result;
} catch ( org.hibernate.HibernateException ex ) {
throw super.convertHibernateAccessException( ex );
}
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDao#find(ubic.gemma.model.genome.PhysicalLocation)
*/
public Collection<Gene> find( PhysicalLocation physicalLocation ) {
return findByPosition( physicalLocation.getChromosome(), physicalLocation.getNucleotide(), physicalLocation
.getNucleotide()
+ physicalLocation.getNucleotideLength(), physicalLocation.getStrand() );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDao#findByOfficialNameInexact(java.lang.String)
*/
@SuppressWarnings( { "unchecked" })
public Collection<Gene> findByOfficialNameInexact( String officialName ) {
final String query = "from GeneImpl g where g.officialName like :officialName order by g.officialName";
org.hibernate.Query queryObject = this.getSession( false ).createQuery( query );
queryObject.setParameter( "officialName", officialName );
queryObject.setMaxResults( MAX_RESULTS );
return queryObject.list();
}
/**
* @see ubic.gemma.model.genome.GeneDao#findByOfficialSymbolInexact(int, java.lang.String)
*/
@SuppressWarnings( { "unchecked" })
@Override
public java.util.Collection<Gene> findByOfficialSymbolInexact( final java.lang.String officialSymbol ) {
final String query = "from GeneImpl g where g.officialSymbol like :officialSymbol order by g.officialSymbol";
org.hibernate.Query queryObject = this.getSession( false ).createQuery( query );
queryObject.setParameter( "officialSymbol", officialSymbol );
queryObject.setMaxResults( MAX_RESULTS );
return queryObject.list();
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDao#findNearest(ubic.gemma.model.genome.PhysicalLocation)
*/
public RelativeLocationData findNearest( PhysicalLocation physicalLocation, boolean useStrand ) {
// FIXME Should return a collection of relativeLocationData in the case of ties
if ( physicalLocation.getNucleotide() == null ) {
throw new IllegalArgumentException( "Locations must have a nucleotide position" );
}
/*
* Strategy: start with a small window, enlarge it until we decide enough is enough.
*/
Chromosome chrom = physicalLocation.getChromosome();
final Long targetStart = physicalLocation.getNucleotide();
Integer nucleotideLength = physicalLocation.getNucleotideLength();
final Long targetEnd = targetStart + ( nucleotideLength == null ? 0 : nucleotideLength );
final String strand = physicalLocation.getStrand();
if ( log.isDebugEnabled() )
log.debug( "Start Search: " + physicalLocation + " length=" + ( targetEnd - targetStart ) );
/*
* Starting with exact location, look for genes, enlarging the region as needed -- ignoring strand.. Finds the
* nearest hit, but tracks if the strand is the same.
*/
int i = 0;
long windowStart = targetStart;
long windowEnd = targetEnd;
while ( windowStart >= 0 && windowEnd - windowStart < MAX_WINDOW ) {
windowStart = windowStart - i * WINDOW_INCREMENT;
if ( targetStart < 0 ) windowStart = 0L;
windowEnd = windowEnd + i * WINDOW_INCREMENT;
if ( log.isDebugEnabled() )
log.debug( "Search: " + physicalLocation + " length=" + ( windowEnd - windowStart ) + " strand="
+ physicalLocation.getStrand() );
// note that here we ignore the strand.
Collection<Gene> candidates = findByPosition( chrom, windowStart, windowEnd, useStrand ? strand : null );
if ( !candidates.isEmpty() ) {
if ( log.isDebugEnabled() )
log.debug( physicalLocation + ": " + candidates.size() + " nearby genes at window size " + i
* WINDOW_INCREMENT );
long closestRange = ( long ) 1e10;
RelativeLocationData result = null;
for ( Gene gene : candidates ) {
this.thaw( gene );
for ( GeneProduct gp : gene.getProducts() ) {
PhysicalLocation genelocation = gp.getPhysicalLocation();
boolean onSameStrand = genelocation.getStrand().equals( strand );
assert genelocation.getChromosome().equals( physicalLocation.getChromosome() );
Long geneStart = genelocation.getNucleotide();
Long geneEnd = genelocation.getNucleotideLength() + geneStart;
RelativeLocationData candidate = new RelativeLocationData( physicalLocation, gene, gp,
genelocation );
candidate.setOnSameStrand( onSameStrand );
long range = 0;
// note we use the 'real' location of the par, not the window.
if ( geneStart > targetEnd ) {
// t ooooo
range = geneStart - targetEnd;
if ( log.isDebugEnabled() )
log.debug( gene + " is " + range + " from the right end of " + physicalLocation );
} else if ( geneStart <= targetStart ) {
if ( geneEnd >= targetEnd ) {
// g oooooooooo
candidate.setContainedWithinGene( true );
candidate.setOverlapsGene( true );
range = 0;
if ( log.isDebugEnabled() ) log.debug( gene + " contains target " + physicalLocation );
} else if ( geneEnd > targetStart ) {
// g ooooooooo
range = 0;
candidate.setOverlapsGene( true );
if ( log.isDebugEnabled() )
log.debug( gene + " overlaps left end of " + physicalLocation );
} else {
assert geneEnd < targetStart;
// g ooooooo
log.debug( gene + " is " + range + " from the left end of " + physicalLocation );
range = targetStart - geneEnd;
}
} else {
if ( geneEnd > targetEnd ) {
// t ooooooo
if ( log.isDebugEnabled() )
log.debug( gene + " overlaps right end of " + physicalLocation );
range = 0;
candidate.setOverlapsGene( true );
} else {
assert geneEnd <= targetEnd;
// t oooooooooooo
range = 0;
candidate.setOverlapsGene( true );
if ( log.isDebugEnabled() )
log.debug( gene + " is contained within " + physicalLocation );
}
}
assert range >= 0;
if ( range < closestRange ) {
result = candidate;
result.setRange( range );
closestRange = range;
}
}
}
return result;
}
// log.debug( "Widening search..." );
i++;
}
// nuthin'
log.debug( "Nothing found" );
return null;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#findOrCreate(ubic.gemma.model.genome.Gene)
*/
@Override
public Gene findOrCreate( Gene gene ) {
Gene existingGene = this.find( gene );
if ( existingGene != null ) {
return existingGene;
}
// We consider this abnormal because we expect most genes to have been loaded into the system already.
log.warn( "*** Creating new gene: " + gene + " ***" );
return create( gene );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDao#geneValueObjectToEntity(ubic.gemma.model.genome.gene.GeneValueObject)
*/
public Gene geneValueObjectToEntity( GeneValueObject geneValueObject ) {
return this.load( geneValueObject.getId() );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDao#loadThawed(java.util.Collection)
*/
public Collection<Gene> loadThawed( Collection<Long> ids ) {
Collection<Gene> result = new HashSet<Gene>();
if ( ids.isEmpty() ) return result;
Collection<Long> batch = new HashSet<Long>();
StopWatch timer = new StopWatch();
timer.start();
for ( Long g : ids ) {
batch.add( g );
if ( batch.size() == BATCH_SIZE ) {
result.addAll( doLoadThawedLite( batch ) );
batch.clear();
}
}
if ( !batch.isEmpty() ) {
result.addAll( doLoadThawedLite( batch ) );
}
if ( timer.getTime() > 1000 ) {
log.info( "Load+thaw " + ids.size() + " genes: " + timer.getTime() + "ms" );
}
return result;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDao#thawLite(ubic.gemma.model.genome.Gene)
*/
public Gene thawLite( final Gene gene ) {
return this.thaw( gene );
}
/**
* @param coexpressions
* @param eeID
* @param geneType
* @return
*/
private ExpressionExperimentValueObject addExpressionExperimentToCoexpressions(
CoexpressionCollectionValueObject coexpressions, Long eeID, String geneType ) {
ExpressionExperimentValueObject eeVo = coexpressions.getExpressionExperiment( geneType, eeID );
if ( eeVo == null ) {
eeVo = new ExpressionExperimentValueObject();
eeVo.setId( eeID );
coexpressions.addExpressionExperiment( geneType, eeVo ); // unorganized.
}
return eeVo;
}
/**
* Generically add a coexpression record to the results set.
*
* @param coexpressions
* @param eeID
* @param queryGene
* @param queryProbe
* @param pvalue
* @param score
* @param coexpressedGene
* @param geneType
* @param coexpressedProbe
*/
private void addResult( CoexpressionCollectionValueObject coexpressions, Long eeID, Gene queryGene,
Long queryProbe, Double pvalue, Double score, Long coexpressedGene, String geneType, Long coexpressedProbe ) {
CoexpressionValueObject coExVO;
// add the gene (if not already seen)
if ( coexpressions.contains( coexpressedGene ) ) {
coExVO = coexpressions.get( coexpressedGene );
} else {
coExVO = new CoexpressionValueObject();
coExVO.setQueryGene( queryGene );
coExVO.setGeneId( coexpressedGene );
coExVO.setGeneType( geneType );
coexpressions.add( coExVO );
}
// log.info( "EE=" + eeID + " in Probe=" + queryProbe + " out Probe=" + coexpressedProbe + " gene="
// + coexpressedGene + " score=" + String.format( "%.3f", score ) );
// add the expression experiment.
ExpressionExperimentValueObject eeVo = addExpressionExperimentToCoexpressions( coexpressions, eeID, geneType );
// add the ee here so we know it is associated with this specific gene.
coExVO.addSupportingExperiment( eeVo );
coExVO.addScore( eeID, score, pvalue, queryProbe, coexpressedProbe );
coexpressions.initializeSpecificityDataStructure( eeID, queryProbe );
}
/**
* @param results
*/
private void debug( List<Gene> results ) {
StringBuilder buf = new StringBuilder();
buf.append( "\n" );
for ( Gene g : results ) {
buf.append( g + "\n" );
}
log.error( buf );
}
// /**
// * @param ids
// * @return
// */
// @SuppressWarnings("unchecked")
// private Collection<Gene> doLoadThawed( Collection<Long> ids ) {
// return this
// .getHibernateTemplate()
// .findByNamedParam(
// "select distinct g from GeneImpl g left join fetch g.aliases left join fetch g.accessions acc "
// + "join fetch g.taxon t left join fetch t.externalDatabase"
// + " left join fetch acc.externalDatabase left join fetch g.products gp "
// + " left join fetch g.auditTrail at left join fetch at.events "
// + "left join fetch gp.accessions gpacc left join fetch gpacc.externalDatabase left join"
// + " fetch gp.physicalLocation gppl left join fetch gppl.chromosome chr left join fetch chr.taxon "
// + " where g.id in (:gids)", "gids", ids );
/**
* @param ids
* @return
*/
@SuppressWarnings("unchecked")
private Collection<Gene> doLoadThawedLite( Collection<Long> ids ) {
return this.getHibernateTemplate().findByNamedParam(
"select distinct g from GeneImpl g left join fetch g.aliases left join fetch g.accessions acc "
+ "join fetch g.taxon t left join fetch g.products gp where g.id in (:gids)", "gids", ids );
}
/**
* Returns KNOWN genes in the region.
*
* @param chrom
* @param targetStart
* @param targetEnd
* @param strand
* @return
*/
@SuppressWarnings("unchecked")
private Collection<Gene> findByPosition( Chromosome chrom, final Long targetStart, final Long targetEnd,
final String strand ) {
// the 'fetch'es are so we don't get lazy loads (typical applications of this method)
String query = "select distinct g from GeneImpl as g "
+ "inner join fetch g.products prod inner join fetch prod.physicalLocation pl inner join fetch pl.chromosome "
+ "where ((pl.nucleotide >= :start AND (pl.nucleotide + pl.nucleotideLength) <= :end) "
+ "OR (pl.nucleotide <= :start AND (pl.nucleotide + pl.nucleotideLength) >= :end) OR "
+ "(pl.nucleotide >= :start AND pl.nucleotide <= :end) "
+ "OR ((pl.nucleotide + pl.nucleotideLength) >= :start AND (pl.nucleotide + pl.nucleotideLength) <= :end )) "
+ "and pl.chromosome = :chromosome and g.class='GeneImpl' ";
query = query + " and " + SequenceBinUtils.addBinToQuery( "pl", targetStart, targetEnd );
String[] params;
Object[] vals;
if ( strand != null ) {
query = query + " and pl.strand = :strand ";
params = new String[] { "chromosome", "start", "end", "strand" };
vals = new Object[] { chrom, targetStart, targetEnd, strand };
} else {
params = new String[] { "chromosome", "start", "end" };
vals = new Object[] { chrom, targetStart, targetEnd };
}
return getHibernateTemplate().findByNamedParam( query, params, vals );
}
/**
* @param css
* @return
* @throws Exception
*/
private Map<Long, Collection<Long>> getCS2GeneMap( Collection<Long> css ) throws Exception {
Map<Long, Collection<Long>> csId2geneIds = new HashMap<Long, Collection<Long>>();
if ( css == null || css.size() == 0 ) {
return csId2geneIds;
}
int CHUNK_SIZE = 1000;
Session session = this.getSession();
if ( css.size() <= CHUNK_SIZE ) {
processCS2GeneChunk( csId2geneIds, css, session );
return csId2geneIds;
}
Collection<Long> batch = new HashSet<Long>();
for ( Long csId : css ) {
batch.add( csId );
if ( batch.size() == CHUNK_SIZE ) {
processCS2GeneChunk( csId2geneIds, batch, session );
batch.clear();
}
}
if ( batch.size() > 0 ) {
processCS2GeneChunk( csId2geneIds, batch, session );
}
return csId2geneIds;
}
/**
* @param ees
* @return
*/
private Collection<Long> getEEIds( Collection<? extends BioAssaySet> ees ) {
Collection<Long> eeIds = new ArrayList<Long>();
for ( BioAssaySet e : ees ) {
eeIds.add( e.getId() );
}
return eeIds;
}
/**
* For queries involving multiple genes as inputs. Query outputs:
* <ol >
* <li>output gene id</li>
* <li>output gene name</li>
* <li>output gene official name</li>
* <li>expression experiment
* <li>pvalue</li>
* <li>score</li>
* <li>query gene probe id</li>
* <li>output gene probe id</li>
* <li>output gene type (predicted etc)</li>
* <li>expression experiment name</li>
* </ol>
*
* @param p2pClassName
* @param in
* @param out
* @param eeIds this is required.
* @param knownGenesOnly
* @param interGeneOnly true to restrict to links among the query genes only (this will not work correctly if you
* only put in one gene!)
* @return
*/
private String getNativeBatchQueryString( String p2pClassName, String in, String out, Collection<Long> eeIds,
boolean knownGenesOnly, boolean interGeneOnly ) {
String inKey = in.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK";
String outKey = out.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK";
String eeClause = "";
// note that with current index scheme, you have to have EE ids specified.
if ( eeIds.size() > 0 ) {
eeClause += " coexp.EXPRESSION_EXPERIMENT_FK in (";
eeClause += StringUtils.join( eeIds.iterator(), "," );
eeClause += ") AND ";
} else {
log.warn( "This query may run very slowly without EE restriction" );
}
String knownGeneClause = "";
if ( knownGenesOnly ) {
knownGeneClause = " gcOut.GTYPE = 'GeneImpl' AND ";
}
String interGeneOnlyClause = "";
if ( interGeneOnly ) {
interGeneOnlyClause = " AND gcOut.GENE in (:ids) ";
}
String p2pClass = getP2PTableNameForClassName( p2pClassName );
/**
* Fields:
*
* <pre>
* 0 Geneid
* 1 exper
* 2 pvalue
* 3 score
* 4 csin
* 5 csout
* 6 genetype
* 7 queryGene id
* </pre>
*/
String query = "SELECT gcOut.GENE as id, coexp.EXPRESSION_EXPERIMENT_FK as exper, coexp.PVALUE as pvalue, coexp.SCORE as score, "
+ "gcIn.CS as csIdIn, gcOut.CS as csIdOut, gcOut.GTYPE as geneType, gcIn.GENE as queryGeneId FROM GENE2CS gcIn INNER JOIN "
+ p2pClass
+ " coexp FORCE INDEX (EEKey) ON gcIn.CS=coexp."
+ inKey
+ " "
+ " INNER JOIN GENE2CS gcOut ON gcOut.CS=coexp."
+ outKey
+ " INNER JOIN INVESTIGATION ee ON ee.ID=coexp.EXPRESSION_EXPERIMENT_FK "
+ " WHERE "
+ eeClause
+ knownGeneClause + " gcIn.GENE in (:ids) " + interGeneOnlyClause;
return query;
}
/**
* Query outputs:
* <ol >
* <li>output gene id</li>
* <li>output gene name</li>
* <li>output gene official name</li>
* <li>expression experiment
* <li>pvalue</li>
* <li>score</li>
* <li>query gene probe id</li>
* <li>output gene probe id</li>
* <li>output gene type (predicted etc)</li>
* <li>expression experiment name</li>
* </ol>
*
* @param p2pClassName
* @param in
* @param out
* @param eeIds this is required.
* @param knownGenesOnly
* @return
*/
private String getNativeQueryString( String p2pClassName, String in, String out, Collection<Long> eeIds,
boolean knownGenesOnly ) {
String inKey = in.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK";
String outKey = out.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK";
String eeClause = "";
// note that with current index scheme, you have to have EE ids specified.
if ( eeIds.size() > 0 ) {
eeClause += " coexp.EXPRESSION_EXPERIMENT_FK in (";
eeClause += StringUtils.join( eeIds.iterator(), "," );
eeClause += ") AND ";
} else {
log.warn( "This query may run very slowly without EE restriction" );
}
// eeClause = " coexp.EXPRESSION_EXPERIMENT_FK = " + eeIds.iterator().next() + " AND ";
String knownGeneClause = "";
if ( knownGenesOnly ) {
knownGeneClause = " gcOut.GTYPE = 'GeneImpl' AND ";
}
String p2pClass = getP2PTableNameForClassName( p2pClassName );
/**
* Fields:
*
* <pre>
* 0 Geneid
* 1 exper
* 2 pvalue
* 3 score
* 4 csin
* 5 csout
* 6 genetype
* </pre>
*/
String query = "SELECT gcOut.GENE as id, coexp.EXPRESSION_EXPERIMENT_FK as exper, coexp.PVALUE as pvalue, coexp.SCORE as score, "
+ "gcIn.CS as csIdIn, gcOut.CS as csIdOut, gcOut.GTYPE as geneType FROM GENE2CS gcIn INNER JOIN "
+ p2pClass
+ " coexp FORCE INDEX (EEKey) ON gcIn.CS=coexp."
+ inKey
+ " "
+ " INNER JOIN GENE2CS gcOut ON gcOut.CS=coexp."
+ outKey
+ " INNER JOIN INVESTIGATION ee ON ee.ID=coexp.EXPRESSION_EXPERIMENT_FK "
+ " WHERE "
+ eeClause
+ knownGeneClause + " gcIn.GENE=:id ";
// AND gcOut.GENE <> :id // Omit , see below!
/*
* Important Implementation Note: The clause to exclude self-hits actually causes problems. When a self-match
* happens, it means that the probe in question hybridizes to the query gene. When the probe in question also
* hybridizes to other genes, we need to know that that 'link' is potentially due to a self-match. Such probes
* are excluded from later analysis. If we throw those matches out at the SQL query stage, it is hard for us to
* detect such crosshybridization problems later.
*/
// log.info( query );
return query;
}
/**
* @param givenG
* @return
*/
private String getP2PClassName( Gene givenG ) {
if ( TaxonUtility.isHuman( givenG.getTaxon() ) )
return "HumanProbeCoExpressionImpl";
else if ( TaxonUtility.isMouse( givenG.getTaxon() ) )
return "MouseProbeCoExpressionImpl";
else if ( TaxonUtility.isRat( givenG.getTaxon() ) )
return "RatProbeCoExpressionImpl";
else
return "OtherProbeCoExpressionImpl";
}
/**
* @param className
* @return
*/
private String getP2PTableNameForClassName( String className ) {
if ( className.equals( "HumanProbeCoExpressionImpl" ) )
return "HUMAN_PROBE_CO_EXPRESSION";
else if ( className.equals( "MouseProbeCoExpressionImpl" ) )
return "MOUSE_PROBE_CO_EXPRESSION";
else if ( className.equals( "RatProbeCoExpressionImpl" ) )
return "RAT_PROBE_CO_EXPRESSION";
else
return "OTHER_PROBE_CO_EXPRESSION";
}
/**
* Merge in the cached results. The CVOs that are cached only contain results for a single expression experiment.
*/
private void mergeCachedCoexpressionResults( CoexpressionCollectionValueObject coexpressions,
Map<Long, Collection<CoexpressionCacheValueObject>> cachedResults ) {
for ( Long eeid : cachedResults.keySet() ) {
Collection<CoexpressionCacheValueObject> cache = cachedResults.get( eeid );
for ( CoexpressionCacheValueObject cachedCVO : cache ) {
assert cachedCVO.getQueryProbe() != null;
assert cachedCVO.getCoexpressedProbe() != null;
if ( cachedCVO.getQueryGene().getId().equals( cachedCVO.getCoexpressedGene() ) ) {
// defensive check against self-links being in the cache (shouldn't happen)
continue;
}
addResult( coexpressions, eeid, cachedCVO.getQueryGene(), cachedCVO.getQueryProbe(), cachedCVO
.getPvalue(), cachedCVO.getScore(), cachedCVO.getCoexpressedGene(), cachedCVO.getGeneType(),
cachedCVO.getCoexpressedProbe() );
assert coexpressions.contains( cachedCVO.getCoexpressedGene() );
}
}
}
/**
* @param coexpressions
* @param knownGenesOnly this probably doesn't matter much, as results are already determined, but defensive
* programming.
* <p>
* Performance notes: Empirically this rarely takes very long, definitely less than 1s in vast majority of
* cases. I changed the logging to trigger at 250ms get a bit better resolution - PP feb 2010
*/
private void postProcess( CoexpressionCollectionValueObject coexpressions, boolean knownGenesOnly ) {
StopWatch watch = new StopWatch();
watch.start();
postProcessKnownGenes( coexpressions );
if ( !knownGenesOnly ) {
postProcessProbeAlignedRegions( coexpressions );
postProcessPredictedGenes( coexpressions );
}
watch.stop();
Long elapsed = watch.getTime();
coexpressions.setPostProcessTime( elapsed );
if ( elapsed > 250 ) log.info( "Specificity check: " + elapsed + "ms." );
}
/**
* @param coexpressions
*/
private void postProcessKnownGenes( CoexpressionCollectionValueObject coexpressions ) {
if ( coexpressions.getNumKnownGenes() == 0 ) return;
CoexpressedGenesDetails knownGeneCoexpression = coexpressions.getKnownGeneCoexpression();
knownGeneCoexpression.postProcess();
}
/**
* @param coexpressions
*/
private void postProcessPredictedGenes( CoexpressionCollectionValueObject coexpressions ) {
if ( coexpressions.getNumPredictedGenes() == 0 ) return;
CoexpressedGenesDetails predictedCoexpressionType = coexpressions.getPredictedGeneCoexpression();
predictedCoexpressionType.postProcess();
}
/**
* @param coexpressions
*/
private void postProcessProbeAlignedRegions( CoexpressionCollectionValueObject coexpressions ) {
if ( coexpressions.getNumProbeAlignedRegions() == 0 ) return;
CoexpressedGenesDetails probeAlignedCoexpressionType = coexpressions.getProbeAlignedRegionCoexpression();
probeAlignedCoexpressionType.postProcess();
}
/**
* Fill in specificity information.
*
* @param knownGenesOnly
* @param coexpressions
* @throws Exception <p>
* Performance notes: This often takes 3-5 seconds. PP Feb 2010
*/
private void postProcessSpecificity( boolean knownGenesOnly, final CoexpressionCollectionValueObject coexpressions )
throws Exception {
// fill in information about the query gene
StopWatch timer = new StopWatch();
timer.start();
Collection<Long> queryGeneProbeIds = coexpressions.getQueryGeneProbes();
Collection<Long> targetGeneProbeIds = coexpressions.getTargetGeneProbes();
Map<Long, Collection<Long>> querySpecificity = getCS2GeneMap( queryGeneProbeIds );
Map<Long, Collection<Long>> targetSpecificity = getCS2GeneMap( targetGeneProbeIds );
if ( timer.getTime() > 1000 ) {
log.info( "Specificity postprocess CS2GeneMap: " + timer.getTime() + "ms" );
}
timer.stop();
timer.reset();
coexpressions.setQueryGeneSpecifityInfo( querySpecificity );
coexpressions.setTargetGeneSpecificityInfo( targetSpecificity );
postProcess( coexpressions, knownGenesOnly );
}
/**
* Perform and process the coexpression query.
*
* @param queryGene
* @param geneMap
* @param queryObject
*/
private void processCoexpQuery( Gene queryGene, Query queryObject, CoexpressionCollectionValueObject coexpressions ) {
ScrollableResults scroll = queryObject.scroll( ScrollMode.FORWARD_ONLY );
while ( scroll.next() ) {
processCoexpQueryResult( queryGene, scroll, coexpressions );
}
}
/**
* @param queryGenes
* @param queryObject
* @param coexpressions
*/
private void processCoexpQuery( Map<Long, Gene> queryGenes, Query queryObject,
Map<Gene, CoexpressionCollectionValueObject> coexpressions ) {
ScrollableResults scroll = queryObject.scroll( ScrollMode.FORWARD_ONLY );
while ( scroll.next() ) {
processCoexpQueryResult( queryGenes, scroll, coexpressions );
}
}
/**
* Process a single query result from the coexpression search, converting it into a
* CoexpressionCollectionValueObject
*
* @param queryGene
* @param geneMap
* @param resultSet
* @see getFastNativeQueryString for the parameterization of the query output.
*/
private void processCoexpQueryResult( Gene queryGene, ScrollableResults resultSet,
CoexpressionCollectionValueObject coexpressions ) {
Long coexpressedGene = resultSet.getLong( 0 );
if ( coexpressedGene.equals( queryGene.getId() ) ) {
return;
}
Long eeID = resultSet.getLong( 1 );
Double pvalue = resultSet.getDouble( 2 );
Double score = resultSet.getDouble( 3 );
Long queryProbe = resultSet.getLong( 4 );
Long coexpressedProbe = resultSet.getLong( 5 );
String geneType = resultSet.getString( 6 );
addResult( coexpressions, eeID, queryGene, queryProbe, pvalue, score, coexpressedGene, geneType,
coexpressedProbe );
/*
* Cache the result.
*/
if ( this.getProbe2ProbeCoexpressionCache().isEnabled() ) {
CoexpressionCacheValueObject coExVOForCache = new CoexpressionCacheValueObject();
coExVOForCache.setQueryGene( queryGene );
coExVOForCache.setCoexpressedGene( coexpressedGene );
coExVOForCache.setGeneType( geneType );
coExVOForCache.setExpressionExperiment( eeID );
coExVOForCache.setScore( score );
coExVOForCache.setPvalue( pvalue );
coExVOForCache.setQueryProbe( queryProbe );
coExVOForCache.setCoexpressedProbe( coexpressedProbe );
if ( log.isDebugEnabled() ) log.debug( "Caching: " + coExVOForCache );
this.getProbe2ProbeCoexpressionCache().addToCache( coExVOForCache );
}
}
/**
* @param queryGenes
* @param resultSet
* @param coexpressions
*/
private void processCoexpQueryResult( Map<Long, Gene> queryGenes, ScrollableResults resultSet,
Map<Gene, CoexpressionCollectionValueObject> coexpressions ) {
Long coexpressedGene = resultSet.getLong( 0 );
Long eeID = resultSet.getLong( 1 );
Double pvalue = resultSet.getDouble( 2 );
Double score = resultSet.getDouble( 3 );
Long queryProbe = resultSet.getLong( 4 );
Long coexpressedProbe = resultSet.getLong( 5 );
String geneType = resultSet.getString( 6 );
Long queryGeneId = resultSet.getLong( 7 );
if ( queryGeneId.equals( coexpressedGene ) ) {
return;
}
Gene queryGene = queryGenes.get( queryGeneId );
assert queryGene != null : queryGeneId + " did not match given queries";
CoexpressionCollectionValueObject ccvo = coexpressions.get( queryGene );
assert ccvo != null;
addResult( ccvo, eeID, queryGene, queryProbe, pvalue, score, coexpressedGene, geneType, coexpressedProbe );
/*
* Cache the result.
*/
if ( this.getProbe2ProbeCoexpressionCache().isEnabled() ) {
CoexpressionCacheValueObject coExVOForCache = new CoexpressionCacheValueObject();
coExVOForCache.setQueryGene( queryGene );
coExVOForCache.setCoexpressedGene( coexpressedGene );
coExVOForCache.setGeneType( geneType );
coExVOForCache.setExpressionExperiment( eeID );
coExVOForCache.setScore( score );
coExVOForCache.setPvalue( pvalue );
coExVOForCache.setQueryProbe( queryProbe );
coExVOForCache.setCoexpressedProbe( coexpressedProbe );
if ( log.isDebugEnabled() ) log.debug( "Caching: " + coExVOForCache );
this.getProbe2ProbeCoexpressionCache().addToCache( coExVOForCache );
}
}
/**
* @param csId2geneIds
* @param csIdChunk
* @param session
*/
private void processCS2GeneChunk( Map<Long, Collection<Long>> csId2geneIds, Collection<Long> csIdChunk,
Session session ) {
assert csIdChunk.size() > 0;
/*
* Check the cache first.
*/
Collection<Long> neededCs = new HashSet<Long>();
for ( Long csid : csIdChunk ) {
if ( gene2CsCache.containsKey( csid ) && gene2CsCache.get( csid ) != null ) {
csId2geneIds.put( csid, gene2CsCache.get( csid ) );
} else {
neededCs.add( csid );
}
}
if ( neededCs.size() == 0 ) {
return;
}
String queryString = "SELECT CS as id, GENE as geneId FROM GENE2CS WHERE CS in ("
+ StringUtils.join( neededCs, "," ) + ")";
org.hibernate.SQLQuery queryObject = session.createSQLQuery( queryString );
queryObject.addScalar( "id", new LongType() );
queryObject.addScalar( "geneId", new LongType() );
ScrollableResults scroll = queryObject.scroll( ScrollMode.FORWARD_ONLY );
while ( scroll.next() ) {
Long csid = scroll.getLong( 0 );
Long geneId = scroll.getLong( 1 );
if ( !csId2geneIds.containsKey( csid ) ) {
csId2geneIds.put( csid, new HashSet<Long>() );
}
csId2geneIds.get( csid ).add( geneId );
}
/*
* FIXME this could be repetitive.
*/
gene2CsCache.putAll( csId2geneIds );
}
/**
* For batch queries
*
* @param genes
* @param ees
* @param id
* @param eeIds
* @param queryString
* @return
*/
private org.hibernate.Query setCoexpQueryParameters( Session session, Collection<Gene> genes, long id,
String queryString ) {
org.hibernate.SQLQuery queryObject;
queryObject = session.createSQLQuery( queryString ); // for native query.
queryObject.addScalar( "id", new LongType() ); // gene out.
queryObject.addScalar( "exper", new LongType() );
queryObject.addScalar( "pvalue", new DoubleType() );
queryObject.addScalar( "score", new DoubleType() );
queryObject.addScalar( "csIdIn", new LongType() );
queryObject.addScalar( "csIdOut", new LongType() );
queryObject.addScalar( "geneType", new StringType() );
queryObject.addScalar( "queryGeneId", new LongType() );
Collection<Long> ids = new HashSet<Long>();
for ( Gene gene : genes ) {
ids.add( gene.getId() );
}
queryObject.setParameterList( "ids", ids );
return queryObject;
}
/**
* @param gene
* @param ees
* @param id
* @param eeIds
* @param queryString
* @return
*/
private org.hibernate.Query setCoexpQueryParameters( Session session, Gene gene, long id, String queryString ) {
org.hibernate.SQLQuery queryObject;
queryObject = session.createSQLQuery( queryString ); // for native query.
queryObject.addScalar( "id", new LongType() ); // gene out.
queryObject.addScalar( "exper", new LongType() );
queryObject.addScalar( "pvalue", new DoubleType() );
queryObject.addScalar( "score", new DoubleType() );
queryObject.addScalar( "csIdIn", new LongType() );
queryObject.addScalar( "csIdOut", new LongType() );
queryObject.addScalar( "geneType", new StringType() );
queryObject.setLong( "id", id );
return queryObject;
}
@SuppressWarnings("unchecked")
@Override
protected Integer handleCountAll() throws Exception {
final String query = "select count(*) from GeneImpl";
List r = getHibernateTemplate().find( query );
return ( Integer ) r.iterator().next();
}
@SuppressWarnings( { "unchecked", "cast" })
@Override
protected Gene handleFindByAccession( String accession, ExternalDatabase source ) throws Exception {
Collection<Gene> genes;
final String accessionQuery = "select g from GeneImpl g inner join g.accessions a where a.accession = :accession";
final String externalDbquery = accessionQuery + " and a.externalDatabase = :source";
if ( source == null ) {
genes = this.getHibernateTemplate().findByNamedParam( accessionQuery, "accession", "accession" );
if ( genes.size() == 0 ) {
genes = this.findByNcbiId( accession );
}
} else {
if ( source.getName().equalsIgnoreCase( "NCBI" ) ) {
genes = this.findByNcbiId( accession );
} else {
genes = this.getHibernateTemplate().findByNamedParam( externalDbquery,
new String[] { "accession", "source" }, new Object[] { accession, source } );
}
}
if ( genes.size() > 0 ) {
return ( Gene ) genes.iterator().next();
}
return null;
}
/**
* Gets all the genes referred to by the alias defined by the search string.
*
* @param search
* @return Collection
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleFindByAlias( String search ) throws Exception {
final String queryString = "select distinct g from GeneImpl as g inner join g.aliases als where als.alias = :search";
return getHibernateTemplate().findByNamedParam( queryString, "search", search );
}
@SuppressWarnings("unchecked")
@Override
protected Gene handleFindByOfficialSymbol( String symbol, Taxon taxon ) {
final String queryString = "select distinct g from GeneImpl as g inner join g.taxon t where g.officialSymbol = :symbol and t= :taxon";
List results = getHibernateTemplate().findByNamedParam( queryString, new String[] { "symbol", "taxon" },
new Object[] { symbol, taxon } );
if ( results.size() == 0 ) {
return null;
} else if ( results.size() > 1 ) {
log.warn( "Multiple genes match " + symbol + " in " + taxon + ", return first hit" );
}
return ( Gene ) results.iterator().next();
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleGetCoexpressedGenes(java.util.Collection, java.util.Collection,
* java.lang.Integer, boolean)
*/
@Override
protected Map<Gene, CoexpressionCollectionValueObject> handleGetCoexpressedGenes( final Collection<Gene> genes,
Collection<? extends BioAssaySet> ees, Integer stringency, boolean knownGenesOnly, boolean interGeneOnly )
throws Exception {
if ( genes.size() == 0 || ees.size() == 0 ) {
throw new IllegalArgumentException( "nothing to search" );
}
final Map<Gene, CoexpressionCollectionValueObject> coexpressions = new HashMap<Gene, CoexpressionCollectionValueObject>();
Map<Long, Gene> queryGenes = new HashMap<Long, Gene>();
for ( Gene g : genes ) {
queryGenes.put( g.getId(), g );
coexpressions.put( g, new CoexpressionCollectionValueObject( g, stringency ) );
}
if ( genes.size() == 1 ) {
Gene soleQueryGene = genes.iterator().next();
coexpressions
.put( soleQueryGene, this.getCoexpressedGenes( soleQueryGene, ees, stringency, knownGenesOnly ) );
return coexpressions;
}
/*
* FIXME: check the cache. This is kind of a pain, because each query gene might have different experiments to
* consider. So we don't really remove datasets from consideration very readily. An exception might be where
* interGeneOnly is true.
*/
/*
* NOTE: assuming all genes are from the same taxon!
*/
Gene givenG = genes.iterator().next();
final long id = givenG.getId();
log.debug( "Gene: " + givenG.getName() );
final String p2pClassName = getP2PClassName( givenG );
final Collection<Long> eeIds = getEEIds( ees );
String queryString = getNativeBatchQueryString( p2pClassName, "firstVector", "secondVector", eeIds,
knownGenesOnly, interGeneOnly );
Session session = this.getSession( false );
org.hibernate.Query queryObject = setCoexpQueryParameters( session, genes, id, queryString );
StopWatch overallWatch = new StopWatch();
overallWatch.start();
// This is the actual business of querying the database.
processCoexpQuery( queryGenes, queryObject, coexpressions );
overallWatch.stop();
if ( overallWatch.getTime() > 1000 ) {
log.info( "Raw query for " + genes.size() + " genes in batch: " + overallWatch.getTime() + "ms" );
}
for ( CoexpressionCollectionValueObject coexp : coexpressions.values() ) {
postProcessSpecificity( knownGenesOnly, coexp );
}
return coexpressions;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDao#getGeneCoexpressionNodeDegree(java.util.Collection, java.util.Collection)
*/
public Map<Gene, Double> getGeneCoexpressionNodeDegree( Collection<Gene> genes,
Collection<? extends BioAssaySet> ees ) {
Map<CompositeSequence, Collection<Gene>> cs2GeneMap = CommonQueries.getCs2GeneMap( genes, this.getSession() );
/*
* When we aggregate, it's only over data sets that had the gene tested (inner join)
*/
List<?> r = this.getHibernateTemplate().findByNamedParam(
"select p.probe, p.nodeDegreeRank from ProbeCoexpressionAnalysisImpl pca "
+ "join pca.probesUsed p where pca.experimentAnalyzed in (:ees) and p.probe in (:ps)",
new String[] { "ps", "ees" }, new Object[] { cs2GeneMap.keySet(), ees } );
Map<Gene, DoubleArrayList> interm = new HashMap<Gene, DoubleArrayList>();
for ( Gene g : genes ) {
interm.put( g, new DoubleArrayList() );
}
for ( Object o : r ) {
Object[] oa = ( Object[] ) o;
CompositeSequence cs = ( CompositeSequence ) oa[0];
Double nodeDegreeRank = ( Double ) oa[1];
Collection<Gene> gs = cs2GeneMap.get( cs );
// if ( gs.size() > 1 ) continue; // nonspecific - perhaps control this.
interm.get( gs.iterator().next() ).add( nodeDegreeRank );
}
// aggregate.
Map<Gene, Double> result = new HashMap<Gene, Double>();
for ( Gene g : interm.keySet() ) {
DoubleArrayList vals = interm.get( g );
/*
* Note: under the null, each node degree is drawn from a uniform(0,1); sampling properties for the mean of
* this are the same as for pvalues, so we treat them thusly. (My first pass implementation just used the
* mean). Note we don't do 1 - fp here -- high node degrees are still represented as values near 1 after
* this transformation. See bug 2379
*/
result.put( g, MetaAnalysis.fisherCombinePvalues( vals ) );
}
return result;
}
@Override
public Map<BioAssaySet, Double> getGeneCoexpressionNodeDegree( Gene gene, Collection<? extends BioAssaySet> ees ) {
Collection<CompositeSequence> probes = CommonQueries.getCompositeSequences( gene, this.getSession() );
List<?> r = this.getHibernateTemplate().findByNamedParam(
"select pca.experimentAnalyzed, p.nodeDegreeRank from ProbeCoexpressionAnalysisImpl pca "
+ "join pca.probesUsed p where pca.experimentAnalyzed ee in (:ees) and p.probe in (:ps)",
new String[] { "ps", "ees" }, new Object[] { probes, ees } );
Map<BioAssaySet, Double> result = new HashMap<BioAssaySet, Double>();
for ( Object o : r ) {
Object[] oa = ( Object[] ) o;
BioAssaySet ee = ( BioAssaySet ) oa[1];
Double nodeDegreeRank = ( Double ) oa[2];
result.put( ee, nodeDegreeRank );
}
return result;
}
/**
* Gets all the genes that are coexpressed with another gene based on stored coexpression 'links', essentially as
* described in Lee et al. (2004) Genome Research.
*
* @param gene to use as the query
* @param ees Data sets to restrict the search to.
* @param stringency minimum number of data sets the coexpression has to occur in before it 'counts'.
* @param knownGenesOnly
* @return Collection of CoexpressionCollectionValueObjects. This needs to be 'postprocessed' before it has all the
* data needed for web display.
*/
@Override
protected CoexpressionCollectionValueObject handleGetCoexpressedGenes( final Gene gene,
Collection<? extends BioAssaySet> ees, Integer stringency, boolean knownGenesOnly ) throws Exception {
Gene givenG = gene;
final long id = givenG.getId();
log.debug( "Gene: " + gene.getName() );
final String p2pClassName = getP2PClassName( givenG );
final CoexpressionCollectionValueObject coexpressions = new CoexpressionCollectionValueObject( gene, stringency );
if ( ees.size() == 0 ) {
log.debug( "No experiments selected" );
coexpressions.setErrorState( "No experiments were selected" );
return coexpressions;
}
StopWatch overallWatch = new StopWatch();
overallWatch.start();
/*
* Check cache first, if we have already queried experiment X for the query, then we don't need to query
* experiment X at all.
*/
Collection<BioAssaySet> eesToSearch = new HashSet<BioAssaySet>();
Map<Long, Collection<CoexpressionCacheValueObject>> cachedResults = new HashMap<Long, Collection<CoexpressionCacheValueObject>>();
for ( BioAssaySet ee : ees ) {
Collection<CoexpressionCacheValueObject> eeResults = this.getProbe2ProbeCoexpressionCache().get( ee, gene );
if ( eeResults != null ) {
cachedResults.put( ee.getId(), eeResults );
if ( log.isDebugEnabled() ) log.debug( "Cache hit! for ee=" + ee.getId() );
} else {
eesToSearch.add( ee );
}
}
overallWatch.stop();
if ( overallWatch.getTime() > 100 ) {
if ( log.isInfoEnabled() ) log.info( "Probe2probe cache check: " + overallWatch.getTime() + "ms" );
}
overallWatch.reset();
overallWatch.start();
if ( eesToSearch.size() > 0 ) {
final Collection<Long> eeIds = getEEIds( eesToSearch );
String queryString = getNativeQueryString( p2pClassName, "firstVector", "secondVector", eeIds,
knownGenesOnly );
Session session = this.getSession( false );
org.hibernate.Query queryObject = setCoexpQueryParameters( session, gene, id, queryString );
// This is the actual business of querying the database.
processCoexpQuery( gene, queryObject, coexpressions );
}
overallWatch.stop();
if ( overallWatch.getTime() > 1000 ) {
log.info( "Raw query: " + overallWatch.getTime() + "ms" );
}
coexpressions.setDbQuerySeconds( overallWatch.getTime() );
overallWatch.reset();
overallWatch.start();
if ( cachedResults.size() > 0 ) {
mergeCachedCoexpressionResults( coexpressions, cachedResults );
overallWatch.stop();
if ( overallWatch.getTime() > 100 ) {
log.info( "Merge cached: " + overallWatch.getTime() + "ms" );
}
overallWatch.reset();
overallWatch.start();
}
if ( coexpressions.getQueryGeneProbes().size() == 0 ) {
if ( log.isDebugEnabled() ) log.debug( "Coexpression query gene " + gene + " has no probes" );
coexpressions.setErrorState( "Query gene " + gene + " has no probes" );
return coexpressions;
}
postProcessSpecificity( knownGenesOnly, coexpressions );
return coexpressions;
}
/**
* Gets a count of the CompositeSequences related to the gene identified by the given id.
*
* @param id
* @return Collection
*/
@SuppressWarnings("unchecked")
@Override
protected long handleGetCompositeSequenceCountById( long id ) throws Exception {
final String queryString = "select count(distinct cs) from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl"
+ " as bs2gp, CompositeSequenceImpl as cs where gp=bs2gp.geneProduct "
+ " and cs.biologicalCharacteristic=bs2gp.bioSequence " + " and gene.id = :id ";
List r = getHibernateTemplate().findByNamedParam( queryString, "id", id );
return ( Long ) r.iterator().next();
}
/*
* Gets all the CompositeSequences related to the gene identified by the given gene and arrayDesign. (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleGetCompositeSequences(ubic.gemma.model.genome.Gene,
* ubic.gemma.model.expression.arrayDesign.ArrayDesign)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleGetCompositeSequences( Gene gene, ArrayDesign arrayDesign ) throws Exception {
Collection<CompositeSequence> compSeq = null;
final String queryString = "select distinct cs from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl"
+ " as bs2gp, CompositeSequenceImpl as cs where gp=bs2gp.geneProduct "
+ " and cs.biologicalCharacteristic=bs2gp.bioSequence "
+ " and gene = :gene and cs.arrayDesign = :arrayDesign ";
try {
org.hibernate.Query queryObject = super.getSession().createQuery( queryString );
queryObject.setParameter( "arrayDesign", arrayDesign );
queryObject.setParameter( "gene", gene );
compSeq = queryObject.list();
} catch ( org.hibernate.HibernateException ex ) {
throw super.convertHibernateAccessException( ex );
}
return compSeq;
}
/**
* Gets all the CompositeSequences related to the gene identified by the given id.
*
* @param id
* @return Collection
*/
@SuppressWarnings("unchecked")
@Override
protected Collection<CompositeSequence> handleGetCompositeSequencesById( long id ) throws Exception {
final String queryString = "select distinct cs from GeneImpl as gene inner join gene.products as gp, BioSequence2GeneProductImpl "
+ " as bs2gp , CompositeSequenceImpl as cs where gp=bs2gp.geneProduct "
+ " and cs.biologicalCharacteristic=bs2gp.bioSequence " + " and gene.id = :id ";
return getHibernateTemplate().findByNamedParam( queryString, "id", id );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleGetGenesByTaxon(ubic.gemma.model.genome.Taxon)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleGetGenesByTaxon( Taxon taxon ) throws Exception {
if ( taxon == null ) {
throw new IllegalArgumentException( "Must provide taxon" );
}
final String queryString = "select gene from GeneImpl as gene where gene.taxon = :taxon ";
return getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleGetMicroRnaByTaxon(ubic.gemma.model.genome.Taxon)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection<Gene> handleGetMicroRnaByTaxon( Taxon taxon ) throws Exception {
if ( taxon == null ) {
throw new IllegalArgumentException( "Must provide taxon" );
}
final String queryString = "select gene from GeneImpl as gene where gene.taxon = :taxon"
+ " and (gene.description like '%micro RNA or sno RNA' OR gene.description = 'miRNA')";
return getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleLoadKnownGenes(ubic.gemma.model.genome.Taxon)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection<Gene> handleLoadKnownGenes( Taxon taxon ) throws Exception {
if ( taxon == null ) {
throw new IllegalArgumentException( "Must provide taxon" );
}
final String queryString = "select gene from GeneImpl as gene fetch all properties where gene.taxon = :taxon"
+ " and gene.class = " + CoexpressionCollectionValueObject.GENE_IMPL;
return this.getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleLoad(java.util.Collection)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleLoadMultiple( Collection ids ) throws Exception {
if ( ids.size() == 0 ) {
return new HashSet();
}
int BATCH_SIZE = 2000;
if ( ids.size() > BATCH_SIZE ) {
log.info( "Loading " + ids.size() + " genes ..." );
}
final String queryString = "select gene from GeneImpl gene where gene.id in (:ids)";
Collection<Long> batch = new HashSet<Long>();
Collection<Gene> genes = new HashSet<Gene>();
for ( Long gene : ( Collection<Long> ) ids ) {
batch.add( gene );
if ( batch.size() == BATCH_SIZE ) {
genes.addAll( getHibernateTemplate().findByNamedParam( queryString, "ids", batch ) );
batch.clear();
}
}
if ( batch.size() > 0 ) {
genes.addAll( getHibernateTemplate().findByNamedParam( queryString, "ids", batch ) );
}
if ( ids.size() > BATCH_SIZE ) {
log.info( "... done" );
}
return genes;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleLoadPredictedGenes(ubic.gemma.model.genome.Taxon)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection<PredictedGene> handleLoadPredictedGenes( Taxon taxon ) throws Exception {
final String queryString = "select gene from GeneImpl as gene fetch all properties where gene.taxon = :taxon"
+ " and gene.class = " + CoexpressionCollectionValueObject.PREDICTED_GENE_IMPL;
return this.getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleLoadProbeAlignedRegions(ubic.gemma.model.genome.Taxon)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection<ProbeAlignedRegion> handleLoadProbeAlignedRegions( Taxon taxon ) throws Exception {
final String queryString = "select gene from GeneImpl as gene fetch all properties where gene.taxon = :taxon"
+ " and gene.class = " + CoexpressionCollectionValueObject.PROBE_ALIGNED_REGION_IMPL;
return this.getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleThaw(ubic.gemma.model.genome.Gene)
*/
@Override
protected Gene handleThaw( final Gene gene ) throws Exception {
if ( gene.getId() == null ) return gene;
List<?> res = this
.getHibernateTemplate()
.findByNamedParam(
"select distinct g from GeneImpl g "
+ "left join fetch g.aliases left join fetch g.accessions acc"
+ " left join fetch acc.externalDatabase left join fetch g.products gp "
+ " left join fetch g.auditTrail at left join fetch at.events "
+ "left join fetch gp.accessions gpacc left join fetch gpacc.externalDatabase left join"
+ " fetch gp.physicalLocation gppl left join fetch gppl.chromosome chr left join fetch chr.taxon "
+ " left join fetch g.taxon t left join fetch t.externalDatabase" + " where g.id=:gid",
"gid", gene.getId() );
return ( Gene ) res.iterator().next();
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.GeneDaoBase#handleThawLite(java.util.Collection)
*/
@Override
protected Collection<Gene> handleThawLite( final Collection<Gene> genes ) throws Exception {
if ( genes.isEmpty() ) return new HashSet<Gene>();
Collection<Gene> result = new HashSet<Gene>();
Collection<Gene> batch = new HashSet<Gene>();
for ( Gene g : genes ) {
batch.add( g );
if ( batch.size() == BATCH_SIZE ) {
result.addAll( loadThawed( EntityUtils.getIds( batch ) ) );
batch.clear();
}
}
if ( !batch.isEmpty() ) {
result.addAll( loadThawed( EntityUtils.getIds( batch ) ) );
}
return result;
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import processing.app.debug.Compiler;
import processing.app.debug.Target;
import processing.app.helpers.FileUtils;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.javax.swing.filechooser.FileNameExtensionFilter;
import processing.app.tools.ZipDeflater;
import processing.core.*;
import static processing.app.I18n._;
/**
* The base class for the main processing application.
* Primary role of this class is for platform identification and
* general interaction with the system (launching URLs, loading
* files and images, etc) that comes from that.
*/
public class Base {
public static final int REVISION = 106;
/** This might be replaced by main() if there's a lib/version.txt file. */
static String VERSION_NAME = "0106";
/** Set true if this a proper release rather than a numbered revision. */
static public boolean RELEASE = false;
static String teensyduino_version = null;
static HashMap<Integer, String> platformNames = new HashMap<Integer, String>();
static {
platformNames.put(PConstants.WINDOWS, "windows");
platformNames.put(PConstants.MACOSX, "macosx");
platformNames.put(PConstants.LINUX, "linux");
}
static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>();
static {
platformIndices.put("windows", PConstants.WINDOWS);
platformIndices.put("macosx", PConstants.MACOSX);
platformIndices.put("linux", PConstants.LINUX);
}
static Platform platform;
static private boolean commandLine;
// A single instance of the preferences window
Preferences preferencesFrame;
// set to true after the first time the menu is built.
// so that the errors while building don't show up again.
boolean builtOnce;
static File buildFolder;
// these are static because they're used by Sketch
static private File examplesFolder;
static private File librariesFolder;
static private File toolsFolder;
static private File hardwareFolder;
static HashSet<File> libraries;
// maps imported packages to their library folder
static HashMap<String, File> importToLibraryTable;
// classpath for all known libraries for p5
// (both those in the p5/libs folder and those with lib subfolders
// found in the sketchbook)
static public String librariesClassPath;
static public HashMap<String, Target> targetsTable;
// Location for untitled items
static File untitledFolder;
// p5 icon for the window
// static Image icon;
// int editorCount;
// Editor[] editors;
java.util.List<Editor> editors =
Collections.synchronizedList(new ArrayList<Editor>());
// ArrayList editors = Collections.synchronizedList(new ArrayList<Editor>());
Editor activeEditor;
static public void main(String args[]) {
initPlatform();
// run static initialization that grabs all the prefs
Preferences.init(null);
try {
File versionFile = getContentFile("lib/version.txt");
if (versionFile.exists()) {
String version = PApplet.loadStrings(versionFile)[0];
if (!version.equals(VERSION_NAME) && !version.equals("${version}")) {
VERSION_NAME = version;
RELEASE = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
// help 3rd party installers find the correct hardware path
Preferences.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath());
Preferences.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000);
try {
File versionFile = getContentFile("lib/teensyduino.txt");
if (versionFile.exists()) {
teensyduino_version = PApplet.loadStrings(versionFile)[0];
}
} catch (Exception e) {
teensyduino_version = null;
}
// if (System.getProperty("mrj.version") != null) {
// //String jv = System.getProperty("java.version");
// String ov = System.getProperty("os.version");
// if (ov.startsWith("10.5")) {
// System.setProperty("apple.laf.useScreenMenuBar", "true");
/*
commandLine = false;
if (args.length >= 2) {
if (args[0].startsWith("--")) {
commandLine = true;
}
}
if (PApplet.javaVersion < 1.5f) {
//System.err.println("no way man");
Base.showError("Need to install Java 1.5",
"This version of Processing requires \n" +
"Java 1.5 or later to run properly.\n" +
"Please visit java.com to upgrade.", null);
}
*/
// // Set the look and feel before opening the window
// try {
// platform.setLookAndFeel();
// } catch (Exception e) {
// System.err.println("Non-fatal error while setting the Look & Feel.");
// System.err.println("The error message follows, however Processing should run fine.");
// System.err.println(e.getMessage());
// //e.printStackTrace();
// Use native popups so they don't look so crappy on osx
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
// Don't put anything above this line that might make GUI,
// because the platform has to be inited properly first.
// Make sure a full JDK is installed
//initRequirements();
// setup the theme coloring fun
Theme.init();
// Set the look and feel before opening the window
try {
platform.setLookAndFeel();
} catch (Exception e) {
String mess = e.getMessage();
if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) {
System.err.println(_("Non-fatal error while setting the Look & Feel."));
System.err.println(_("The error message follows, however Arduino should run fine."));
System.err.println(mess);
}
}
// Create a location for untitled sketches
untitledFolder = createTempFolder("untitled");
untitledFolder.deleteOnExit();
new Base(args);
}
static protected void setCommandLine() {
commandLine = true;
}
static protected boolean isCommandLine() {
return commandLine;
}
static protected void initPlatform() {
try {
Class<?> platformClass = Class.forName("processing.app.Platform");
if (Base.isMacOS()) {
platformClass = Class.forName("processing.app.macosx.Platform");
} else if (Base.isWindows()) {
platformClass = Class.forName("processing.app.windows.Platform");
} else if (Base.isLinux()) {
platformClass = Class.forName("processing.app.linux.Platform");
}
platform = (Platform) platformClass.newInstance();
} catch (Exception e) {
Base.showError(_("Problem Setting the Platform"),
_("An unknown error occurred while trying to load\n" +
"platform-specific code for your machine."), e);
}
}
static protected void initRequirements() {
try {
Class.forName("com.sun.jdi.VirtualMachine");
} catch (ClassNotFoundException cnfe) {
Base.showPlatforms();
Base.showError(_("Please install JDK 1.5 or later"),
_("Arduino requires a full JDK (not just a JRE)\n" +
"to run. Please install JDK 1.5 or later.\n" +
"More information can be found in the reference."), cnfe);
}
}
public Base(String[] args) {
platform.init(this);
// Get paths for the libraries and examples in the Processing folder
//String workingDirectory = System.getProperty("user.dir");
examplesFolder = getContentFile("examples");
librariesFolder = getContentFile("libraries");
toolsFolder = getContentFile("tools");
// Get the sketchbook path, and make sure it's set properly
String sketchbookPath = Preferences.get("sketchbook.path");
// If a value is at least set, first check to see if the folder exists.
// If it doesn't, warn the user that the sketchbook folder is being reset.
if (sketchbookPath != null) {
File skechbookFolder = new File(sketchbookPath);
if (!skechbookFolder.exists()) {
Base.showWarning(_("Sketchbook folder disappeared"),
_("The sketchbook folder no longer exists.\n" +
"Arduino will switch to the default sketchbook\n" +
"location, and create a new sketchbook folder if\n" +
"necessary. Arduino will then stop talking about\n" +
"himself in the third person."), null);
sketchbookPath = null;
}
}
// If no path is set, get the default sketchbook folder for this platform
if (sketchbookPath == null) {
File defaultFolder = getDefaultSketchbookFolder();
Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath());
if (!defaultFolder.exists()) {
defaultFolder.mkdirs();
}
}
targetsTable = new LinkedHashMap<String, Target>();
loadHardware(getHardwareFolder());
loadHardware(getSketchbookHardwareFolder());
// allow command line usage - adapted from Arduino 1.5.x branch
boolean fileOpened = false;
boolean doUpload = false;
boolean doVerify = false;
boolean doVerbose = false;
String selectBoard = null;
String selectPort = null;
String selectUsbType = null;
String selectSpeed = null;
// Check if any files were passed in on the command line
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--upload")) {
doUpload = true;
continue;
}
if (args[i].equals("--verify")) {
doVerify = true;
continue;
}
if (args[i].equals("--verbose") || args[i].equals("-v")) {
doVerbose = true;
continue;
}
if (args[i].equals("--board")) {
i++;
if (i < args.length)
selectBoard = args[i];
continue;
}
if (args[i].equals("--port")) {
i++;
if (i < args.length)
selectPort = args[i];
continue;
}
if (args[i].equals("--usbtype")) {
i++;
if (i < args.length)
selectUsbType = args[i];
continue;
}
if (args[i].equals("--speed")) {
i++;
if (i < args.length)
selectSpeed = args[i];
continue;
}
String path = args[i];
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
if (isWindows()) {
try {
File file = new File(args[i]);
path = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
}
if (handleOpen(path) != null) {
fileOpened = true;
}
}
if (doUpload || doVerify) {
if (!fileOpened) {
System.out.println(_("Can't open source sketch!"));
System.exit(2);
}
//try {
// this was necessary before adding the 2 checks for
// (progressBar == null) in EditorStatus.java
//Thread.sleep(250);
//} catch (Exception e) { }
// Set verbosity for command line build
Preferences.set("build.verbose", "" + doVerbose);
Preferences.set("upload.verbose", "" + doVerbose);
// Do board selection if requested
Editor editor = editors.get(0);
if (selectBoard == null) {
System.out.println("No board selected");
System.exit(3);
}
String[] split = selectBoard.split(":");
if (split.length != 3) {
System.out.println("error in board parameter, format is platform:arch:board");
System.exit(3);
}
// TODO: check if target exists
Preferences.set("target", split[0]);
// "arch" is not used on Arduino 1.0.x
// TODO: check if board exists within target
Preferences.set("board", split[2]);
if (selectUsbType != null) {
Preferences.set("menu.usb", selectUsbType);
}
if (selectSpeed != null) {
Preferences.set("menu.speed", selectSpeed);
}
onBoardOrPortChange();
Sketch.buildSettingChanged();
//System.out.println("selected board is " + getBoardPreferences().get("name"));
Thread buildProcess;
if (doUpload) {
// Build and upload
if (selectPort != null) {
editor.selectSerialPort(selectPort);
onBoardOrPortChange();
}
buildProcess = new Thread(editor.exportHandler);
} else {
// Build only
System.out.println("run verify....");
//Thread t = editor.handleRun(doVerbose);
if (doVerbose) {
buildProcess = new Thread(editor.presentHandler);
} else {
buildProcess = new Thread(editor.runHandler);
}
}
// actually run the build process and wait for it to complete
buildProcess.run();
// Error during build or upload
int res = editor.status.mode;
if (res == EditorStatus.ERR)
System.exit(1);
// No errors exit gracefully
System.exit(0);
}
// Check if there were previously opened sketches to be restored
boolean opened = restoreSketches();
// Check if any files were passed in on the command line
for (int i = 0; i < args.length; i++) {
String path = args[i];
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
if (isWindows()) {
try {
File file = new File(args[i]);
path = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
}
if (handleOpen(path) != null) {
opened = true;
}
}
// Create a new empty window (will be replaced with any files to be opened)
if (!opened) {
handleNew();
}
// check for updates
if (Preferences.getBoolean("update.check")) {
new UpdateCheck(this);
}
}
/**
* Post-constructor setup for the editor area. Loads the last
* sketch that was used (if any), and restores other Editor settings.
* The complement to "storePreferences", this is called when the
* application is first launched.
*/
protected boolean restoreSketches() {
// figure out window placement
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
boolean windowPositionValid = true;
if (Preferences.get("last.screen.height") != null) {
// if screen size has changed, the window coordinates no longer
// make sense, so don't use them unless they're identical
int screenW = Preferences.getInteger("last.screen.width");
int screenH = Preferences.getInteger("last.screen.height");
if ((screen.width != screenW) || (screen.height != screenH)) {
windowPositionValid = false;
}
/*
int windowX = Preferences.getInteger("last.window.x");
int windowY = Preferences.getInteger("last.window.y");
if ((windowX < 0) || (windowY < 0) ||
(windowX > screenW) || (windowY > screenH)) {
windowPositionValid = false;
}
*/
} else {
windowPositionValid = false;
}
// Iterate through all sketches that were open last time p5 was running.
// If !windowPositionValid, then ignore the coordinates found for each.
// Save the sketch path and window placement for each open sketch
int count = Preferences.getInteger("last.sketch.count");
int opened = 0;
for (int i = 0; i < count; i++) {
String path = Preferences.get("last.sketch" + i + ".path");
int[] location;
if (windowPositionValid) {
String locationStr = Preferences.get("last.sketch" + i + ".location");
location = PApplet.parseInt(PApplet.split(locationStr, ','));
} else {
location = nextEditorLocation();
}
// If file did not exist, null will be returned for the Editor
if (handleOpen(path, location) != null) {
opened++;
}
}
return (opened > 0);
}
/**
* Store list of sketches that are currently open.
* Called when the application is quitting and documents are still open.
*/
protected void storeSketches() {
// Save the width and height of the screen
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Preferences.setInteger("last.screen.width", screen.width);
Preferences.setInteger("last.screen.height", screen.height);
String untitledPath = untitledFolder.getAbsolutePath();
// Save the sketch path and window placement for each open sketch
int index = 0;
for (Editor editor : editors) {
String path = editor.getSketch().getMainFilePath();
// In case of a crash, save untitled sketches if they contain changes.
// (Added this for release 0158, may not be a good idea.)
if (path.startsWith(untitledPath) &&
!editor.getSketch().isModified()) {
continue;
}
Preferences.set("last.sketch" + index + ".path", path);
int[] location = editor.getPlacement();
String locationStr = PApplet.join(PApplet.str(location), ",");
Preferences.set("last.sketch" + index + ".location", locationStr);
index++;
}
Preferences.setInteger("last.sketch.count", index);
}
// If a sketch is untitled on quit, may need to store the new name
// rather than the location from the temp folder.
protected void storeSketchPath(Editor editor, int index) {
String path = editor.getSketch().getMainFilePath();
String untitledPath = untitledFolder.getAbsolutePath();
if (path.startsWith(untitledPath)) {
path = "";
}
Preferences.set("last.sketch" + index + ".path", path);
}
/*
public void storeSketch(Editor editor) {
int index = -1;
for (int i = 0; i < editorCount; i++) {
if (editors[i] == editor) {
index = i;
break;
}
}
if (index == -1) {
System.err.println("Problem storing sketch " + editor.sketch.name);
} else {
String path = editor.sketch.getMainFilePath();
Preferences.set("last.sketch" + index + ".path", path);
}
}
*/
// Because of variations in native windowing systems, no guarantees about
// changes to the focused and active Windows can be made. Developers must
// never assume that this Window is the focused or active Window until this
// Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event.
protected void handleActivated(Editor whichEditor) {
activeEditor = whichEditor;
// set the current window to be the console that's getting output
EditorConsole.setEditor(activeEditor);
}
protected int[] nextEditorLocation() {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int defaultWidth = Preferences.getInteger("editor.window.width.default");
int defaultHeight = Preferences.getInteger("editor.window.height.default");
if (activeEditor == null) {
// If no current active editor, use default placement
return new int[] {
(screen.width - defaultWidth) / 2,
(screen.height - defaultHeight) / 2,
defaultWidth, defaultHeight, 0
};
} else {
// With a currently active editor, open the new window
// using the same dimensions, but offset slightly.
synchronized (editors) {
final int OVER = 50;
// In release 0160, don't
//location = activeEditor.getPlacement();
Editor lastOpened = editors.get(editors.size() - 1);
int[] location = lastOpened.getPlacement();
// Just in case the bounds for that window are bad
location[0] += OVER;
location[1] += OVER;
if (location[0] == OVER ||
location[2] == OVER ||
location[0] + location[2] > screen.width ||
location[1] + location[3] > screen.height) {
// Warp the next window to a randomish location on screen.
return new int[] {
(int) (Math.random() * (screen.width - defaultWidth)),
(int) (Math.random() * (screen.height - defaultHeight)),
defaultWidth, defaultHeight, 0
};
}
return location;
}
}
}
boolean breakTime = false;
String[] months = {
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"
};
/**
* Handle creating a sketch folder, return its base .pde file
* or null if the operation was canceled.
* @param shift whether shift is pressed, which will invert prompt setting
* @param noPrompt disable prompt, no matter the setting
*/
protected String createNewUntitled() throws IOException {
File newbieDir = null;
String newbieName = null;
// In 0126, untitled sketches will begin in the temp folder,
// and then moved to a new location because Save will default to Save As.
File sketchbookDir = getSketchbookFolder();
File newbieParentDir = untitledFolder;
// Use a generic name like sketch_031008a, the date plus a char
int index = 0;
//SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
//SimpleDateFormat formatter = new SimpleDateFormat("MMMdd");
//String purty = formatter.format(new Date()).toLowerCase();
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31
int month = cal.get(Calendar.MONTH); // 0..11
String purty = months[month] + PApplet.nf(day, 2);
do {
if (index == 26) {
// In 0159, avoid running past z by sending people outdoors.
if (!breakTime) {
Base.showWarning(_("Time for a Break"),
_("You've reached the limit for auto naming of new sketches\n" +
"for the day. How about going for a walk instead?"), null);
breakTime = true;
} else {
Base.showWarning(_("Sunshine"),
_("No really, time for some fresh air for you."), null);
}
return null;
}
newbieName = "sketch_" + purty + ((char) ('a' + index));
newbieDir = new File(newbieParentDir, newbieName);
index++;
// Make sure it's not in the temp folder *and* it's not in the sketchbook
} while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists());
// Make the directory for the new sketch
newbieDir.mkdirs();
// Make an empty pde file
File newbieFile = new File(newbieDir, newbieName + ".ino");
new FileOutputStream(newbieFile); // create the file
return newbieFile.getAbsolutePath();
}
/**
* Create a new untitled document in a new sketch window.
*/
public void handleNew() {
try {
String path = createNewUntitled();
if (path != null) {
Editor editor = handleOpen(path);
editor.untitled = true;
}
} catch (IOException e) {
if (activeEditor != null) {
activeEditor.statusError(e);
}
}
}
/**
* Replace the sketch in the current window with a new untitled document.
*/
public void handleNewReplace() {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
// Actually replace things
handleNewReplaceImpl();
}
protected void handleNewReplaceImpl() {
try {
String path = createNewUntitled();
if (path != null) {
activeEditor.handleOpenInternal(path);
activeEditor.untitled = true;
}
// return true;
} catch (IOException e) {
activeEditor.statusError(e);
// return false;
}
}
/**
* Open a sketch, replacing the sketch in the current window.
* @param path Location of the primary pde file for the sketch.
*/
public void handleOpenReplace(String path) {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
boolean loaded = activeEditor.handleOpenInternal(path);
if (!loaded) {
// replace the document without checking if that's ok
handleNewReplaceImpl();
}
}
/**
* Prompt for a sketch to open, and open it in a new window.
*/
public void handleOpenPrompt() {
// get the frontmost window frame for placing file dialog
FileDialog fd = new FileDialog(activeEditor,
_("Open an Arduino sketch..."),
FileDialog.LOAD);
// This was annoying people, so disabled it in 0125.
//fd.setDirectory(Preferences.get("sketchbook.path"));
//fd.setDirectory(getSketchbookPath());
// Only show .pde files as eligible bachelors
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
// TODO this doesn't seem to ever be used. AWESOME.
//System.out.println("check filter on " + dir + " " + name);
return name.toLowerCase().endsWith(".ino")
|| name.toLowerCase().endsWith(".pde");
}
});
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// User canceled selection
if (filename == null) return;
File inputFile = new File(directory, filename);
handleOpen(inputFile.getAbsolutePath());
}
/**
* Open a sketch in a new window.
* @param path Path to the pde file for the sketch in question
* @return the Editor object, so that properties (like 'untitled')
* can be set by the caller
*/
public Editor handleOpen(String path) {
return handleOpen(path, nextEditorLocation());
}
protected Editor handleOpen(String path, int[] location) {
// System.err.println("entering handleOpen " + path);
File file = new File(path);
if (!file.exists()) return null;
// System.err.println(" editors: " + editors);
// Cycle through open windows to make sure that it's not already open.
for (Editor editor : editors) {
if (editor.getSketch().getMainFilePath().equals(path)) {
editor.toFront();
// System.err.println(" handleOpen: already opened");
return editor;
}
}
// If the active editor window is an untitled, and un-modified document,
// just replace it with the file that's being opened.
// if (activeEditor != null) {
// Sketch activeSketch = activeEditor.sketch;
// if (activeSketch.isUntitled() && !activeSketch.isModified()) {
// // if it's an untitled, unmodified document, it can be replaced.
// // except in cases where a second blank window is being opened.
// if (!path.startsWith(untitledFolder.getAbsolutePath())) {
// activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0);
// return activeEditor;
// System.err.println(" creating new editor");
Editor editor = new Editor(this, path, location);
// Editor editor = null;
// try {
// editor = new Editor(this, path, location);
// } catch (Exception e) {
// e.printStackTrace();
// System.err.flush();
// System.out.flush();
// System.exit(1);
// System.err.println(" done creating new editor");
// EditorConsole.systemErr.println(" done creating new editor");
// Make sure that the sketch actually loaded
if (editor.getSketch() == null) {
// System.err.println("sketch was null, getting out of handleOpen");
return null; // Just walk away quietly
}
// if (editors == null) {
// editors = new Editor[5];
// if (editorCount == editors.length) {
// editors = (Editor[]) PApplet.expand(editors);
// editors[editorCount++] = editor;
editors.add(editor);
// if (markedForClose != null) {
// Point p = markedForClose.getLocation();
// handleClose(markedForClose, false);
// // open the new window in
// editor.setLocation(p);
// now that we're ready, show the window
// (don't do earlier, cuz we might move it based on a window being closed)
editor.setVisible(true);
// System.err.println("exiting handleOpen");
return editor;
}
/**
* Close a sketch as specified by its editor window.
* @param editor Editor object of the sketch to be closed.
* @return true if succeeded in closing, false if canceled.
*/
public boolean handleClose(Editor editor) {
// Check if modified
// boolean immediate = editors.size() == 1;
if (!editor.checkModified()) {
return false;
}
// Close the running window, avoid window boogers with multiple sketches
editor.internalCloseRunner();
if (editors.size() == 1) {
// For 0158, when closing the last window /and/ it was already an
// untitled sketch, just give up and let the user quit.
// if (Preferences.getBoolean("sketchbook.closing_last_window_quits") ||
// (editor.untitled && !editor.getSketch().isModified())) {
if (Base.isMacOS()) {
Object[] options = { "OK", "Cancel" };
String prompt =
_("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Are you sure you want to Quit?</b>" +
"<p>Closing the last open sketch will quit Arduino.");
int result = JOptionPane.showOptionDialog(editor,
prompt,
_("Quit"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.NO_OPTION ||
result == JOptionPane.CLOSED_OPTION) {
return false;
}
}
// This will store the sketch count as zero
Editor.serialMonitor.closeSerialPort();
storeSketches();
editors.remove(editor);
// Save out the current prefs state
Preferences.save();
// Since this wasn't an actual Quit event, call System.exit()
System.exit(0);
} else {
// More than one editor window open,
// proceed with closing the current window.
editor.setVisible(false);
editor.dispose();
// for (int i = 0; i < editorCount; i++) {
// if (editor == editors[i]) {
// for (int j = i; j < editorCount-1; j++) {
// editors[j] = editors[j+1];
// editorCount--;
// // Set to null so that garbage collection occurs
// editors[editorCount] = null;
editors.remove(editor);
}
return true;
}
/**
* Handler for File → Quit.
* @return false if canceled, true otherwise.
*/
public boolean handleQuit() {
// If quit is canceled, this will be replaced anyway
// by a later handleQuit() that is not canceled.
storeSketches();
Editor.serialMonitor.closeSerialPort();
if (handleQuitEach()) {
// make sure running sketches close before quitting
for (Editor editor : editors) {
editor.internalCloseRunner();
}
// Save out the current prefs state
Preferences.save();
if (!Base.isMacOS()) {
// If this was fired from the menu or an AppleEvent (the Finder),
// then Mac OS X will send the terminate signal itself.
System.exit(0);
}
return true;
}
return false;
}
/**
* Attempt to close each open sketch in preparation for quitting.
* @return false if canceled along the way
*/
protected boolean handleQuitEach() {
int index = 0;
for (Editor editor : editors) {
if (editor.checkModified()) {
// Update to the new/final sketch path for this fella
storeSketchPath(editor, index);
index++;
} else {
return false;
}
}
return true;
}
/**
* Asynchronous version of menu rebuild to be used on save and rename
* to prevent the interface from locking up until the menus are done.
*/
protected void rebuildSketchbookMenus() {
//System.out.println("async enter");
//new Exception().printStackTrace();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//System.out.println("starting rebuild");
rebuildSketchbookMenu(Editor.sketchbookMenu);
rebuildToolbarMenu(Editor.toolbarMenu);
//System.out.println("done with rebuild");
}
});
//System.out.println("async exit");
}
protected void rebuildToolbarMenu(JMenu menu) {
JMenuItem item;
menu.removeAll();
//System.out.println("rebuilding toolbar menu");
// Add the single "Open" item
item = Editor.newJMenuItem(_("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleOpenPrompt();
}
});
menu.add(item);
menu.addSeparator();
// Add a list of all sketches and subfolders
try {
boolean sketches = addSketches(menu, getSketchbookFolder(), true);
//boolean sketches = addSketches(menu, getSketchbookFolder());
if (sketches) menu.addSeparator();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("rebuilding examples menu");
// Add each of the subfolders of examples directly to the menu
try {
boolean found = addSketches(menu, examplesFolder, true);
if (found) menu.addSeparator();
found = addSketches(menu, getSketchbookLibrariesFolder(), true);
if (found) menu.addSeparator();
addSketches(menu, librariesFolder, true);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void rebuildSketchbookMenu(JMenu menu) {
//System.out.println("rebuilding sketchbook menu");
//new Exception().printStackTrace();
try {
menu.removeAll();
addSketches(menu, getSketchbookFolder(), false);
//addSketches(menu, getSketchbookFolder());
} catch (IOException e) {
e.printStackTrace();
}
}
public void rebuildImportMenu(JMenu importMenu, final Editor editor) {
importMenu.removeAll();
JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library..."));
addLibraryMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.this.handleAddLibrary(editor);
Base.this.onBoardOrPortChange();
Base.this.rebuildImportMenu(Editor.importMenu, editor);
Base.this.rebuildExamplesMenu(Editor.examplesMenu);
}
});
importMenu.add(addLibraryMenuItem);
importMenu.addSeparator();
// reset the set of libraries
libraries = new HashSet<File>();
// reset the table mapping imports to libraries
importToLibraryTable = new HashMap<String, File>();
// Add from the "libraries" subfolder in the Processing directory
try {
addLibraries(importMenu, librariesFolder);
} catch (IOException e) {
e.printStackTrace();
}
// Add libraries found in the sketchbook folder
int separatorIndex = importMenu.getItemCount();
try {
File sketchbookLibraries = getSketchbookLibrariesFolder();
boolean found = addLibraries(importMenu, sketchbookLibraries);
if (found) {
JMenuItem contrib = new JMenuItem(_("Contributed"));
contrib.setEnabled(false);
importMenu.insert(contrib, separatorIndex);
importMenu.insertSeparator(separatorIndex);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void rebuildExamplesMenu(JMenu menu) {
//System.out.println("rebuilding examples menu");
try {
menu.removeAll();
boolean found = addSketches(menu, examplesFolder, false);
if (found) menu.addSeparator();
found = addSketches(menu, getSketchbookLibrariesFolder(), false);
if (found) menu.addSeparator();
addSketches(menu, librariesFolder, false);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onBoardOrPortChange() {
for (Editor editor : editors) {
editor.onBoardOrPortChange();
}
}
public void rebuildBoardsMenu(JMenu menu, final Editor editor) {
//System.out.println("rebuilding boards menu");
menu.removeAll();
ButtonGroup group = new ButtonGroup();
for (Target target : targetsTable.values()) {
for (String board : target.getBoards().keySet()) {
AbstractAction action =
new AbstractAction(target.getBoards().get(board).get("name")) {
public void actionPerformed(ActionEvent actionevent) {
//System.out.println("Switching to " + target + ":" + board);
Preferences.set("target", (String) getValue("target"));
Preferences.set("board", (String) getValue("board"));
onBoardOrPortChange();
Sketch.buildSettingChanged();
}
};
action.putValue("target", target.getName());
action.putValue("board", board);
JMenuItem item = new JRadioButtonMenuItem(action);
if (target.getName().equals(Preferences.get("target")) &&
board.equals(Preferences.get("board"))) {
item.setSelected(true);
}
group.add(item);
menu.add(item);
}
}
}
public void rebuildProgrammerMenu(JMenu menu) {
//System.out.println("rebuilding programmer menu");
menu.removeAll();
ButtonGroup group = new ButtonGroup();
for (Target target : targetsTable.values()) {
for (String programmer : target.getProgrammers().keySet()) {
AbstractAction action =
new AbstractAction(
target.getProgrammers().get(programmer).get("name")) {
public void actionPerformed(ActionEvent actionevent) {
Preferences.set("programmer", getValue("target") + ":" +
getValue("programmer"));
}
};
action.putValue("target", target.getName());
action.putValue("programmer", programmer);
JMenuItem item = new JRadioButtonMenuItem(action);
if (Preferences.get("programmer").equals(target.getName() + ":" +
programmer)) {
item.setSelected(true);
}
group.add(item);
menu.add(item);
}
}
}
/**
* Scan a folder recursively, and add any sketches found to the menu
* specified. Set the openReplaces parameter to true when opening the sketch
* should replace the sketch in the current window, or false when the
* sketch should open in a new window.
*/
protected boolean addSketches(JMenu menu, File folder,
final boolean replaceExisting) throws IOException {
// skip .DS_Store files, etc (this shouldn't actually be necessary)
if (!folder.isDirectory()) return false;
String[] list = folder.list();
// If a bad folder or unreadable or whatever, this will come back null
if (list == null) return false;
// Alphabetize list, since it's not always alpha order
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
//processing.core.PApplet.println("adding sketches " + folder.getAbsolutePath());
//PApplet.println(list);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = e.getActionCommand();
if (new File(path).exists()) {
boolean replace = replaceExisting;
if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
replace = !replace;
}
if (replace) {
handleOpenReplace(path);
} else {
handleOpen(path);
}
} else {
showWarning(_("Sketch Does Not Exist"),
_("The selected sketch no longer exists.\n" +
"You may need to restart Arduino to update\n" +
"the sketchbook menu."), null);
}
}
};
// offers no speed improvement
//menu.addActionListener(listener);
boolean ifound = false;
for (int i = 0; i < list.length; i++) {
if ((list[i].charAt(0) == '.') ||
list[i].equals("CVS")) continue;
File subfolder = new File(folder, list[i]);
if (!subfolder.isDirectory()) continue;
File entry = new File(subfolder, list[i] + ".ino");
if (!entry.exists() && (new File(subfolder, list[i] + ".pde")).exists()) {
entry = new File(subfolder, list[i] + ".pde");
}
// if a .pde file of the same prefix as the folder exists..
if (entry.exists()) {
//String sanityCheck = sanitizedName(list[i]);
//if (!sanityCheck.equals(list[i])) {
if (!Sketch.isSanitaryName(list[i])) {
if (!builtOnce) {
String complaining = I18n.format(
_("The sketch \"{0}\" cannot be used.\n" +
"Sketch names must contain only basic letters and numbers\n" +
"(ASCII-only with no spaces, " +
"and it cannot start with a number).\n" +
"To get rid of this message, remove the sketch from\n" +
"{1}"), list[i], entry.getAbsolutePath()
);
Base.showMessage(_("Ignoring sketch with bad name"), complaining);
}
continue;
}
JMenuItem item = new JMenuItem(list[i]);
item.addActionListener(listener);
item.setActionCommand(entry.getAbsolutePath());
menu.add(item);
ifound = true;
} else {
// don't create an extra menu level for a folder named "examples"
if (subfolder.getName().equals("examples")) {
boolean found = addSketches(menu, subfolder, replaceExisting);
if (found) ifound = true;
} else {
// not a sketch folder, but maybe a subfolder containing sketches
JMenu submenu = new JMenu(list[i]);
// needs to be separate var
// otherwise would set ifound to false
boolean found = addSketches(submenu, subfolder, replaceExisting);
//boolean found = addSketches(submenu, subfolder); //, false);
if (found) {
menu.add(submenu);
ifound = true;
}
}
}
}
return ifound; // actually ignored, but..
}
protected boolean addLibraries(JMenu menu, File folder) throws IOException {
if (!folder.isDirectory()) return false;
String list[] = folder.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// skip .DS_Store files, .svn folders, etc
if (name.charAt(0) == '.') return false;
if (name.equals("CVS")) return false;
return (new File(dir, name).isDirectory());
}
});
// if a bad folder or something like that, this might come back null
if (list == null) return false;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
String jarPath = event.getActionCommand();
try {
activeEditor.getSketch().importLibrary(jarPath);
} catch (IOException e) {
showWarning(_("Error"), I18n.format("Unable to list header files in {0}", jarPath), e);
}
}
};
boolean ifound = false;
for (String potentialName : list) {
File libFolder = new File(folder, potentialName);
String sanityCheck = Sketch.sanitizeName(potentialName);
if (!sanityCheck.equals(potentialName)) {
String mess = I18n.format(_("The library \"{0}\" cannot be used.\n"
+ "Library names must contain only basic letters and numbers.\n"
+ "(ASCII only and no spaces, and it cannot start with a number)"),
potentialName);
Base.showMessage(_("Ignoring bad library name"), mess);
continue;
}
String libraryName = potentialName;
libraries.add(libFolder);
String libFolderPath = libFolder.getAbsolutePath();
try {
String headers[] = Compiler.headerListFromIncludePath(libFolderPath);
for (String header : headers) {
File old = importToLibraryTable.get(header);
if (old == null) {
// found a header file not on the list
//System.out.println("library " + libFolder + " for header " + header);
importToLibraryTable.put(header, libFolder);
} else {
// found a header file already on the list,
// so we must decide whether to use the library already
// found, or use this library when this header is #include
String name = header.substring(0, header.length() - 2); // header without ".h"
//System.out.println("Duplicate " + header);
//System.out.println(" prev: " + old.getPath() + " " + old.getName());
//System.out.println(" new: " + libFolder.getPath() + " " + libFolder.getName());
if (name.equalsIgnoreCase(libFolder.getName()) || name.startsWith(libFolder.getName())) {
// header name clearly matches this new library, so use it
//System.out.println(" use: " + libFolder.getPath());
importToLibraryTable.put(header, libFolder);
} else if (name.equalsIgnoreCase(old.getName()) || name.startsWith(old.getName())) {
// header name clearly matches the previously found library, so keep it
//System.out.println(" use: " + old.getPath());
} else {
// neither is a good match, so go with the last one found
//System.out.println(" use: " + libFolder.getPath());
importToLibraryTable.put(header, libFolder);
}
}
}
} catch (IOException e) {
showWarning(_("Error"), I18n.format(
"Unable to list header files in {0}", libFolder), e);
}
JMenuItem item = new JMenuItem(libraryName);
item.addActionListener(listener);
item.setActionCommand(libFolderPath);
menu.add(item);
ifound = true;
}
return ifound;
}
protected void loadHardware(File folder) {
if (!folder.isDirectory()) return;
String list[] = folder.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// skip .DS_Store files, .svn folders, etc
if (name.charAt(0) == '.') return false;
if (name.equals("CVS")) return false;
return (new File(dir, name).isDirectory());
}
});
// if a bad folder or something like that, this might come back null
if (list == null) return;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, new Comparator<String>() {
public int compare(String s1, String s2) {
int i = s1.compareToIgnoreCase(s2);
if (i == 0) return 0;
if (s1.equalsIgnoreCase("teensy")) return -1;
if (s2.equalsIgnoreCase("teensy")) return 1;
return i;
}
});
for (String target : list) {
File subfolder = new File(folder, target);
targetsTable.put(target, new Target(target, subfolder));
}
}
/**
* Show the About box.
*/
public void handleAbout() {
final Image image = Base.getLibImage("about.jpg", activeEditor);
final Window window = new Window(activeEditor) {
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
Font f = new Font("SansSerif", Font.PLAIN, 11);
g.setFont(f);
g.setColor(Color.white);
g.drawString(Base.VERSION_NAME, 50, 30);
if (Base.teensyduino_version != null) {
FontMetrics m = g.getFontMetrics(f);
g.drawString("Teensyduino", 285 - m.stringWidth("Teensyduino") / 2, 44);
g.drawString(Base.teensyduino_version,
285 - m.stringWidth(Base.teensyduino_version) / 2, 60);
}
}
};
window.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
window.dispose();
}
});
int w = image.getWidth(activeEditor);
int h = image.getHeight(activeEditor);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h);
window.setVisible(true);
}
/**
* Show the Preferences window.
*/
public void handlePrefs() {
if (preferencesFrame == null) preferencesFrame = new Preferences();
preferencesFrame.showFrame(activeEditor);
}
/**
* Get list of platform constants.
*/
// static public int[] getPlatforms() {
// return platforms;
// static public int getPlatform() {
// String osname = System.getProperty("os.name");
// if (osname.indexOf("Mac") != -1) {
// return PConstants.MACOSX;
// } else if (osname.indexOf("Windows") != -1) {
// return PConstants.WINDOWS;
// } else if (osname.equals("Linux")) { // true for the ibm vm
// return PConstants.LINUX;
// } else {
// return PConstants.OTHER;
static public Platform getPlatform() {
return platform;
}
static public String getPlatformName() {
String osname = System.getProperty("os.name");
if (osname.indexOf("Mac") != -1) {
return "macosx";
} else if (osname.indexOf("Windows") != -1) {
return "windows";
} else if (osname.equals("Linux")) { // true for the ibm vm
return "linux";
} else {
return "other";
}
}
/**
* Map a platform constant to its name.
* @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX
* @return one of "windows", "macosx", or "linux"
*/
static public String getPlatformName(int which) {
return platformNames.get(which);
}
static public int getPlatformIndex(String what) {
Integer entry = platformIndices.get(what);
return (entry == null) ? -1 : entry.intValue();
}
// These were changed to no longer rely on PApplet and PConstants because
// of conflicts that could happen with older versions of core.jar, where
// the MACOSX constant would instead read as the LINUX constant.
/**
* returns true if Processing is running on a Mac OS X machine.
*/
static public boolean isMacOS() {
//return PApplet.platform == PConstants.MACOSX;
return System.getProperty("os.name").indexOf("Mac") != -1;
}
/**
* returns true if running on windows.
*/
static public boolean isWindows() {
//return PApplet.platform == PConstants.WINDOWS;
return System.getProperty("os.name").indexOf("Windows") != -1;
}
/**
* true if running on linux.
*/
static public boolean isLinux() {
//return PApplet.platform == PConstants.LINUX;
return System.getProperty("os.name").indexOf("Linux") != -1;
}
static public File getSettingsFolder() {
File settingsFolder = null;
String preferencesPath = Preferences.get("settings.path");
if (preferencesPath != null) {
settingsFolder = new File(preferencesPath);
} else {
try {
settingsFolder = platform.getSettingsFolder();
} catch (Exception e) {
showError(_("Problem getting data folder"),
_("Error getting the Arduino data folder."), e);
}
}
// create the folder if it doesn't exist already
if (!settingsFolder.exists()) {
if (!settingsFolder.mkdirs()) {
showError(_("Settings issues"),
_("Arduino cannot run because it could not\n" +
"create a folder to store your settings."), null);
}
}
return settingsFolder;
}
/**
* Convenience method to get a File object for the specified filename inside
* the settings folder.
* For now, only used by Preferences to get the preferences.txt file.
* @param filename A file inside the settings folder.
* @return filename wrapped as a File object inside the settings folder
*/
static public File getSettingsFile(String filename) {
return new File(getSettingsFolder(), filename);
}
static public File getBuildFolder() {
if (buildFolder == null) {
String buildPath = Preferences.get("build.path");
if (buildPath != null) {
buildFolder = new File(buildPath);
} else {
//File folder = new File(getTempFolder(), "build");
//if (!folder.exists()) folder.mkdirs();
buildFolder = createTempFolder("build");
buildFolder.deleteOnExit();
}
}
return buildFolder;
}
/**
* Get the path to the platform's temporary folder, by creating
* a temporary temporary file and getting its parent folder.
* <br/>
* Modified for revision 0094 to actually make the folder randomized
* to avoid conflicts in multi-user environments. (Bug 177)
*/
static public File createTempFolder(String name) {
try {
File folder = File.createTempFile(name, null);
//String tempPath = ignored.getParent();
//return new File(tempPath);
folder.delete();
folder.mkdirs();
return folder;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static public Set<File> getLibraries() {
return libraries;
}
static public String getExamplesPath() {
return examplesFolder.getAbsolutePath();
}
static public String getLibrariesPath() {
return librariesFolder.getAbsolutePath();
}
static public File getToolsFolder() {
return toolsFolder;
}
static public String getToolsPath() {
return toolsFolder.getAbsolutePath();
}
static public File getHardwareFolder() {
// calculate on the fly because it's needed by Preferences.init() to find
// the boards.txt and programmers.txt preferences files (which happens
// before the other folders / paths get cached).
return getContentFile("hardware");
}
static public String getHardwarePath() {
return getHardwareFolder().getAbsolutePath();
}
static public String getAvrBasePath() {
String arch = getBoardPreferences().get("build.architecture");
if (arch == null) arch = "avr";
//System.out.println("build.architecture = " + arch);
String path = getHardwarePath() + File.separator + "tools" +
File.separator + arch + File.separator + "bin" + File.separator;
if (!(new File(path)).exists()) {
return ""; // use distribution provided avr tools if bundled tools missing
}
return path;
}
static public Target getTarget() {
return Base.targetsTable.get(Preferences.get("target"));
}
static public Map<String, String> getBoardPreferences() {
Target target = getTarget();
if (target == null) return new LinkedHashMap();
Map map = target.getBoards();
if (map == null) return new LinkedHashMap();
map = (Map) map.get(Preferences.get("board"));
if (map == null) return new LinkedHashMap();
return map;
}
static public String getBoardMenuPreference(String key) {
Map<String,String> map = getBoardPreferences();
//System.out.println("getBoardMenuPreference: key = " + key);
for (String pref : map.keySet()) {
//System.out.println("getBoardMenuPreference: pref " + pref);
if (getBoardMenuMatch(pref, key)) return map.get(pref);
}
//System.out.println("getBoardMenuPreference: not found");
return null;
}
static public boolean getBoardMenuPreferenceBoolean(String key) {
return (new Boolean(getBoardMenuPreference(key))).booleanValue();
}
static public boolean isTeensyduino() {
String t = Preferences.get("target");
String b = Preferences.get("board");
if (t == null || b == null) return false;
if (t.compareTo("teensy") != 0) return false;
if (b.startsWith("teensy") == false) return false;
return true;
}
static private boolean getBoardMenuMatch(String pref, String key) {
String field[] = pref.split("\\.");
int index = 0;
while (field.length - index > 3 && field[index].equals("menu")) {
String val = Preferences.get("menu." + field[index + 1]);
if (val == null) return false;
//System.out.println("getBoardMenuMatch, menu." + field[index + 1] + " = " + val);
if (!field[index + 2].equals(val)) return false;
//System.out.println("getBoardMenuMatch, menu match");
index += 3;
}
if (key == null) return false;
String keys[] = key.split("\\.");
//System.out.println("getBoardMenuMatch, key=" + key + ", fields: " + keys.length);
if (keys.length != field.length - index) return false;
for (int i=0; i < keys.length; i++) {
if (!keys[i].equals(field[i + index])) return false;
}
//System.out.println("getBoardMenuMatch, success");
return true;
}
static public File getSketchbookFolder() {
return new File(Preferences.get("sketchbook.path"));
}
static public File getSketchbookLibrariesFolder() {
File libdir = new File(getSketchbookFolder(), "libraries");
if (!libdir.exists()) {
try {
libdir.mkdirs();
File readme = new File(libdir, "readme.txt");
FileWriter freadme = new FileWriter(readme);
freadme.write(_("For information on installing libraries, see: " +
"http://arduino.cc/en/Guide/Libraries\n"));
freadme.close();
} catch (Exception e) {
}
}
return libdir;
}
static public String getSketchbookLibrariesPath() {
return getSketchbookLibrariesFolder().getAbsolutePath();
}
static public File getSketchbookHardwareFolder() {
return new File(getSketchbookFolder(), "hardware");
}
protected File getDefaultSketchbookFolder() {
File sketchbookFolder = null;
try {
sketchbookFolder = platform.getDefaultSketchbookFolder();
} catch (Exception e) { }
if (sketchbookFolder == null) {
sketchbookFolder = promptSketchbookLocation();
}
// create the folder if it doesn't exist already
boolean result = true;
if (!sketchbookFolder.exists()) {
result = sketchbookFolder.mkdirs();
}
if (!result) {
showError(_("You forgot your sketchbook"),
_("Arduino cannot run because it could not\n" +
"create a folder to store your sketchbook."), null);
}
return sketchbookFolder;
}
/**
* Check for a new sketchbook location.
*/
static protected File promptSketchbookLocation() {
File folder = null;
folder = new File(System.getProperty("user.home"), "sketchbook");
if (!folder.exists()) {
folder.mkdirs();
return folder;
}
String prompt = _("Select (or create new) folder for sketches...");
folder = Base.selectFolder(prompt, null, null);
if (folder == null) {
System.exit(0);
}
return folder;
}
/**
* Implements the cross-platform headache of opening URLs
* TODO This code should be replaced by PApplet.link(),
* however that's not a static method (because it requires
* an AppletContext when used as an applet), so it's mildly
* trickier than just removing this method.
*/
static public void openURL(String url) {
try {
platform.openURL(url);
} catch (Exception e) {
showWarning(_("Problem Opening URL"),
I18n.format(_("Could not open the URL\n{0}"), url), e);
}
}
/**
* Used to determine whether to disable the "Show Sketch Folder" option.
* @return true If a means of opening a folder is known to be available.
*/
static protected boolean openFolderAvailable() {
return platform.openFolderAvailable();
}
/**
* Implements the other cross-platform headache of opening
* a folder in the machine's native file browser.
*/
static public void openFolder(File file) {
try {
platform.openFolder(file);
} catch (Exception e) {
showWarning(_("Problem Opening Folder"),
I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e);
}
}
static public File selectFolder(String prompt, File folder, Frame frame) {
if (Base.isMacOS()) {
if (frame == null) frame = new Frame(); //.pack();
FileDialog fd = new FileDialog(frame, prompt, FileDialog.LOAD);
if (folder != null) {
fd.setDirectory(folder.getParent());
//fd.setFile(folder.getName());
}
System.setProperty("apple.awt.fileDialogForDirectories", "true");
fd.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
if (fd.getFile() == null) {
return null;
}
return new File(fd.getDirectory(), fd.getFile());
} else {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(prompt);
if (folder != null) {
fc.setSelectedFile(folder);
}
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returned = fc.showOpenDialog(new JDialog());
if (returned == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
}
}
return null;
}
/**
* Give this Frame a Processing icon.
*/
static public void setIcon(Frame frame) {
// don't use the low-res icon on Mac OS X; the window should
// already have the right icon from the .app file.
if (Base.isMacOS()) return;
Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE);
frame.setIconImage(image);
}
// someone needs to be slapped
//static KeyStroke closeWindowKeyStroke;
/**
* Return true if the key event was a Ctrl-W or an ESC,
* both indicators to close the window.
* Use as part of a keyPressed() event handler for frames.
*/
/*
static public boolean isCloseWindowEvent(KeyEvent e) {
if (closeWindowKeyStroke == null) {
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers);
}
return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) ||
KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke));
}
*/
/**
* Registers key events for a Ctrl-W and ESC with an ActionListener
* that will take care of disposing the window.
*/
static public void registerWindowCloseKeys(JRootPane root,
ActionListener disposer) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
stroke = KeyStroke.getKeyStroke('W', modifiers);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
static public void showReference(String filename) {
File referenceFolder = Base.getContentFile("reference");
File referenceFile = new File(referenceFolder, filename);
openURL(referenceFile.getAbsolutePath());
}
static public void showGettingStarted() {
if (Base.isMacOS()) {
Base.showReference(_("Guide_MacOSX.html"));
} else if (Base.isWindows()) {
Base.showReference(_("Guide_Windows.html"));
} else {
Base.openURL(_("http:
}
}
static public void showReference() {
showReference(_("index.html"));
}
static public void showEnvironment() {
showReference(_("Guide_Environment.html"));
}
static public void showPlatforms() {
showReference(_("environment") + File.separator + _("platforms.html"));
}
static public void showTroubleshooting() {
showReference(_("Guide_Troubleshooting.html"));
}
static public void showFAQ() {
showReference(_("FAQ.html"));
}
/**
* "No cookie for you" type messages. Nothing fatal or all that
* much of a bummer, but something to notify the user about.
*/
static public void showMessage(String title, String message) {
if (title == null) title = _("Message");
if (commandLine) {
System.out.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Non-fatal error message with optional stack trace side dish.
*/
static public void showWarning(String title, String message, Exception e) {
if (title == null) title = _("Warning");
if (commandLine) {
System.out.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.WARNING_MESSAGE);
}
if (e != null) e.printStackTrace();
}
/**
* Show an error message that's actually fatal to the program.
* This is an error that can't be recovered. Use showWarning()
* for errors that allow P5 to continue running.
*/
static public void showError(String title, String message, Throwable e) {
if (title == null) title = _("Error");
if (commandLine) {
System.err.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.ERROR_MESSAGE);
}
if (e != null) e.printStackTrace();
System.exit(1);
}
// incomplete
static public int showYesNoCancelQuestion(Editor editor, String title,
String primary, String secondary) {
if (!Base.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
return result;
// if (result == JOptionPane.YES_OPTION) {
// } else if (result == JOptionPane.NO_OPTION) {
// return true; // ok to continue
// } else if (result == JOptionPane.CANCEL_OPTION) {
// return false;
// } else {
} else {
// Pane formatting adapted from the Quaqua guide
JOptionPane pane =
new JOptionPane("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost.",
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
"Save", "Cancel", "Don't Save"
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
// on macosx, setting the destructive property places this option
// away from the others at the lefthand side
pane.putClientProperty("Quaqua.OptionPane.destructiveOption",
new Integer(2));
JDialog dialog = pane.createDialog(editor, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) {
return JOptionPane.YES_OPTION;
} else if (result == options[1]) {
return JOptionPane.CANCEL_OPTION;
} else if (result == options[2]) {
return JOptionPane.NO_OPTION;
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
//if (result == JOptionPane.YES_OPTION) {
// } else if (result == JOptionPane.NO_OPTION) {
// return true; // ok to continue
// } else if (result == JOptionPane.CANCEL_OPTION) {
// return false;
// } else {
static public int showYesNoQuestion(Frame editor, String title,
String primary, String secondary) {
if (!Base.isMacOS()) {
return JOptionPane.showConfirmDialog(editor,
"<html><body>" +
"<b>" + primary + "</b>" +
"<br>" + secondary, title,
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
} else {
// Pane formatting adapted from the Quaqua guide
JOptionPane pane =
new JOptionPane("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>" + primary + "</b>" +
"<p>" + secondary + "</p>",
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
"Yes", "No"
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
JDialog dialog = pane.createDialog(editor, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) {
return JOptionPane.YES_OPTION;
} else if (result == options[1]) {
return JOptionPane.NO_OPTION;
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
/**
* Retrieve a path to something in the Processing folder. Eventually this
* may refer to the Contents subfolder of Processing.app, if we bundle things
* up as a single .app file with no additional folders.
*/
// static public String getContentsPath(String filename) {
// String basePath = System.getProperty("user.dir");
// /*
// // do this later, when moving to .app package
// if (PApplet.platform == PConstants.MACOSX) {
// basePath = System.getProperty("processing.contents");
// }
// */
// return basePath + File.separator + filename;
/**
* Get a path for something in the Processing lib folder.
*/
/*
static public String getLibContentsPath(String filename) {
String libPath = getContentsPath("lib/" + filename);
File libDir = new File(libPath);
if (libDir.exists()) {
return libPath;
}
// was looking into making this run from Eclipse, but still too much mess
// libPath = getContents("build/shared/lib/" + what);
// libDir = new File(libPath);
// if (libDir.exists()) {
// return libPath;
// }
return null;
}
*/
static public File getContentFile(String name) {
String path = System.getProperty("user.dir");
// Get a path to somewhere inside the .app folder
if (Base.isMacOS()) {
// <key>javaroot</key>
// <string>$JAVAROOT</string>
String javaroot = System.getProperty("javaroot");
if (javaroot != null) {
path = javaroot;
}
}
File working = new File(path);
return new File(working, name);
}
/**
* Get an image associated with the current color theme.
*/
static public Image getThemeImage(String name, Component who) {
return getLibImage("theme/" + name, who);
}
/**
* Return an Image object from inside the Processing lib folder.
*/
static public Image getLibImage(String name, Component who) {
Image image = null;
Toolkit tk = Toolkit.getDefaultToolkit();
File imageLocation = new File(getContentFile("lib"), name);
image = tk.getImage(imageLocation.getAbsolutePath());
MediaTracker tracker = new MediaTracker(who);
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) { }
return image;
}
/**
* Return an InputStream for a file inside the Processing lib folder.
*/
static public InputStream getLibStream(String filename) throws IOException {
return new FileInputStream(new File(getContentFile("lib"), filename));
}
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
int count = 1;
for (char c : what.toCharArray()) {
if (c == '\n') count++;
}
return count;
}
/**
* Same as PApplet.loadBytes(), however never does gzip decoding.
*/
static public byte[] loadBytesRaw(File file) throws IOException {
int size = (int) file.length();
FileInputStream input = new FileInputStream(file);
byte buffer[] = new byte[size];
int offset = 0;
int bytesRead;
while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) {
offset += bytesRead;
if (bytesRead == 0) break;
}
input.close(); // weren't properly being closed
input = null;
return buffer;
}
/**
* Read from a file with a bunch of attribute/value pairs
* that are separated by = and ignore comments with #.
*/
static public HashMap<String,String> readSettings(File inputFile) {
HashMap<String,String> outgoing = new HashMap<String,String>();
if (!inputFile.exists()) return outgoing; // return empty hash
String lines[] = PApplet.loadStrings(inputFile);
for (int i = 0; i < lines.length; i++) {
int hash = lines[i].indexOf('
String line = (hash == -1) ?
lines[i].trim() : lines[i].substring(0, hash).trim();
if (line.length() == 0) continue;
int equals = line.indexOf('=');
if (equals == -1) {
System.err.println("ignoring illegal line in " + inputFile);
System.err.println(" " + line);
continue;
}
String attr = line.substring(0, equals).trim();
String valu = line.substring(equals + 1).trim();
outgoing.put(attr, valu);
}
return outgoing;
}
static public void copyFile(File sourceFile,
File targetFile) throws IOException {
InputStream from =
new BufferedInputStream(new FileInputStream(sourceFile));
OutputStream to =
new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buffer = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1) {
to.write(buffer, 0, bytesRead);
}
to.flush();
from.close();
from = null;
to.close();
to = null;
targetFile.setLastModified(sourceFile.lastModified());
}
/**
* Grab the contents of a file as a string.
*/
static public String loadFile(File file) throws IOException {
String[] contents = PApplet.loadStrings(file);
if (contents == null) return null;
return PApplet.join(contents, "\n");
}
/**
* Spew the contents of a String object out to a file.
*/
static public void saveFile(String str, File file) throws IOException {
File temp = File.createTempFile(file.getName(), null, file.getParentFile());
PApplet.saveStrings(temp, new String[] { str });
if (file.exists()) {
boolean result = file.delete();
if (!result) {
throw new IOException(
I18n.format(
_("Could not remove old version of {0}"),
file.getAbsolutePath()
)
);
}
}
boolean result = temp.renameTo(file);
if (!result) {
throw new IOException(
I18n.format(
_("Could not replace {0}"),
file.getAbsolutePath()
)
);
}
}
/**
* Copy a folder from one place to another. This ignores all dot files and
* folders found in the source directory, to avoid copying silly .DS_Store
* files and potentially troublesome .svn folders.
*/
static public void copyDir(File sourceDir,
File targetDir) throws IOException {
targetDir.mkdirs();
String files[] = sourceDir.list();
for (int i = 0; i < files.length; i++) {
// Ignore dot files (.DS_Store), dot folders (.svn) while copying
if (files[i].charAt(0) == '.') continue;
//if (files[i].equals(".") || files[i].equals("..")) continue;
File source = new File(sourceDir, files[i]);
File target = new File(targetDir, files[i]);
if (source.isDirectory()) {
//target.mkdirs();
copyDir(source, target);
target.setLastModified(source.lastModified());
} else {
copyFile(source, target);
}
}
}
/**
* Remove all files in a directory and the directory itself.
*/
static public void removeDir(File dir) {
if (dir.exists()) {
removeDescendants(dir);
if (!dir.delete()) {
System.err.println(I18n.format(_("Could not delete {0}"), dir));
}
}
}
/**
* Recursively remove all files within a directory,
* used with removeDir(), or when the contents of a dir
* should be removed, but not the directory itself.
* (i.e. when cleaning temp files from lib/build)
*/
static public void removeDescendants(File dir) {
if (!dir.exists()) return;
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || files[i].equals("..")) continue;
File dead = new File(dir, files[i]);
if (!dead.isDirectory()) {
if (!Preferences.getBoolean("compiler.save_build_files")) {
if (!dead.delete()) {
// temporarily disabled
System.err.println(I18n.format(_("Could not delete {0}"), dead));
}
}
} else {
removeDir(dead);
//dead.delete();
}
}
}
/**
* Calculate the size of the contents of a folder.
* Used to determine whether sketches are empty or not.
* Note that the function calls itself recursively.
*/
static public int calcFolderSize(File folder) {
int size = 0;
String files[] = folder.list();
// null if folder doesn't exist, happens when deleting sketch
if (files == null) return -1;
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || (files[i].equals("..")) ||
files[i].equals(".DS_Store")) continue;
File fella = new File(folder, files[i]);
if (fella.isDirectory()) {
size += calcFolderSize(fella);
} else {
size += (int) fella.length();
}
}
return size;
}
/**
* Recursively creates a list of all files within the specified folder,
* and returns a list of their relative paths.
* Ignores any files/folders prefixed with a dot.
*/
static public String[] listFiles(String path, boolean relative) {
return listFiles(new File(path), relative);
}
static public String[] listFiles(File folder, boolean relative) {
String path = folder.getAbsolutePath();
Vector<String> vector = new Vector<String>();
listFiles(relative ? (path + File.separator) : "", path, vector);
String outgoing[] = new String[vector.size()];
vector.copyInto(outgoing);
return outgoing;
}
static protected void listFiles(String basePath,
String path, Vector<String> vector) {
File folder = new File(path);
String list[] = folder.list();
if (list == null) return;
for (int i = 0; i < list.length; i++) {
if (list[i].charAt(0) == '.') continue;
File file = new File(path, list[i]);
String newPath = file.getAbsolutePath();
if (newPath.startsWith(basePath)) {
newPath = newPath.substring(basePath.length());
}
vector.add(newPath);
if (file.isDirectory()) {
listFiles(basePath, newPath, vector);
}
}
}
public void handleAddLibrary(Editor editor) {
JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home"));
fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip"));
Dimension preferredSize = fileChooser.getPreferredSize();
fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200));
int returnVal = fileChooser.showOpenDialog(editor);
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File sourceFile = fileChooser.getSelectedFile();
File tmpFolder = null;
try {
// unpack ZIP
if (!sourceFile.isDirectory()) {
try {
tmpFolder = FileUtils.createTempFolder();
ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder);
zipDeflater.deflate();
File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs());
if (foldersInTmpFolder.length != 1) {
throw new IOException(_("Zip doesn't contain a library"));
}
sourceFile = foldersInTmpFolder[0];
} catch (IOException e) {
editor.statusError(e);
return;
}
}
// is there a valid library?
File libFolder = sourceFile;
String libName = libFolder.getName();
if (!Sketch.isSanitaryName(libName)) {
String mess = I18n.format(_("The library \"{0}\" cannot be used.\n"
+ "Library names must contain only basic letters and numbers.\n"
+ "(ASCII only and no spaces, and it cannot start with a number)"),
libName);
editor.statusError(mess);
return;
}
// copy folder
File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName());
if (!destinationFolder.mkdir()) {
editor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName()));
return;
}
try {
FileUtils.copy(sourceFile, destinationFolder);
} catch (IOException e) {
editor.statusError(e);
return;
}
editor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu"));
} finally {
// delete zip created temp folder, if exists
FileUtils.recursiveDelete(tmpFolder);
}
}
}
|
package xyz.brassgoggledcoders.moarcarts;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.oredict.RecipeSorter;
import xyz.brassgoggledcoders.boilerplate.lib.BoilerplateLib;
import xyz.brassgoggledcoders.boilerplate.lib.common.IBoilerplateMod;
import xyz.brassgoggledcoders.boilerplate.lib.common.config.ConfigEntry;
import xyz.brassgoggledcoders.boilerplate.lib.common.config.Type;
import xyz.brassgoggledcoders.boilerplate.lib.common.registries.ConfigRegistry;
import xyz.brassgoggledcoders.boilerplate.lib.common.utils.ModLogger;
import xyz.brassgoggledcoders.moarcarts.items.MoarCartsCreativeTab;
import xyz.brassgoggledcoders.moarcarts.mods.extras.ExtrasModule;
import xyz.brassgoggledcoders.moarcarts.mods.hydraulicraft.HydraulicraftModule;
import xyz.brassgoggledcoders.moarcarts.mods.ie.IEModule;
import xyz.brassgoggledcoders.moarcarts.mods.ironchest.IronChestCompat;
import xyz.brassgoggledcoders.moarcarts.mods.neotech.NeotechModule;
import xyz.brassgoggledcoders.moarcarts.mods.rf.RFModule;
import xyz.brassgoggledcoders.moarcarts.mods.vanilla.VanillaModule;
import xyz.brassgoggledcoders.moarcarts.mods.waila.WailaModule;
import xyz.brassgoggledcoders.moarcarts.network.EntityTileEntityUpdateMessage;
import xyz.brassgoggledcoders.moarcarts.proxies.CommonProxy;
import xyz.brassgoggledcoders.moarcarts.recipes.NBTCartRecipe;
/*
* @author SkySom
*/
@Mod(modid = MoarCarts.MODID, name = MoarCarts.MODNAME, version = MoarCarts.MODVERSION, dependencies = MoarCarts.DEPENDENCIES)
public class MoarCarts implements IBoilerplateMod
{
@Instance("moarcarts")
public static MoarCarts instance;
public static final String MODID = "moarcarts";
public static final String MODNAME = "MoarCarts";
public static final String MODVERSION = "@VERSION@";
public static final String DEPENDENCIES = "after:IronChest;";
public static ModLogger logger;
public static Configuration config;
public static MoarCartsCreativeTab moarcartsTab = new MoarCartsCreativeTab();
@SidedProxy(clientSide = "xyz.brassgoggledcoders.moarcarts.proxies.ClientProxy", serverSide = "xyz.brassgoggledcoders.moarcarts.proxies.CommonProxy")
public static CommonProxy proxy;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
logger = new ModLogger(MODID);
initModCompatHandler();
BoilerplateLib.getInstance().preInitStart(event);
BoilerplateLib.getPacketHandler().registerPacket(EntityTileEntityUpdateMessage.Handler.class,
EntityTileEntityUpdateMessage.class, Side.CLIENT);
ConfigRegistry.addCategoryComment("Tweaks",
"Most these values will be overwritten by Railcraft values, if it is installed");
ConfigRegistry.addEntry(new ConfigEntry("Tweaks", "breakOnDrop", Type.BOOLEAN, "false",
"change to 'true' to restore vanilla behavior"));
ConfigRegistry.addEntry(new ConfigEntry("Tweaks", "maxStackSize", Type.INTEGER, "3",
"change the value to your desired minecart stack size, vanilla=1, default=3, max=64"));
BoilerplateLib.getInstance().preInitEnd(event);
MoarCarts.proxy.preInit();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
BoilerplateLib.getInstance().init(event);
RecipeSorter.register("moarcarts:nbtcartrecipe", NBTCartRecipe.class, RecipeSorter.Category.SHAPELESS,
"after:minecraft:shapeless");
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
BoilerplateLib.getInstance().postInit(event);
}
public void initModCompatHandler()
{
BoilerplateLib.getModuleHandler().addModule(new VanillaModule());
BoilerplateLib.getModuleHandler().addModule(new IronChestCompat());
BoilerplateLib.getModuleHandler().addModule(new WailaModule());
BoilerplateLib.getModuleHandler().addModule(new HydraulicraftModule());
BoilerplateLib.getModuleHandler().addModule(new NeotechModule());
BoilerplateLib.getModuleHandler().addModule(new ExtrasModule());
BoilerplateLib.getModuleHandler().addModule(new RFModule());
BoilerplateLib.getModuleHandler().addModule(new IEModule());
}
@Override
public Object getInstance()
{
return MoarCarts.instance;
}
@Override
public CreativeTabs getCreativeTab()
{
return moarcartsTab;
}
@Override
public String getID()
{
return MODID;
}
@Override
public String getName()
{
return MODNAME;
}
@Override
public String getVersion()
{
return MODVERSION;
}
@Override
public String getPrefix()
{
return MODID + ":";
}
}
|
package org.mockito.internal.configuration;
import org.mockito.configuration.ReturnValues;
import org.mockito.configuration.experimental.ConfigurationSupport;
/**
* Allows configuring Mockito.
* <p>
* See examples in javadoc for {@link ConfigurationSupport}
*/
public interface MockitoConfiguration {
/**
* returns currently set {@link ReturnValues}
*
* @return
*/
ReturnValues getReturnValues();
/**
* Sets {@link ReturnValues} implementation.
* <p>
* Allows to change the values returned by unstubbed methods.
*
* @param returnValues
*/
void setReturnValues(ReturnValues returnValues);
/**
* Resets {@link ReturnValues} implementation to the default one: {@link MockitoProperties#DEFAULT_RETURN_VALUES}
*/
void resetReturnValues();
}
|
package eu.amidst.core.huginlink;
import COM.hugin.HAPI.*;
import COM.hugin.HAPI.Node;
import eu.amidst.core.distribution.*;
import eu.amidst.core.variables.DistType;
import eu.amidst.core.variables.MultinomialStateSpace;
import eu.amidst.core.variables.StaticVariables;
import eu.amidst.core.variables.Variable;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.utils.MultinomialIndex;
import java.util.List;
public class ConverterToHugin {
private Domain huginBN;
private BayesianNetwork amidstBN;
public ConverterToHugin(BayesianNetwork amidstBN_) throws ExceptionHugin {
this.huginBN = new Domain();
this.amidstBN = amidstBN_;
}
public Domain getHuginNetwork(){
return this.huginBN;
}
public void setNodes() throws ExceptionHugin {
StaticVariables amidstVars = amidstBN.getStaticVariables();
int size = amidstVars.getNumberOfVars();
//Hugin always inserts variables in position 0, i.e, for an order A,B,C, it stores C,B,A !!!
//A reverse order of the variables is used instead.
for(int i=1;i<=size;i++){
Variable amidstVar = amidstVars.getVariableById(size-i);
if (amidstVar.getDistributionType().compareTo(DistType.MULTINOMIAL) == 0) {
LabelledDCNode n = new LabelledDCNode(this.huginBN);
n.setName(amidstVar.getName());
n.setNumberOfStates(amidstVar.getNumberOfStates());
for (int j=0;j<n.getNumberOfStates();j++){
String stateName = ((MultinomialStateSpace)amidstVar.getStateSpace()).getStatesName(j);
n.setStateLabel(j, stateName);
}
} else if (amidstVar.getDistributionType().compareTo(DistType.GAUSSIAN) == 0) {
ContinuousChanceNode c = new ContinuousChanceNode(this.huginBN);
c.setName(amidstVar.getName());
} else {
throw new IllegalArgumentException("Unrecognized DistributionType.");
}
}
}
public void setStructure () throws ExceptionHugin {
DAG dag = amidstBN.getDAG();
for (Variable amidstChild: amidstBN.getStaticVariables()) {
for (Variable amidstParent: dag.getParentSet(amidstChild)) {
Node huginChild = this.huginBN.getNodeByName(amidstChild.getName());
Node huginParent = this.huginBN.getNodeByName(amidstParent.getName());
huginChild.addParent(huginParent);
}
}
}
public void setMultinomial_MultinomialParents(Multinomial_MultinomialParents dist) throws ExceptionHugin {
Variable amidstVar = dist.getVariable();
Node huginVar = this.huginBN.getNodeByName(amidstVar.getName());
Multinomial[] probabilities = dist.getProbabilities();
List<Variable> conditioningVariables = dist.getConditioningVariables();
int numParentAssignments = MultinomialIndex.getNumberOfPossibleAssignments(conditioningVariables);
int nStates = amidstVar.getNumberOfStates();
int sizeArray = numParentAssignments * nStates;
double[] finalArray = new double[sizeArray];
for(int i=0;i<numParentAssignments;i++){
double[] sourceArray = probabilities[i].getProbabilities();
System.arraycopy(sourceArray, 0, finalArray, i*nStates, nStates);
}
huginVar.getTable().setData(finalArray);
}
public void setNormal_NormalParents(Normal_NormalParents dist, int assign_i) throws ExceptionHugin {
Variable amidstVar = dist.getVariable();
List<Variable> normalParents = dist.getConditioningVariables();
int numNormalParents = normalParents.size();
Node huginVar = this.huginBN.getNodeByName(amidstVar.getName());
double variance = Math.pow(dist.getSd(), 2);
((ContinuousChanceNode)huginVar).setGamma(variance,assign_i);
double intercept = dist.getIntercept();
((ContinuousChanceNode) huginVar).setAlpha(intercept, assign_i);
double[] coeffParents = dist.getCoeffParents();
for(int i=0;i<numNormalParents;i++) {
ContinuousChanceNode huginParent =
(ContinuousChanceNode)this.huginBN.getNodeByName(normalParents.get(i).getName());
((ContinuousChanceNode)huginVar).setBeta(coeffParents[i],huginParent,assign_i);
}
}
public void setNormal(Normal dist, int i) throws ExceptionHugin {
Variable amidstVar = dist.getVariable();
Node huginVar = this.huginBN.getNodeByName(amidstVar.getName());
double mean = dist.getMean();
double sd = dist.getSd();
((ContinuousChanceNode)huginVar).setAlpha(mean, i);
((ContinuousChanceNode)huginVar).setGamma(Math.pow(sd,2),i);
}
public void setNormal_MultinomialParents(Normal_MultinomialParents dist) throws ExceptionHugin {
List<Variable> conditioningVariables = dist.getConditioningVariables();
int numParentAssignments = MultinomialIndex.getNumberOfPossibleAssignments(conditioningVariables);
for(int i=0;i<numParentAssignments;i++) {
Normal normal = dist.getNormal(i);
this.setNormal(normal, i);
}
}
public void setNormal_MultinomialNormalParents(Normal_MultinomialNormalParents dist) throws ExceptionHugin {
List<Variable> multinomialParents = dist.getMultinomialParents();
int numParentAssignments = MultinomialIndex.getNumberOfPossibleAssignments(multinomialParents);
for(int i=0;i<numParentAssignments;i++) {
this.setNormal_NormalParents(dist.getNormal_NormalParentsDistribution(i),i);
}
}
public void setDistributions() throws ExceptionHugin {
for (Variable amidstVar : amidstBN.getStaticVariables()) {
switch (Utils.getConditionalDistributionType(amidstVar, amidstBN)) {
case 0:
this.setMultinomial_MultinomialParents(amidstBN.getDistribution(amidstVar));
break;
case 1:
this.setNormal_NormalParents(amidstBN.getDistribution(amidstVar), 0);
break;
case 2:
this.setNormal_MultinomialParents(amidstBN.getDistribution(amidstVar));
break;
case 3:
this.setNormal_MultinomialNormalParents(amidstBN.getDistribution(amidstVar));
break;
default:
throw new IllegalArgumentException("Unrecognized DistributionType. ");
}
}
}
public void convertToHuginBN() throws ExceptionHugin {
this.setNodes();
this.setStructure();
this.setDistributions();
}
}
|
package be.isach.samaritan.music;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class AudioFilesManager {
public static void checkforSongsToConvert() {
cleanMp4();
File directory = new File("/home/samaritan/music");
for (File file : directory.listFiles()) {
if (file.getName().endsWith(".webm")) {
convert(file);
}
}
}
private static void convert(File file) {
// System.out.println("Trying to convert: " + file.getName());
// String spacedName = file.getName().replace(".webm", ".mp3");
// File webmFile = file.getAbsoluteFile();
// webmFile.renameTo(new File(webmFile.getAbsolutePath().replace(" ", "")));
// File mp3File = new File(webmFile.getAbsolutePath().replace(" ", "").replace(".webm", ".mp3"));
// System.out.println("\nExists: " + webmFile.exists() + "\n");
String[] commandCD = {
"cd music/",
};
String[] command = {
"ffmpeg",
"-i",
"\"" + "a b.webm" + "\"",
"\"" + "a b.mp3" + "\""
};
System.out.println(Arrays.asList(command));
execProcess(commandCD);
execProcess(command);
// mp3File.renameTo(new File(spacedName));
}
private static void execProcess(String[] args) {
try {
Process p = Runtime.getRuntime().exec(args);
BufferedReader output = getOutput(p);
BufferedReader error = getError(p);
String line = "";
while ((line = output.readLine()) != null) {
System.out.println(line);
}
while ((line = error.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private static BufferedReader getOutput(Process p) {
return new BufferedReader(new InputStreamReader(p.getInputStream()));
}
private static BufferedReader getError(Process p) {
return new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
private static void cleanMp4() {
File file = new File("/home/samaritan/music");
// Arrays.asList(file.listFiles()).stream().filter(file1 -> file1.getName().endsWith(".mp4")).forEach(File::delete);
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.apache.commons.logging.impl.NoOpLog;
import cc.arduino.packages.DiscoveryManager;
import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
import processing.app.debug.TargetPlatformException;
import processing.app.helpers.FileUtils;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.helpers.filefilters.OnlyFilesWithExtension;
import processing.app.javax.swing.filechooser.FileNameExtensionFilter;
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
import processing.app.tools.MenuScroller;
import processing.app.tools.ZipDeflater;
import processing.core.*;
import static processing.app.I18n._;
/**
* The base class for the main processing application.
* Primary role of this class is for platform identification and
* general interaction with the system (launching URLs, loading
* files and images, etc) that comes from that.
*/
public class Base {
public static final int REVISION = 155;
/** This might be replaced by main() if there's a lib/version.txt file. */
static String VERSION_NAME = "0155";
/** Set true if this a proper release rather than a numbered revision. */
static public boolean RELEASE = false;
static Map<Integer, String> platformNames = new HashMap<Integer, String>();
static {
platformNames.put(PConstants.WINDOWS, "windows");
platformNames.put(PConstants.MACOSX, "macosx");
platformNames.put(PConstants.LINUX, "linux");
}
static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>();
static {
platformIndices.put("windows", PConstants.WINDOWS);
platformIndices.put("macosx", PConstants.MACOSX);
platformIndices.put("linux", PConstants.LINUX);
}
static Platform platform;
private static DiscoveryManager discoveryManager = new DiscoveryManager();
static private boolean commandLine;
// A single instance of the preferences window
Preferences preferencesFrame;
// set to true after the first time the menu is built.
// so that the errors while building don't show up again.
boolean builtOnce;
static File buildFolder;
// these are static because they're used by Sketch
static private File examplesFolder;
static private File toolsFolder;
static private List<File> librariesFolders;
// maps library name to their library folder
static private LibraryList libraries;
// maps #included files to their library folder
static Map<String, Library> importToLibraryTable;
// classpath for all known libraries for p5
// (both those in the p5/libs folder and those with lib subfolders
// found in the sketchbook)
static public String librariesClassPath;
static public Map<String, TargetPackage> packages;
// Location for untitled items
static File untitledFolder;
// p5 icon for the window
// static Image icon;
// int editorCount;
List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>());
Editor activeEditor;
private final Map<String, Map<String, Object>> boardsViaNetwork;
static File portableFolder = null;
static final String portableSketchbookFolder = "sketchbook";
static public void main(String args[]) throws Exception {
System.setProperty(LogFactoryImpl.LOG_PROPERTY, NoOpLog.class.getCanonicalName());
Logger.getLogger("javax.jmdns").setLevel(Level.OFF);
initPlatform();
// Portable folder
portableFolder = getContentFile("portable");
if (!portableFolder.exists())
portableFolder = null;
// run static initialization that grabs all the prefs
Preferences.init(null);
try {
File versionFile = getContentFile("lib/version.txt");
if (versionFile.exists()) {
String version = PApplet.loadStrings(versionFile)[0];
if (!version.equals(VERSION_NAME) && !version.equals("${version}")) {
VERSION_NAME = version;
RELEASE = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
// help 3rd party installers find the correct hardware path
Preferences.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath());
Preferences.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000);
// if (System.getProperty("mrj.version") != null) {
// //String jv = System.getProperty("java.version");
// String ov = System.getProperty("os.version");
// if (ov.startsWith("10.5")) {
// System.setProperty("apple.laf.useScreenMenuBar", "true");
/*
commandLine = false;
if (args.length >= 2) {
if (args[0].startsWith("--")) {
commandLine = true;
}
}
if (PApplet.javaVersion < 1.5f) {
//System.err.println("no way man");
Base.showError("Need to install Java 1.5",
"This version of Processing requires \n" +
"Java 1.5 or later to run properly.\n" +
"Please visit java.com to upgrade.", null);
}
*/
// // Set the look and feel before opening the window
// try {
// platform.setLookAndFeel();
// } catch (Exception e) {
// System.err.println("Non-fatal error while setting the Look & Feel.");
// System.err.println("The error message follows, however Processing should run fine.");
// System.err.println(e.getMessage());
// //e.printStackTrace();
// Use native popups so they don't look so crappy on osx
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
// Don't put anything above this line that might make GUI,
// because the platform has to be inited properly first.
// Make sure a full JDK is installed
//initRequirements();
// setup the theme coloring fun
Theme.init();
// Set the look and feel before opening the window
try {
platform.setLookAndFeel();
} catch (Exception e) {
String mess = e.getMessage();
if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) {
System.err.println(_("Non-fatal error while setting the Look & Feel."));
System.err.println(_("The error message follows, however Arduino should run fine."));
System.err.println(mess);
}
}
// Create a location for untitled sketches
untitledFolder = createTempFolder("untitled");
untitledFolder.deleteOnExit();
new Base(args);
}
static protected void setCommandLine() {
commandLine = true;
}
static protected boolean isCommandLine() {
return commandLine;
}
static protected void initPlatform() {
try {
Class<?> platformClass = Class.forName("processing.app.Platform");
if (Base.isMacOS()) {
platformClass = Class.forName("processing.app.macosx.Platform");
} else if (Base.isWindows()) {
platformClass = Class.forName("processing.app.windows.Platform");
} else if (Base.isLinux()) {
platformClass = Class.forName("processing.app.linux.Platform");
}
platform = (Platform) platformClass.newInstance();
} catch (Exception e) {
Base.showError(_("Problem Setting the Platform"),
_("An unknown error occurred while trying to load\n" +
"platform-specific code for your machine."), e);
}
}
static protected void initRequirements() {
try {
Class.forName("com.sun.jdi.VirtualMachine");
} catch (ClassNotFoundException cnfe) {
Base.showPlatforms();
Base.showError(_("Please install JDK 1.5 or later"),
_("Arduino requires a full JDK (not just a JRE)\n" +
"to run. Please install JDK 1.5 or later.\n" +
"More information can be found in the reference."), cnfe);
}
}
public Base(String[] args) throws Exception {
platform.init(this);
this.boardsViaNetwork = new ConcurrentHashMap<String, Map<String, Object>>();
// Get the sketchbook path, and make sure it's set properly
String sketchbookPath = Preferences.get("sketchbook.path");
// If a value is at least set, first check to see if the folder exists.
// If it doesn't, warn the user that the sketchbook folder is being reset.
if (sketchbookPath != null) {
File sketchbookFolder;
if (portableFolder != null)
sketchbookFolder = new File(portableFolder, sketchbookPath);
else
sketchbookFolder = new File(sketchbookPath);
if (!sketchbookFolder.exists()) {
Base.showWarning(_("Sketchbook folder disappeared"),
_("The sketchbook folder no longer exists.\n" +
"Arduino will switch to the default sketchbook\n" +
"location, and create a new sketchbook folder if\n" +
"necessary. Arduino will then stop talking about\n" +
"himself in the third person."), null);
sketchbookPath = null;
}
}
// If no path is set, get the default sketchbook folder for this platform
if (sketchbookPath == null) {
File defaultFolder = getDefaultSketchbookFolder();
if (portableFolder != null)
Preferences.set("sketchbook.path", portableSketchbookFolder);
else
Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath());
if (!defaultFolder.exists()) {
defaultFolder.mkdirs();
}
}
packages = new HashMap<String, TargetPackage>();
loadHardware(getHardwareFolder());
loadHardware(getSketchbookHardwareFolder());
if (packages.size() == 0) {
System.out.println(_("No valid configured cores found! Exiting..."));
System.exit(3);
}
// Setup board-dependent variables.
onBoardOrPortChange();
boolean opened = false;
boolean doUpload = false;
boolean doVerify = false;
boolean doVerbose = false;
String selectBoard = null;
String selectPort = null;
String currentDirectory = System.getProperty("user.dir");
// Check if any files were passed in on the command line
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--upload")) {
doUpload = true;
continue;
}
if (args[i].equals("--verify")) {
doVerify = true;
continue;
}
if (args[i].equals("--verbose") || args[i].equals("-v")) {
doVerbose = true;
continue;
}
if (args[i].equals("--board")) {
i++;
if (i < args.length)
selectBoard = args[i];
continue;
}
if (args[i].equals("--port")) {
i++;
if (i < args.length)
selectPort = args[i];
continue;
}
if (args[i].equals("--curdir")) {
i++;
if (i < args.length)
currentDirectory = args[i];
continue;
}
String path = args[i];
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
if (isWindows()) {
try {
File file = new File(args[i]);
path = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!new File(path).isAbsolute()) {
path = new File(currentDirectory, path).getAbsolutePath();
}
if (handleOpen(path) != null) {
opened = true;
}
}
if (doUpload || doVerify) {
if (!opened) {
System.out.println(_("Can't open source sketch!"));
System.exit(2);
}
// Set verbosity for command line build
Preferences.set("build.verbose", "" + doVerbose);
Preferences.set("upload.verbose", "" + doVerbose);
Editor editor = editors.get(0);
// Wait until editor is initialized
while (!editor.status.isInitialized())
Thread.sleep(10);
// Do board selection if requested
if (selectBoard != null)
selectBoard(selectBoard);
if (doUpload) {
// Build and upload
if (selectPort != null)
editor.selectSerialPort(selectPort);
editor.exportHandler.run();
} else {
// Build only
editor.runHandler.run();
}
// Error during build or upload
int res = editor.status.mode;
if (res == EditorStatus.ERR)
System.exit(1);
// No errors exit gracefully
System.exit(0);
}
// Check if there were previously opened sketches to be restored
if (restoreSketches())
opened = true;
// Create a new empty window (will be replaced with any files to be opened)
if (!opened) {
handleNew();
}
// Check for updates
if (Preferences.getBoolean("update.check")) {
new UpdateCheck(this);
}
}
public Map<String, Map<String, Object>> getBoardsViaNetwork() {
return new HashMap<String, Map<String, Object>>(boardsViaNetwork);
}
/**
* Post-constructor setup for the editor area. Loads the last
* sketch that was used (if any), and restores other Editor settings.
* The complement to "storePreferences", this is called when the
* application is first launched.
* @throws Exception
*/
protected boolean restoreSketches() throws Exception {
// figure out window placement
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
boolean windowPositionValid = true;
if (Preferences.get("last.screen.height") != null) {
// if screen size has changed, the window coordinates no longer
// make sense, so don't use them unless they're identical
int screenW = Preferences.getInteger("last.screen.width");
int screenH = Preferences.getInteger("last.screen.height");
if ((screen.width != screenW) || (screen.height != screenH)) {
windowPositionValid = false;
}
/*
int windowX = Preferences.getInteger("last.window.x");
int windowY = Preferences.getInteger("last.window.y");
if ((windowX < 0) || (windowY < 0) ||
(windowX > screenW) || (windowY > screenH)) {
windowPositionValid = false;
}
*/
} else {
windowPositionValid = false;
}
// Iterate through all sketches that were open last time p5 was running.
// If !windowPositionValid, then ignore the coordinates found for each.
// Save the sketch path and window placement for each open sketch
int count = Preferences.getInteger("last.sketch.count");
int opened = 0;
for (int i = 0; i < count; i++) {
String path = Preferences.get("last.sketch" + i + ".path");
if (portableFolder != null) {
File absolute = new File(portableFolder, path);
try {
path = absolute.getCanonicalPath();
} catch (IOException e) {
// path unchanged.
}
}
int[] location;
if (windowPositionValid) {
String locationStr = Preferences.get("last.sketch" + i + ".location");
location = PApplet.parseInt(PApplet.split(locationStr, ','));
} else {
location = nextEditorLocation();
}
// If file did not exist, null will be returned for the Editor
if (handleOpen(path, location) != null) {
opened++;
}
}
return (opened > 0);
}
/**
* Store list of sketches that are currently open.
* Called when the application is quitting and documents are still open.
*/
protected void storeSketches() {
// Save the width and height of the screen
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Preferences.setInteger("last.screen.width", screen.width);
Preferences.setInteger("last.screen.height", screen.height);
String untitledPath = untitledFolder.getAbsolutePath();
// Save the sketch path and window placement for each open sketch
int index = 0;
for (Editor editor : editors) {
String path = editor.getSketch().getMainFilePath();
// In case of a crash, save untitled sketches if they contain changes.
// (Added this for release 0158, may not be a good idea.)
if (path.startsWith(untitledPath) &&
!editor.getSketch().isModified()) {
continue;
}
if (portableFolder != null) {
path = FileUtils.relativePath(portableFolder.toString(), path);
if (path == null)
continue;
}
Preferences.set("last.sketch" + index + ".path", path);
int[] location = editor.getPlacement();
String locationStr = PApplet.join(PApplet.str(location), ",");
Preferences.set("last.sketch" + index + ".location", locationStr);
index++;
}
Preferences.setInteger("last.sketch.count", index);
}
// If a sketch is untitled on quit, may need to store the new name
// rather than the location from the temp folder.
protected void storeSketchPath(Editor editor, int index) {
String path = editor.getSketch().getMainFilePath();
String untitledPath = untitledFolder.getAbsolutePath();
if (path.startsWith(untitledPath)) {
path = "";
} else
if (portableFolder != null) {
path = FileUtils.relativePath(portableFolder.toString(), path);
if (path == null)
path = "";
}
Preferences.set("last.sketch" + index + ".path", path);
}
/*
public void storeSketch(Editor editor) {
int index = -1;
for (int i = 0; i < editorCount; i++) {
if (editors[i] == editor) {
index = i;
break;
}
}
if (index == -1) {
System.err.println("Problem storing sketch " + editor.sketch.name);
} else {
String path = editor.sketch.getMainFilePath();
Preferences.set("last.sketch" + index + ".path", path);
}
}
*/
// Because of variations in native windowing systems, no guarantees about
// changes to the focused and active Windows can be made. Developers must
// never assume that this Window is the focused or active Window until this
// Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event.
protected void handleActivated(Editor whichEditor) {
activeEditor = whichEditor;
// set the current window to be the console that's getting output
EditorConsole.setEditor(activeEditor);
}
protected int[] nextEditorLocation() {
int defaultWidth = Preferences.getInteger("editor.window.width.default");
int defaultHeight = Preferences.getInteger("editor.window.height.default");
if (activeEditor == null) {
Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
// If no current active editor, use default placement
return new int[] {
(screen.width - defaultWidth) / 2,
(screen.height - defaultHeight) / 2,
defaultWidth, defaultHeight, 0
};
} else {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// With a currently active editor, open the new window
// using the same dimensions, but offset slightly.
synchronized (editors) {
final int OVER = 50;
// In release 0160, don't
//location = activeEditor.getPlacement();
Editor lastOpened = activeEditor;
int[] location = lastOpened.getPlacement();
// Just in case the bounds for that window are bad
location[0] += OVER;
location[1] += OVER;
if (location[0] == OVER ||
location[2] == OVER ||
location[0] + location[2] > screen.width ||
location[1] + location[3] > screen.height) {
// Warp the next window to a randomish location on screen.
return new int[] {
(int) (Math.random() * (screen.width - defaultWidth)),
(int) (Math.random() * (screen.height - defaultHeight)),
defaultWidth, defaultHeight, 0
};
}
return location;
}
}
}
boolean breakTime = false;
String[] months = {
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"
};
/**
* Handle creating a sketch folder, return its base .pde file
* or null if the operation was canceled.
* @param shift whether shift is pressed, which will invert prompt setting
* @param noPrompt disable prompt, no matter the setting
*/
protected String createNewUntitled() throws IOException {
File newbieDir = null;
String newbieName = null;
// In 0126, untitled sketches will begin in the temp folder,
// and then moved to a new location because Save will default to Save As.
File sketchbookDir = getSketchbookFolder();
File newbieParentDir = untitledFolder;
// Use a generic name like sketch_031008a, the date plus a char
int index = 0;
//SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
//SimpleDateFormat formatter = new SimpleDateFormat("MMMdd");
//String purty = formatter.format(new Date()).toLowerCase();
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31
int month = cal.get(Calendar.MONTH); // 0..11
String purty = months[month] + PApplet.nf(day, 2);
do {
if (index == 26) {
// In 0159, avoid running past z by sending people outdoors.
if (!breakTime) {
Base.showWarning(_("Time for a Break"),
_("You've reached the limit for auto naming of new sketches\n" +
"for the day. How about going for a walk instead?"), null);
breakTime = true;
} else {
Base.showWarning(_("Sunshine"),
_("No really, time for some fresh air for you."), null);
}
return null;
}
newbieName = "sketch_" + purty + ((char) ('a' + index));
newbieDir = new File(newbieParentDir, newbieName);
index++;
// Make sure it's not in the temp folder *and* it's not in the sketchbook
} while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists());
// Make the directory for the new sketch
newbieDir.mkdirs();
// Make an empty pde file
File newbieFile = new File(newbieDir, newbieName + ".ino");
if (!newbieFile.createNewFile()) {
throw new IOException();
}
FileUtils.copyFile(new File(getContentFile("examples"), "01.Basics" + File.separator + "BareMinimum" + File.separator + "BareMinimum.ino"), newbieFile);
return newbieFile.getAbsolutePath();
}
/**
* Create a new untitled document in a new sketch window.
* @throws Exception
*/
public void handleNew() throws Exception {
try {
String path = createNewUntitled();
if (path != null) {
Editor editor = handleOpen(path);
editor.untitled = true;
}
} catch (IOException e) {
if (activeEditor != null) {
activeEditor.statusError(e);
}
}
}
/**
* Replace the sketch in the current window with a new untitled document.
*/
public void handleNewReplace() {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
// Actually replace things
handleNewReplaceImpl();
}
protected void handleNewReplaceImpl() {
try {
String path = createNewUntitled();
if (path != null) {
activeEditor.handleOpenInternal(path);
activeEditor.untitled = true;
}
// return true;
} catch (IOException e) {
activeEditor.statusError(e);
// return false;
}
}
/**
* Open a sketch, replacing the sketch in the current window.
* @param path Location of the primary pde file for the sketch.
*/
public void handleOpenReplace(String path) {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
boolean loaded = activeEditor.handleOpenInternal(path);
if (!loaded) {
// replace the document without checking if that's ok
handleNewReplaceImpl();
}
}
/**
* Prompt for a sketch to open, and open it in a new window.
* @throws Exception
*/
public void handleOpenPrompt() throws Exception {
// get the frontmost window frame for placing file dialog
JFileChooser fd = new JFileChooser(Preferences.get("last.folder", Base.getSketchbookFolder().getAbsolutePath()));
fd.setDialogTitle(_("Open an Arduino sketch..."));
fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
fd.setFileFilter(new FileNameExtensionFilter(_("Sketches (*.ino, *.pde)"), "ino", "pde"));
Dimension preferredSize = fd.getPreferredSize();
fd.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200));
int returnVal = fd.showOpenDialog(activeEditor);
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File inputFile = fd.getSelectedFile();
Preferences.set("last.folder", inputFile.getAbsolutePath());
handleOpen(inputFile.getAbsolutePath());
}
/**
* Open a sketch in a new window.
* @param path Path to the pde file for the sketch in question
* @return the Editor object, so that properties (like 'untitled')
* can be set by the caller
* @throws Exception
*/
public Editor handleOpen(String path) throws Exception {
return handleOpen(path, nextEditorLocation());
}
protected Editor handleOpen(String path, int[] location) throws Exception {
// System.err.println("entering handleOpen " + path);
File file = new File(path);
if (!file.exists()) return null;
// System.err.println(" editors: " + editors);
// Cycle through open windows to make sure that it's not already open.
for (Editor editor : editors) {
if (editor.getSketch().getMainFilePath().equals(path)) {
editor.toFront();
// System.err.println(" handleOpen: already opened");
return editor;
}
}
// If the active editor window is an untitled, and un-modified document,
// just replace it with the file that's being opened.
// if (activeEditor != null) {
// Sketch activeSketch = activeEditor.sketch;
// if (activeSketch.isUntitled() && !activeSketch.isModified()) {
// // if it's an untitled, unmodified document, it can be replaced.
// // except in cases where a second blank window is being opened.
// if (!path.startsWith(untitledFolder.getAbsolutePath())) {
// activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0);
// return activeEditor;
// System.err.println(" creating new editor");
Editor editor = new Editor(this, path, location);
// Editor editor = null;
// try {
// editor = new Editor(this, path, location);
// } catch (Exception e) {
// e.printStackTrace();
// System.err.flush();
// System.out.flush();
// System.exit(1);
// System.err.println(" done creating new editor");
// EditorConsole.systemErr.println(" done creating new editor");
// Make sure that the sketch actually loaded
if (editor.getSketch() == null) {
// System.err.println("sketch was null, getting out of handleOpen");
return null; // Just walk away quietly
}
// if (editors == null) {
// editors = new Editor[5];
// if (editorCount == editors.length) {
// editors = (Editor[]) PApplet.expand(editors);
// editors[editorCount++] = editor;
editors.add(editor);
// if (markedForClose != null) {
// Point p = markedForClose.getLocation();
// handleClose(markedForClose, false);
// // open the new window in
// editor.setLocation(p);
// now that we're ready, show the window
// (don't do earlier, cuz we might move it based on a window being closed)
editor.setVisible(true);
// System.err.println("exiting handleOpen");
return editor;
}
/**
* Close a sketch as specified by its editor window.
* @param editor Editor object of the sketch to be closed.
* @return true if succeeded in closing, false if canceled.
*/
public boolean handleClose(Editor editor) {
// Check if modified
// boolean immediate = editors.size() == 1;
if (!editor.checkModified()) {
return false;
}
// Close the running window, avoid window boogers with multiple sketches
editor.internalCloseRunner();
if (editors.size() == 1) {
// For 0158, when closing the last window /and/ it was already an
// untitled sketch, just give up and let the user quit.
// if (Preferences.getBoolean("sketchbook.closing_last_window_quits") ||
// (editor.untitled && !editor.getSketch().isModified())) {
if (Base.isMacOS()) {
Object[] options = { "OK", "Cancel" };
String prompt =
_("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Are you sure you want to Quit?</b>" +
"<p>Closing the last open sketch will quit Arduino.");
int result = JOptionPane.showOptionDialog(editor,
prompt,
_("Quit"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.NO_OPTION ||
result == JOptionPane.CLOSED_OPTION) {
return false;
}
}
// This will store the sketch count as zero
editors.remove(editor);
try {
Editor.serialMonitor.close();
} catch (Exception e) {
//ignore
}
storeSketches();
// Save out the current prefs state
Preferences.save();
// Since this wasn't an actual Quit event, call System.exit()
System.exit(0);
} else {
// More than one editor window open,
// proceed with closing the current window.
editor.setVisible(false);
editor.dispose();
// for (int i = 0; i < editorCount; i++) {
// if (editor == editors[i]) {
// for (int j = i; j < editorCount-1; j++) {
// editors[j] = editors[j+1];
// editorCount--;
// // Set to null so that garbage collection occurs
// editors[editorCount] = null;
editors.remove(editor);
}
return true;
}
/**
* Handler for File → Quit.
* @return false if canceled, true otherwise.
*/
public boolean handleQuit() {
// If quit is canceled, this will be replaced anyway
// by a later handleQuit() that is not canceled.
storeSketches();
try {
Editor.serialMonitor.close();
} catch (Exception e) {
// ignore
}
if (handleQuitEach()) {
// make sure running sketches close before quitting
for (Editor editor : editors) {
editor.internalCloseRunner();
}
// Save out the current prefs state
Preferences.save();
if (!Base.isMacOS()) {
// If this was fired from the menu or an AppleEvent (the Finder),
// then Mac OS X will send the terminate signal itself.
System.exit(0);
}
return true;
}
return false;
}
/**
* Attempt to close each open sketch in preparation for quitting.
* @return false if canceled along the way
*/
protected boolean handleQuitEach() {
int index = 0;
for (Editor editor : editors) {
if (editor.checkModified()) {
// Update to the new/final sketch path for this fella
storeSketchPath(editor, index);
index++;
} else {
return false;
}
}
return true;
}
/**
* Asynchronous version of menu rebuild to be used on save and rename
* to prevent the interface from locking up until the menus are done.
*/
protected void rebuildSketchbookMenus() {
//System.out.println("async enter");
//new Exception().printStackTrace();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//System.out.println("starting rebuild");
rebuildSketchbookMenu(Editor.sketchbookMenu);
rebuildToolbarMenu(Editor.toolbarMenu);
//System.out.println("done with rebuild");
}
});
//System.out.println("async exit");
}
protected void rebuildToolbarMenu(JMenu menu) {
JMenuItem item;
menu.removeAll();
// Add the single "Open" item
item = Editor.newJMenuItem(_("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
menu.add(item);
menu.addSeparator();
// Add a list of all sketches and subfolders
try {
boolean sketches = addSketches(menu, getSketchbookFolder(), true);
if (sketches) menu.addSeparator();
} catch (IOException e) {
e.printStackTrace();
}
// Add each of the subfolders of examples directly to the menu
try {
boolean found = addSketches(menu, examplesFolder, true);
if (found) menu.addSeparator();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void rebuildSketchbookMenu(JMenu menu) {
//System.out.println("rebuilding sketchbook menu");
//new Exception().printStackTrace();
try {
menu.removeAll();
addSketches(menu, getSketchbookFolder(), false);
//addSketches(menu, getSketchbookFolder());
} catch (IOException e) {
e.printStackTrace();
}
}
public LibraryList getIDELibs() {
if (libraries == null)
return new LibraryList();
LibraryList res = new LibraryList(libraries);
res.removeAll(getUserLibs());
return res;
}
public LibraryList getUserLibs() {
if (libraries == null)
return new LibraryList();
return libraries.filterLibrariesInSubfolder(getSketchbookFolder());
}
public void rebuildImportMenu(JMenu importMenu) {
importMenu.removeAll();
JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library..."));
addLibraryMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.this.handleAddLibrary();
Base.this.onBoardOrPortChange();
Base.this.rebuildImportMenu(Editor.importMenu);
Base.this.rebuildExamplesMenu(Editor.examplesMenu);
}
});
importMenu.add(addLibraryMenuItem);
importMenu.addSeparator();
// Split between user supplied libraries and IDE libraries
TargetPlatform targetPlatform = getTargetPlatform();
if (targetPlatform != null) {
LibraryList ideLibs = getIDELibs();
LibraryList userLibs = getUserLibs();
try {
// Find the current target. Get the platform, and then select the
// correct name and core path.
PreferencesMap prefs = targetPlatform.getPreferences();
if (prefs != null) {
String platformName = prefs.get("name");
if (platformName != null) {
JMenuItem platformItem = new JMenuItem(_(platformName));
platformItem.setEnabled(false);
importMenu.add(platformItem);
}
}
if (ideLibs.size() > 0) {
importMenu.addSeparator();
addLibraries(importMenu, ideLibs);
}
if (userLibs.size() > 0) {
importMenu.addSeparator();
addLibraries(importMenu, userLibs);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void rebuildExamplesMenu(JMenu menu) {
try {
menu.removeAll();
// Add examples from distribution "example" folder
boolean found = addSketches(menu, examplesFolder, false);
if (found) menu.addSeparator();
// Add examples from libraries
LibraryList ideLibs = getIDELibs();
ideLibs.sort();
for (Library lib : ideLibs)
addSketchesSubmenu(menu, lib, false);
LibraryList userLibs = getUserLibs();
if (userLibs.size()>0) {
menu.addSeparator();
userLibs.sort();
for (Library lib : userLibs)
addSketchesSubmenu(menu, lib, false);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public LibraryList scanLibraries(List<File> folders) throws IOException {
LibraryList res = new LibraryList();
for (File folder : folders)
res.addOrReplaceAll(scanLibraries(folder));
return res;
}
public LibraryList scanLibraries(File folder) throws IOException {
LibraryList res = new LibraryList();
String list[] = folder.list(new OnlyDirs());
// if a bad folder or something like that, this might come back null
if (list == null)
return res;
for (String libName : list) {
File subfolder = new File(folder, libName);
if (!Sketch.isSanitaryName(libName)) {
String mess = I18n.format(_("The library \"{0}\" cannot be used.\n"
+ "Library names must contain only basic letters and numbers.\n"
+ "(ASCII only and no spaces, and it cannot start with a number)"),
libName);
Base.showMessage(_("Ignoring bad library name"), mess);
continue;
}
try {
Library lib = Library.create(subfolder);
// (also replace previously found libs with the same name)
if (lib != null)
res.addOrReplace(lib);
} catch (IOException e) {
System.out.println(I18n.format(_("Invalid library found in {0}: {1}"),
subfolder, e.getMessage()));
}
}
return res;
}
public void onBoardOrPortChange() {
TargetPlatform targetPlatform = getTargetPlatform();
if (targetPlatform == null)
return;
// Calculate paths for libraries and examples
examplesFolder = getContentFile("examples");
toolsFolder = getContentFile("tools");
File platformFolder = targetPlatform.getFolder();
librariesFolders = new ArrayList<File>();
librariesFolders.add(getContentFile("libraries"));
String core = getBoardPreferences().get("build.core");
if (core.contains(":")) {
String referencedCore = core.split(":")[0];
TargetPlatform referencedPlatform = Base.getTargetPlatform(referencedCore, targetPlatform.getId());
if (referencedPlatform != null) {
File referencedPlatformFolder = referencedPlatform.getFolder();
librariesFolders.add(new File(referencedPlatformFolder, "libraries"));
}
}
librariesFolders.add(new File(platformFolder, "libraries"));
librariesFolders.add(getSketchbookLibrariesFolder());
// Scan for libraries in each library folder.
// Libraries located in the latest folders on the list can override
// other libraries with the same name.
try {
libraries = scanLibraries(librariesFolders);
} catch (IOException e) {
showWarning(_("Error"), _("Error loading libraries"), e);
}
String currentArch = Base.getTargetPlatform().getId();
libraries = libraries.filterByArchitecture(currentArch);
// Populate importToLibraryTable
importToLibraryTable = new HashMap<String, Library>();
for (Library lib : libraries) {
try {
String headers[] = headerListFromIncludePath(lib.getSrcFolder());
for (String header : headers) {
importToLibraryTable.put(header, lib);
}
} catch (IOException e) {
showWarning(_("Error"), I18n
.format("Unable to list header files in {0}", lib.getSrcFolder()), e);
}
}
// Update editors status bar
for (Editor editor : editors)
editor.onBoardOrPortChange();
}
public void rebuildBoardsMenu(JMenu toolsMenu, Editor editor) throws Exception {
JMenu boardsMenu = getBoardCustomMenu();
boolean first = true;
List<JMenuItem> menuItemsToClickAfterStartup = new LinkedList<JMenuItem>();
ButtonGroup boardsButtonGroup = new ButtonGroup();
Map<String, ButtonGroup> buttonGroupsMap = new HashMap<String, ButtonGroup>();
// Generate custom menus for all platforms
Set<String> titles = new HashSet<String>();
for (TargetPackage targetPackage : packages.values()) {
for (TargetPlatform targetPlatform : targetPackage.platforms())
titles.addAll(targetPlatform.getCustomMenus().values());
}
for (String title : titles)
makeBoardCustomMenu(toolsMenu, _(title));
// Cycle through all packages
for (TargetPackage targetPackage : packages.values()) {
// For every package cycle through all platform
for (TargetPlatform targetPlatform : targetPackage.platforms()) {
// Add a separator from the previous platform
if (!first)
boardsMenu.add(new JSeparator());
first = false;
// Add a title for each platform
String platformLabel = targetPlatform.getPreferences().get("name");
if (platformLabel != null && !targetPlatform.getBoards().isEmpty()) {
JMenuItem menuLabel = new JMenuItem(_(platformLabel));
menuLabel.setEnabled(false);
boardsMenu.add(menuLabel);
}
// Cycle through all boards of this platform
for (TargetBoard board : targetPlatform.getBoards().values()) {
JMenuItem item = createBoardMenusAndCustomMenus(menuItemsToClickAfterStartup,
buttonGroupsMap,
board, targetPlatform, targetPackage);
boardsMenu.add(item);
boardsButtonGroup.add(item);
}
}
}
if (menuItemsToClickAfterStartup.isEmpty()) {
menuItemsToClickAfterStartup.add(selectFirstEnabledMenuItem(boardsMenu));
}
for (JMenuItem menuItemToClick : menuItemsToClickAfterStartup) {
menuItemToClick.setSelected(true);
menuItemToClick.getAction().actionPerformed(new ActionEvent(this, -1, ""));
}
}
private JRadioButtonMenuItem createBoardMenusAndCustomMenus(
List<JMenuItem> menuItemsToClickAfterStartup,
Map<String, ButtonGroup> buttonGroupsMap,
TargetBoard board, TargetPlatform targetPlatform, TargetPackage targetPackage)
throws Exception {
String selPackage = Preferences.get("target_package");
String selPlatform = Preferences.get("target_platform");
String selBoard = Preferences.get("board");
String boardId = board.getId();
String packageName = targetPackage.getId();
String platformName = targetPlatform.getId();
// Setup a menu item for the current board
@SuppressWarnings("serial")
Action action = new AbstractAction(board.getName()) {
public void actionPerformed(ActionEvent actionevent) {
selectBoard((String) getValue("b"));
}
};
action.putValue("b", packageName + ":" + platformName + ":" + boardId);
JRadioButtonMenuItem item = new JRadioButtonMenuItem(action);
if (selBoard.equals(boardId) && selPackage.equals(packageName)
&& selPlatform.equals(platformName)) {
menuItemsToClickAfterStartup.add(item);
}
int i = 0;
PreferencesMap customMenus = targetPlatform.getCustomMenus();
for (final String menuId : customMenus.keySet()) {
String title = customMenus.get(menuId);
JMenu menu = getBoardCustomMenu(_(title));
if (board.hasMenu(menuId)) {
PreferencesMap boardCustomMenu = board.getMenuLabels(menuId);
final int currentIndex = i + 1 + 1; //plus 1 to skip the first board menu, plus 1 to keep the custom menu next to this one
i++;
for (String customMenuOption : boardCustomMenu.keySet()) {
@SuppressWarnings("serial")
Action subAction = new AbstractAction(_(boardCustomMenu.get(customMenuOption))) {
public void actionPerformed(ActionEvent e) {
Preferences.set("target_package", (String) getValue("package"));
Preferences.set("target_platform", (String) getValue("platform"));
Preferences.set("board", (String) getValue("board"));
Preferences.set("custom_" + menuId, getValue("board") + "_" + getValue("custom_menu_option"));
filterVisibilityOfSubsequentBoardMenus((String) getValue("board"), currentIndex);
onBoardOrPortChange();
Sketch.buildSettingChanged();
rebuildImportMenu(Editor.importMenu);
rebuildExamplesMenu(Editor.examplesMenu);
}
};
subAction.putValue("board", boardId);
subAction.putValue("custom_menu_option", customMenuOption);
subAction.putValue("package", packageName);
subAction.putValue("platform", platformName);
if (!buttonGroupsMap.containsKey(menuId)) {
buttonGroupsMap.put(menuId, new ButtonGroup());
}
JRadioButtonMenuItem subItem = new JRadioButtonMenuItem(subAction);
menu.add(subItem);
buttonGroupsMap.get(menuId).add(subItem);
String selectedCustomMenuEntry = Preferences.get("custom_" + menuId);
if (selBoard.equals(boardId) && (boardId + "_" + customMenuOption).equals(selectedCustomMenuEntry)) {
menuItemsToClickAfterStartup.add(subItem);
}
}
}
}
return item;
}
private static void filterVisibilityOfSubsequentBoardMenus(String boardID, int fromIndex) {
for (int i = fromIndex; i < Editor.boardsMenus.size(); i++) {
JMenu menu = Editor.boardsMenus.get(i);
for (int m = 0; m < menu.getItemCount(); m++) {
JMenuItem menuItem = menu.getItem(m);
menuItem.setVisible(menuItem.getAction().getValue("board").equals(boardID));
}
menu.setVisible(ifThereAreVisibleItemsOn(menu));
if (menu.isVisible()) {
JMenuItem visibleSelectedOrFirstMenuItem = selectVisibleSelectedOrFirstMenuItem(menu);
if (!visibleSelectedOrFirstMenuItem.isSelected()) {
visibleSelectedOrFirstMenuItem.setSelected(true);
visibleSelectedOrFirstMenuItem.getAction().actionPerformed(null);
}
}
}
}
private static boolean ifThereAreVisibleItemsOn(JMenu menu) {
for (int i = 0; i < menu.getItemCount(); i++) {
if (menu.getItem(i).isVisible()) {
return true;
}
}
return false;
}
private JMenu makeBoardCustomMenu(JMenu toolsMenu, String label) {
JMenu menu = new JMenu(label);
Editor.boardsMenus.add(menu);
toolsMenu.add(menu);
return menu;
}
private JMenu getBoardCustomMenu() throws Exception {
return getBoardCustomMenu(_("Board"));
}
private JMenu getBoardCustomMenu(String label) throws Exception {
for (JMenu menu : Editor.boardsMenus)
if (label.equals(menu.getText()))
return menu;
throw new Exception("Custom menu not found!");
}
private static JMenuItem selectVisibleSelectedOrFirstMenuItem(JMenu menu) {
JMenuItem firstVisible = null;
for (int i = 0; i < menu.getItemCount(); i++) {
JMenuItem item = menu.getItem(i);
if (item != null && item.isVisible()) {
if (item.isSelected()) {
return item;
}
if (firstVisible == null) {
firstVisible = item;
}
}
}
if (firstVisible != null) {
return firstVisible;
}
throw new IllegalStateException("Menu has no enabled items");
}
private static JMenuItem selectFirstEnabledMenuItem(JMenu menu) {
for (int i = 0; i < menu.getItemCount(); i++) {
JMenuItem item = menu.getItem(i);
if (item != null && item.isEnabled()) {
return item;
}
}
throw new IllegalStateException("Menu has no enabled items");
}
private void selectBoard(String selectBoard) {
String[] split = selectBoard.split(":");
Preferences.set("target_package", split[0]);
Preferences.set("target_platform", split[1]);
String boardId = split[2];
Preferences.set("board", boardId);
if (split.length > 3) {
String[] customsParts = split[3].split(",");
for (String customParts : customsParts) {
String[] keyValue = customParts.split("=");
Preferences.set("custom_" + keyValue[0].trim(), boardId + "_" + keyValue[1].trim());
}
}
filterVisibilityOfSubsequentBoardMenus(boardId, 1);
onBoardOrPortChange();
Sketch.buildSettingChanged();
rebuildImportMenu(Editor.importMenu);
rebuildExamplesMenu(Editor.examplesMenu);
}
public void rebuildProgrammerMenu(JMenu menu) {
menu.removeAll();
ButtonGroup group = new ButtonGroup();
for (TargetPackage targetPackage : packages.values()) {
for (TargetPlatform targetPlatform : targetPackage.platforms()) {
for (String programmer : targetPlatform.getProgrammers().keySet()) {
String id = targetPackage.getId() + ":" + programmer;
@SuppressWarnings("serial")
AbstractAction action = new AbstractAction(targetPlatform
.getProgrammer(programmer).get("name")) {
public void actionPerformed(ActionEvent actionevent) {
Preferences.set("programmer", "" + getValue("id"));
}
};
action.putValue("id", id);
JMenuItem item = new JRadioButtonMenuItem(action);
if (Preferences.get("programmer").equals(id))
item.setSelected(true);
group.add(item);
menu.add(item);
}
}
}
}
/**
* Scan a folder recursively, and add any sketches found to the menu
* specified. Set the openReplaces parameter to true when opening the sketch
* should replace the sketch in the current window, or false when the
* sketch should open in a new window.
*/
protected boolean addSketches(JMenu menu, File folder, final boolean replaceExisting) throws IOException {
if (folder == null)
return false;
if (!folder.isDirectory()) return false;
File[] files = folder.listFiles();
// If a bad folder or unreadable or whatever, this will come back null
if (files == null) return false;
// Alphabetize files, since it's not always alpha order
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File file, File file2) {
return file.getName().compareToIgnoreCase(file2.getName());
}
});
boolean ifound = false;
for (File subfolder : files) {
if (FileUtils.isSCCSOrHiddenFile(subfolder)) {
continue;
}
if (!subfolder.isDirectory()) continue;
if (addSketchesSubmenu(menu, subfolder.getName(), subfolder, replaceExisting)) {
ifound = true;
}
}
return ifound;
}
private boolean addSketchesSubmenu(JMenu menu, Library lib,
boolean replaceExisting)
throws IOException {
return addSketchesSubmenu(menu, lib.getName(), lib.getFolder(),
replaceExisting);
}
private boolean addSketchesSubmenu(JMenu menu, String name, File folder,
final boolean replaceExisting) throws IOException {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = e.getActionCommand();
if (new File(path).exists()) {
boolean replace = replaceExisting;
if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
replace = !replace;
}
if (replace) {
handleOpenReplace(path);
} else {
try {
handleOpen(path);
} catch (Exception e1) {
e1.printStackTrace();
}
}
} else {
showWarning(_("Sketch Does Not Exist"),
_("The selected sketch no longer exists.\n"
+ "You may need to restart Arduino to update\n"
+ "the sketchbook menu."), null);
}
}
};
File entry = new File(folder, name + ".ino");
if (!entry.exists() && (new File(folder, name + ".pde")).exists())
entry = new File(folder, name + ".pde");
// if a .pde file of the same prefix as the folder exists..
if (entry.exists()) {
if (!Sketch.isSanitaryName(name)) {
if (!builtOnce) {
String complaining = I18n
.format(
_("The sketch \"{0}\" cannot be used.\n"
+ "Sketch names must contain only basic letters and numbers\n"
+ "(ASCII-only with no spaces, "
+ "and it cannot start with a number).\n"
+ "To get rid of this message, remove the sketch from\n"
+ "{1}"), name, entry.getAbsolutePath());
Base.showMessage(_("Ignoring sketch with bad name"), complaining);
}
return false;
}
JMenuItem item = new JMenuItem(name);
item.addActionListener(listener);
item.setActionCommand(entry.getAbsolutePath());
menu.add(item);
return true;
}
// don't create an extra menu level for a folder named "examples"
if (folder.getName().equals("examples"))
return addSketches(menu, folder, replaceExisting);
// not a sketch folder, but maybe a subfolder containing sketches
JMenu submenu = new JMenu(name);
boolean found = addSketches(submenu, folder, replaceExisting);
if (found) {
menu.add(submenu);
MenuScroller.setScrollerFor(submenu);
}
return found;
}
protected void addLibraries(JMenu menu, LibraryList libs) throws IOException {
LibraryList list = new LibraryList(libs);
list.sort();
for (Library lib : list) {
@SuppressWarnings("serial")
AbstractAction action = new AbstractAction(lib.getName()) {
public void actionPerformed(ActionEvent event) {
Library l = (Library) getValue("library");
try {
activeEditor.getSketch().importLibrary(l);
} catch (IOException e) {
showWarning(_("Error"), I18n.format("Unable to list header files in {0}", l.getSrcFolder()), e);
}
}
};
action.putValue("library", lib);
// Add new element at the bottom
JMenuItem item = new JMenuItem(action);
item.putClientProperty("library", lib);
menu.add(item);
// XXX: DAM: should recurse here so that library folders can be nested
}
}
/**
* Given a folder, return a list of the header files in that folder (but not
* the header files in its sub-folders, as those should be included from
* within the header files at the top-level).
*/
static public String[] headerListFromIncludePath(File path) throws IOException {
String[] list = path.list(new OnlyFilesWithExtension(".h"));
if (list == null) {
throw new IOException();
}
return list;
}
protected void loadHardware(File folder) {
if (!folder.isDirectory()) return;
String list[] = folder.list(new OnlyDirs());
// if a bad folder or something like that, this might come back null
if (list == null) return;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String target : list) {
// Skip reserved 'tools' folder.
if (target.equals("tools"))
continue;
File subfolder = new File(folder, target);
try {
packages.put(target, new TargetPackage(target, subfolder));
} catch (TargetPlatformException e) {
System.out.println("WARNING: Error loading hardware folder " + target);
System.out.println(" " + e.getMessage());
}
}
}
/**
* Show the About box.
*/
@SuppressWarnings("serial")
public void handleAbout() {
final Image image = Base.getLibImage("about.jpg", activeEditor);
final Window window = new Window(activeEditor) {
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setFont(new Font("SansSerif", Font.PLAIN, 11));
g.setColor(Color.white);
g.drawString(Base.VERSION_NAME, 50, 30);
}
};
window.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
window.dispose();
}
});
int w = image.getWidth(activeEditor);
int h = image.getHeight(activeEditor);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h);
window.setVisible(true);
}
/**
* Show the Preferences window.
*/
public void handlePrefs() {
if (preferencesFrame == null) preferencesFrame = new Preferences();
preferencesFrame.showFrame(activeEditor);
}
/**
* Get list of platform constants.
*/
// static public int[] getPlatforms() {
// return platforms;
// static public int getPlatform() {
// String osname = System.getProperty("os.name");
// if (osname.indexOf("Mac") != -1) {
// return PConstants.MACOSX;
// } else if (osname.indexOf("Windows") != -1) {
// return PConstants.WINDOWS;
// } else if (osname.equals("Linux")) { // true for the ibm vm
// return PConstants.LINUX;
// } else {
// return PConstants.OTHER;
static public Platform getPlatform() {
return platform;
}
static public String getPlatformName() {
String osname = System.getProperty("os.name");
if (osname.indexOf("Mac") != -1) {
return "macosx";
} else if (osname.indexOf("Windows") != -1) {
return "windows";
} else if (osname.equals("Linux")) { // true for the ibm vm
return "linux";
} else {
return "other";
}
}
/**
* Map a platform constant to its name.
* @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX
* @return one of "windows", "macosx", or "linux"
*/
static public String getPlatformName(int which) {
return platformNames.get(which);
}
static public int getPlatformIndex(String what) {
Integer entry = platformIndices.get(what);
return (entry == null) ? -1 : entry.intValue();
}
// These were changed to no longer rely on PApplet and PConstants because
// of conflicts that could happen with older versions of core.jar, where
// the MACOSX constant would instead read as the LINUX constant.
/**
* returns true if Processing is running on a Mac OS X machine.
*/
static public boolean isMacOS() {
//return PApplet.platform == PConstants.MACOSX;
return System.getProperty("os.name").indexOf("Mac") != -1;
}
/**
* returns true if running on windows.
*/
static public boolean isWindows() {
//return PApplet.platform == PConstants.WINDOWS;
return System.getProperty("os.name").indexOf("Windows") != -1;
}
/**
* true if running on linux.
*/
static public boolean isLinux() {
//return PApplet.platform == PConstants.LINUX;
return System.getProperty("os.name").indexOf("Linux") != -1;
}
static public File getSettingsFolder() {
if (portableFolder != null)
return portableFolder;
File settingsFolder = null;
String preferencesPath = Preferences.get("settings.path");
if (preferencesPath != null) {
settingsFolder = new File(preferencesPath);
} else {
try {
settingsFolder = platform.getSettingsFolder();
} catch (Exception e) {
showError(_("Problem getting data folder"),
_("Error getting the Arduino data folder."), e);
}
}
// create the folder if it doesn't exist already
if (!settingsFolder.exists()) {
if (!settingsFolder.mkdirs()) {
showError(_("Settings issues"),
_("Arduino cannot run because it could not\n" +
"create a folder to store your settings."), null);
}
}
return settingsFolder;
}
/**
* Convenience method to get a File object for the specified filename inside
* the settings folder.
* For now, only used by Preferences to get the preferences.txt file.
* @param filename A file inside the settings folder.
* @return filename wrapped as a File object inside the settings folder
*/
static public File getSettingsFile(String filename) {
return new File(getSettingsFolder(), filename);
}
static public File getBuildFolder() {
if (buildFolder == null) {
String buildPath = Preferences.get("build.path");
if (buildPath != null) {
buildFolder = new File(buildPath);
} else {
//File folder = new File(getTempFolder(), "build");
//if (!folder.exists()) folder.mkdirs();
buildFolder = createTempFolder("build");
buildFolder.deleteOnExit();
}
}
return buildFolder;
}
/**
* Get the path to the platform's temporary folder, by creating
* a temporary temporary file and getting its parent folder.
* <br/>
* Modified for revision 0094 to actually make the folder randomized
* to avoid conflicts in multi-user environments. (Bug 177)
*/
static public File createTempFolder(String name) {
try {
File folder = File.createTempFile(name, null);
//String tempPath = ignored.getParent();
//return new File(tempPath);
folder.delete();
folder.mkdirs();
return folder;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static public LibraryList getLibraries() {
return libraries;
}
static public String getExamplesPath() {
return examplesFolder.getAbsolutePath();
}
static public List<File> getLibrariesPath() {
return librariesFolders;
}
static public File getToolsFolder() {
return toolsFolder;
}
static public String getToolsPath() {
return toolsFolder.getAbsolutePath();
}
static public File getHardwareFolder() {
// calculate on the fly because it's needed by Preferences.init() to find
// the boards.txt and programmers.txt preferences files (which happens
// before the other folders / paths get cached).
return getContentFile("hardware");
}
//Get the core libraries
static public File getCoreLibraries(String path) {
return getContentFile(path);
}
static public String getHardwarePath() {
return getHardwareFolder().getAbsolutePath();
}
static public String getAvrBasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "avr" + File.separator + "bin" + File.separator;
if (Base.isLinux() && !(new File(path)).exists()) {
return ""; // use distribution provided avr tools if bundled tools missing
}
return path;
}
/**
* Returns the currently selected TargetPlatform.
*
* @return
*/
static public TargetPlatform getTargetPlatform() {
String packageName = Preferences.get("target_package");
String platformName = Preferences.get("target_platform");
return getTargetPlatform(packageName, platformName);
}
/**
* Returns a specific TargetPlatform searching Package/Platform
*
* @param packageName
* @param platformName
* @return
*/
static public TargetPlatform getTargetPlatform(String packageName,
String platformName) {
TargetPackage p = packages.get(packageName);
if (p == null)
return null;
return p.get(platformName);
}
static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) {
return getTargetPlatform(pack, Preferences.get("target_platform"));
}
static public PreferencesMap getBoardPreferences() {
TargetBoard board = getTargetBoard();
PreferencesMap prefs = new PreferencesMap(board.getPreferences());
for (String menuId : board.getMenuIds()) {
String entry = Preferences.get("custom_" + menuId);
if (board.hasMenu(menuId) && entry != null &&
entry.startsWith(board.getId())) {
String selectionId = entry.substring(entry.indexOf("_") + 1);
prefs.putAll(board.getMenuPreferences(menuId, selectionId));
prefs.put("name", prefs.get("name") + ", " +
board.getMenuLabel(menuId, selectionId));
}
}
return prefs;
}
public static TargetBoard getTargetBoard() {
String boardId = Preferences.get("board");
return getTargetPlatform().getBoard(boardId);
}
static public File getPortableFolder() {
return portableFolder;
}
static public String getPortableSketchbookFolder() {
return portableSketchbookFolder;
}
static public File getSketchbookFolder() {
if (portableFolder != null)
return new File(portableFolder, Preferences.get("sketchbook.path"));
return new File(Preferences.get("sketchbook.path"));
}
static public File getSketchbookLibrariesFolder() {
File libdir = new File(getSketchbookFolder(), "libraries");
if (!libdir.exists()) {
try {
libdir.mkdirs();
File readme = new File(libdir, "readme.txt");
FileWriter freadme = new FileWriter(readme);
freadme.write(_("For information on installing libraries, see: " +
"http://arduino.cc/en/Guide/Libraries\n"));
freadme.close();
} catch (Exception e) {
}
}
return libdir;
}
static public String getSketchbookLibrariesPath() {
return getSketchbookLibrariesFolder().getAbsolutePath();
}
static public File getSketchbookHardwareFolder() {
return new File(getSketchbookFolder(), "hardware");
}
protected File getDefaultSketchbookFolder() {
if (portableFolder != null)
return new File(portableFolder, portableSketchbookFolder);
File sketchbookFolder = null;
try {
sketchbookFolder = platform.getDefaultSketchbookFolder();
} catch (Exception e) { }
if (sketchbookFolder == null) {
sketchbookFolder = promptSketchbookLocation();
}
// create the folder if it doesn't exist already
boolean result = true;
if (!sketchbookFolder.exists()) {
result = sketchbookFolder.mkdirs();
}
if (!result) {
showError(_("You forgot your sketchbook"),
_("Arduino cannot run because it could not\n" +
"create a folder to store your sketchbook."), null);
}
return sketchbookFolder;
}
/**
* Check for a new sketchbook location.
*/
static protected File promptSketchbookLocation() {
File folder = null;
folder = new File(System.getProperty("user.home"), "sketchbook");
if (!folder.exists()) {
folder.mkdirs();
return folder;
}
String prompt = _("Select (or create new) folder for sketches...");
folder = Base.selectFolder(prompt, null, null);
if (folder == null) {
System.exit(0);
}
return folder;
}
/**
* Implements the cross-platform headache of opening URLs
* TODO This code should be replaced by PApplet.link(),
* however that's not a static method (because it requires
* an AppletContext when used as an applet), so it's mildly
* trickier than just removing this method.
*/
static public void openURL(String url) {
try {
platform.openURL(url);
} catch (Exception e) {
showWarning(_("Problem Opening URL"),
I18n.format(_("Could not open the URL\n{0}"), url), e);
}
}
/**
* Used to determine whether to disable the "Show Sketch Folder" option.
* @return true If a means of opening a folder is known to be available.
*/
static protected boolean openFolderAvailable() {
return platform.openFolderAvailable();
}
/**
* Implements the other cross-platform headache of opening
* a folder in the machine's native file browser.
*/
static public void openFolder(File file) {
try {
platform.openFolder(file);
} catch (Exception e) {
showWarning(_("Problem Opening Folder"),
I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e);
}
}
static public File selectFolder(String prompt, File folder, Frame frame) {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(prompt);
if (folder != null) {
fc.setSelectedFile(folder);
}
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returned = fc.showOpenDialog(new JDialog());
if (returned == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
}
return null;
}
/**
* Give this Frame a Processing icon.
*/
static public void setIcon(Frame frame) {
// don't use the low-res icon on Mac OS X; the window should
// already have the right icon from the .app file.
if (Base.isMacOS()) return;
Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE);
frame.setIconImage(image);
}
// someone needs to be slapped
//static KeyStroke closeWindowKeyStroke;
/**
* Return true if the key event was a Ctrl-W or an ESC,
* both indicators to close the window.
* Use as part of a keyPressed() event handler for frames.
*/
/*
static public boolean isCloseWindowEvent(KeyEvent e) {
if (closeWindowKeyStroke == null) {
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers);
}
return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) ||
KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke));
}
*/
/**
* Registers key events for a Ctrl-W and ESC with an ActionListener
* that will take care of disposing the window.
*/
static public void registerWindowCloseKeys(JRootPane root,
ActionListener disposer) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
stroke = KeyStroke.getKeyStroke('W', modifiers);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
static public void showReference(String filename) {
File referenceFolder = Base.getContentFile("reference");
File referenceFile = new File(referenceFolder, filename);
openURL(referenceFile.getAbsolutePath());
}
static public void showGettingStarted() {
if (Base.isMacOS()) {
Base.showReference(_("Guide_MacOSX.html"));
} else if (Base.isWindows()) {
Base.showReference(_("Guide_Windows.html"));
} else {
Base.openURL(_("http:
}
}
static public void showReference() {
showReference(_("index.html"));
}
static public void showEnvironment() {
showReference(_("Guide_Environment.html"));
}
static public void showPlatforms() {
showReference(_("environment") + File.separator + _("platforms.html"));
}
static public void showTroubleshooting() {
showReference(_("Guide_Troubleshooting.html"));
}
static public void showFAQ() {
showReference(_("FAQ.html"));
}
/**
* "No cookie for you" type messages. Nothing fatal or all that
* much of a bummer, but something to notify the user about.
*/
static public void showMessage(String title, String message) {
if (title == null) title = _("Message");
if (commandLine) {
System.out.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Non-fatal error message with optional stack trace side dish.
*/
static public void showWarning(String title, String message, Exception e) {
if (title == null) title = _("Warning");
if (commandLine) {
System.out.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.WARNING_MESSAGE);
}
if (e != null) e.printStackTrace();
}
/**
* Show an error message that's actually fatal to the program.
* This is an error that can't be recovered. Use showWarning()
* for errors that allow P5 to continue running.
*/
static public void showError(String title, String message, Throwable e) {
if (title == null) title = _("Error");
if (commandLine) {
System.err.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.ERROR_MESSAGE);
}
if (e != null) e.printStackTrace();
System.exit(1);
}
// incomplete
static public int showYesNoCancelQuestion(Editor editor, String title,
String primary, String secondary) {
if (!Base.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
return result;
// if (result == JOptionPane.YES_OPTION) {
// } else if (result == JOptionPane.NO_OPTION) {
// return true; // ok to continue
// } else if (result == JOptionPane.CANCEL_OPTION) {
// return false;
// } else {
} else {
// Pane formatting adapted from the Quaqua guide
JOptionPane pane =
new JOptionPane("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost.",
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
"Save", "Cancel", "Don't Save"
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
// on macosx, setting the destructive property places this option
// away from the others at the lefthand side
pane.putClientProperty("Quaqua.OptionPane.destructiveOption",
new Integer(2));
JDialog dialog = pane.createDialog(editor, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) {
return JOptionPane.YES_OPTION;
} else if (result == options[1]) {
return JOptionPane.CANCEL_OPTION;
} else if (result == options[2]) {
return JOptionPane.NO_OPTION;
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
//if (result == JOptionPane.YES_OPTION) {
// } else if (result == JOptionPane.NO_OPTION) {
// return true; // ok to continue
// } else if (result == JOptionPane.CANCEL_OPTION) {
// return false;
// } else {
static public int showYesNoQuestion(Frame editor, String title,
String primary, String secondary) {
if (!Base.isMacOS()) {
return JOptionPane.showConfirmDialog(editor,
"<html><body>" +
"<b>" + primary + "</b>" +
"<br>" + secondary, title,
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
} else {
// Pane formatting adapted from the Quaqua guide
JOptionPane pane =
new JOptionPane("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>" + primary + "</b>" +
"<p>" + secondary + "</p>",
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
"Yes", "No"
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
JDialog dialog = pane.createDialog(editor, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) {
return JOptionPane.YES_OPTION;
} else if (result == options[1]) {
return JOptionPane.NO_OPTION;
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
/**
* Retrieve a path to something in the Processing folder. Eventually this
* may refer to the Contents subfolder of Processing.app, if we bundle things
* up as a single .app file with no additional folders.
*/
// static public String getContentsPath(String filename) {
// String basePath = System.getProperty("user.dir");
// /*
// // do this later, when moving to .app package
// if (PApplet.platform == PConstants.MACOSX) {
// basePath = System.getProperty("processing.contents");
// }
// */
// return basePath + File.separator + filename;
/**
* Get a path for something in the Processing lib folder.
*/
/*
static public String getLibContentsPath(String filename) {
String libPath = getContentsPath("lib/" + filename);
File libDir = new File(libPath);
if (libDir.exists()) {
return libPath;
}
// was looking into making this run from Eclipse, but still too much mess
// libPath = getContents("build/shared/lib/" + what);
// libDir = new File(libPath);
// if (libDir.exists()) {
// return libPath;
// }
return null;
}
*/
static public File getContentFile(String name) {
String path = System.getProperty("user.dir");
// Get a path to somewhere inside the .app folder
if (Base.isMacOS()) {
// <key>javaroot</key>
// <string>$JAVAROOT</string>
String javaroot = System.getProperty("javaroot");
if (javaroot != null) {
path = javaroot;
}
}
File working = new File(path);
return new File(working, name);
}
/**
* Get an image associated with the current color theme.
*/
static public Image getThemeImage(String name, Component who) {
return getLibImage("theme/" + name, who);
}
/**
* Return an Image object from inside the Processing lib folder.
*/
static public Image getLibImage(String name, Component who) {
Image image = null;
Toolkit tk = Toolkit.getDefaultToolkit();
File imageLocation = new File(getContentFile("lib"), name);
image = tk.getImage(imageLocation.getAbsolutePath());
MediaTracker tracker = new MediaTracker(who);
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) { }
return image;
}
/**
* Return an InputStream for a file inside the Processing lib folder.
*/
static public InputStream getLibStream(String filename) throws IOException {
return new FileInputStream(new File(getContentFile("lib"), filename));
}
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
int count = 1;
for (char c : what.toCharArray()) {
if (c == '\n') count++;
}
return count;
}
/**
* Same as PApplet.loadBytes(), however never does gzip decoding.
*/
static public byte[] loadBytesRaw(File file) throws IOException {
int size = (int) file.length();
FileInputStream input = new FileInputStream(file);
byte buffer[] = new byte[size];
int offset = 0;
int bytesRead;
while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) {
offset += bytesRead;
if (bytesRead == 0) break;
}
input.close(); // weren't properly being closed
input = null;
return buffer;
}
/**
* Read from a file with a bunch of attribute/value pairs
* that are separated by = and ignore comments with #.
*/
static public HashMap<String,String> readSettings(File inputFile) {
HashMap<String,String> outgoing = new HashMap<String,String>();
if (!inputFile.exists()) return outgoing; // return empty hash
String lines[] = PApplet.loadStrings(inputFile);
for (int i = 0; i < lines.length; i++) {
int hash = lines[i].indexOf('
String line = (hash == -1) ?
lines[i].trim() : lines[i].substring(0, hash).trim();
if (line.length() == 0) continue;
int equals = line.indexOf('=');
if (equals == -1) {
System.err.println("ignoring illegal line in " + inputFile);
System.err.println(" " + line);
continue;
}
String attr = line.substring(0, equals).trim();
String valu = line.substring(equals + 1).trim();
outgoing.put(attr, valu);
}
return outgoing;
}
static public void copyFile(File sourceFile,
File targetFile) throws IOException {
InputStream from =
new BufferedInputStream(new FileInputStream(sourceFile));
OutputStream to =
new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buffer = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1) {
to.write(buffer, 0, bytesRead);
}
to.flush();
from.close();
from = null;
to.close();
to = null;
targetFile.setLastModified(sourceFile.lastModified());
}
/**
* Grab the contents of a file as a string.
*/
static public String loadFile(File file) throws IOException {
String[] contents = PApplet.loadStrings(file);
if (contents == null) return null;
return PApplet.join(contents, "\n");
}
/**
* Spew the contents of a String object out to a file.
*/
static public void saveFile(String str, File file) throws IOException {
File temp = File.createTempFile(file.getName(), null, file.getParentFile());
PApplet.saveStrings(temp, new String[] { str });
if (file.exists()) {
boolean result = file.delete();
if (!result) {
throw new IOException(
I18n.format(
_("Could not remove old version of {0}"),
file.getAbsolutePath()
)
);
}
}
boolean result = temp.renameTo(file);
if (!result) {
throw new IOException(
I18n.format(
_("Could not replace {0}"),
file.getAbsolutePath()
)
);
}
}
/**
* Copy a folder from one place to another. This ignores all dot files and
* folders found in the source directory, to avoid copying silly .DS_Store
* files and potentially troublesome .svn folders.
*/
static public void copyDir(File sourceDir,
File targetDir) throws IOException {
targetDir.mkdirs();
String files[] = sourceDir.list();
for (int i = 0; i < files.length; i++) {
// Ignore dot files (.DS_Store), dot folders (.svn) while copying
if (files[i].charAt(0) == '.') continue;
//if (files[i].equals(".") || files[i].equals("..")) continue;
File source = new File(sourceDir, files[i]);
File target = new File(targetDir, files[i]);
if (source.isDirectory()) {
//target.mkdirs();
copyDir(source, target);
target.setLastModified(source.lastModified());
} else {
copyFile(source, target);
}
}
}
/**
* Remove all files in a directory and the directory itself.
*/
static public void removeDir(File dir) {
if (dir.exists()) {
removeDescendants(dir);
if (!dir.delete()) {
System.err.println(I18n.format(_("Could not delete {0}"), dir));
}
}
}
/**
* Recursively remove all files within a directory,
* used with removeDir(), or when the contents of a dir
* should be removed, but not the directory itself.
* (i.e. when cleaning temp files from lib/build)
*/
static public void removeDescendants(File dir) {
if (!dir.exists()) return;
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || files[i].equals("..")) continue;
File dead = new File(dir, files[i]);
if (!dead.isDirectory()) {
if (!Preferences.getBoolean("compiler.save_build_files")) {
if (!dead.delete()) {
// temporarily disabled
System.err.println(I18n.format(_("Could not delete {0}"), dead));
}
}
} else {
removeDir(dead);
//dead.delete();
}
}
}
/**
* Calculate the size of the contents of a folder.
* Used to determine whether sketches are empty or not.
* Note that the function calls itself recursively.
*/
static public int calcFolderSize(File folder) {
int size = 0;
String files[] = folder.list();
// null if folder doesn't exist, happens when deleting sketch
if (files == null) return -1;
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || (files[i].equals("..")) ||
files[i].equals(".DS_Store")) continue;
File fella = new File(folder, files[i]);
if (fella.isDirectory()) {
size += calcFolderSize(fella);
} else {
size += (int) fella.length();
}
}
return size;
}
/**
* Recursively creates a list of all files within the specified folder,
* and returns a list of their relative paths.
* Ignores any files/folders prefixed with a dot.
*/
static public String[] listFiles(String path, boolean relative) {
return listFiles(new File(path), relative);
}
static public String[] listFiles(File folder, boolean relative) {
String path = folder.getAbsolutePath();
Vector<String> vector = new Vector<String>();
listFiles(relative ? (path + File.separator) : "", path, vector);
String outgoing[] = new String[vector.size()];
vector.copyInto(outgoing);
return outgoing;
}
static protected void listFiles(String basePath,
String path, Vector<String> vector) {
File folder = new File(path);
String list[] = folder.list();
if (list == null) return;
for (int i = 0; i < list.length; i++) {
if (list[i].charAt(0) == '.') continue;
File file = new File(path, list[i]);
String newPath = file.getAbsolutePath();
if (newPath.startsWith(basePath)) {
newPath = newPath.substring(basePath.length());
}
vector.add(newPath);
if (file.isDirectory()) {
listFiles(basePath, newPath, vector);
}
}
}
public void handleAddLibrary() {
JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home"));
fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip"));
Dimension preferredSize = fileChooser.getPreferredSize();
fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200));
int returnVal = fileChooser.showOpenDialog(activeEditor);
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File sourceFile = fileChooser.getSelectedFile();
File tmpFolder = null;
try {
// unpack ZIP
if (!sourceFile.isDirectory()) {
try {
tmpFolder = FileUtils.createTempFolder();
ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder);
zipDeflater.deflate();
File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs());
if (foldersInTmpFolder.length != 1) {
throw new IOException(_("Zip doesn't contain a library"));
}
sourceFile = foldersInTmpFolder[0];
} catch (IOException e) {
activeEditor.statusError(e);
return;
}
}
// is there a valid library?
File libFolder = sourceFile;
String libName = libFolder.getName();
if (!Sketch.isSanitaryName(libName)) {
String mess = I18n.format(_("The library \"{0}\" cannot be used.\n"
+ "Library names must contain only basic letters and numbers.\n"
+ "(ASCII only and no spaces, and it cannot start with a number)"),
libName);
activeEditor.statusError(mess);
return;
}
// copy folder
File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName());
if (!destinationFolder.mkdir()) {
activeEditor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName()));
return;
}
try {
FileUtils.copy(sourceFile, destinationFolder);
} catch (IOException e) {
activeEditor.statusError(e);
return;
}
activeEditor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu"));
} finally {
// delete zip created temp folder, if exists
FileUtils.recursiveDelete(tmpFolder);
}
}
public static DiscoveryManager getDiscoveryManager() {
return discoveryManager;
}
}
|
// ZAP: 2011/04/08 Changed to support clearview() in HttpPanels
// ZAP: 2011/04/08 Changed to use PopupMenuResendMessage
// ZAP: 2011/07/23 Use new add alert popup
// ZAP: 2011/09/06 Fix alert save plus concurrent mod exceptions
// ZAP: 2011/10/23 Fix add note and manage tags dialogs
// ZAP: 2011/11/20 Set order
// ZAP: 2011/12/21 Added 'show in history' popup
// ZAP: 2012/02/18 Rationalised session handling
// ZAP: 2012/03/03 Moved popups to stdmenus extension
// ZAP: 2012/03/15 Changed the method getResendDialog to pass the configuration key
// to the ManualRequestEditorDialog.
// ZAP: 2012/03/17 Issue 282 Added getAuthor()
// ZAP: 2012/04/24 Added type arguments to generic types, removed unnecessary
// cast and added @Override annotation to all appropriate methods.
// ZAP: 2012/04/28 Added log of exception.
// ZAP: 2012/05/31 Issue 308 NPE in sessionChangedEventHandler in daemon mode
// ZAP: 2012/07/02 Added the method showAlertAddDialog(HttpMessage, int).
// ZAP: 2012/07/29 Issue 43: added sessionScopeChanged event and removed access to some UI elements
// ZAP: 2012/08/01 Issue 332: added support for Modes
// ZAP: 2012/10/08 Issue 391: Performance improvements
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2013/03/03 Issue 547: Deprecate unused classes and methods
// ZAP: 2013/04/14 Issue 588: ExtensionHistory.historyIdToRef should be cleared when changing session
// ZAP: 2013/04/14 Issue 598: Replace/update "old" pop up menu items
// ZAP: 2013/07/14 Issue 725: Clear alert's panel fields
// ZAP: 2013/07/23 Issue 738: Options to hide tabs
// ZAP: 2013/08/07 Also show Authentication messages
// ZAP: 2013/11/16 Issue 869: Differentiate proxied requests from (ZAP) user requests
// ZAP: 2013/12/02 Issue 915: Dynamically filter history based on selection in the sites window
// ZAP: 2014/03/23 Issue 503: Change the footer tabs to display the data
// with tables instead of lists
// ZAP: 2014/03/23 Issue 999: History loaded in wrong order
// ZAP: 2014/04/10 Remove cached history reference when a history reference is removed
// ZAP: 2014/04/10 Issue 1042: Having significant issues opening a previous session
// ZAP: 2014/05/20 Issue 1206: "History" tab is not cleared when a new session is created
// through the API with ZAP in GUI mode
// ZAP: 2014/12/12 Issue 1449: Added help button
// ZAP: 2015/02/09 Issue 1525: Introduce a database interface layer to allow for alternative implementations
// ZAP: 2015/03/03 Added delete(href) method to ensure local map updated
// ZAP: 2015/04/02 Issue 321: Support multiple databases and Issue 1582: Low memory option
// ZAP: 2015/07/16 Issue 1617: ZAP 2.4.0 throws HeadlessExceptions when running in daemon mode on headless machine
// ZAP: 2015/09/16 Issue 1890: ZAP can't completely scan OWASP Benchmark
// ZAP: 2016/01/26 Fixed findbugs warning
// ZAP: 2016/04/12 Listen to alert events to update the table model entries
// ZAP: 2016/04/14 Use View to display the HTTP messages
// ZAP: 2016/04/05 Issue 2458: Fix xlint warning messages
// ZAP: 2016/05/20 Moved purge method to here from PopupMenuPurgeSites
// ZAP: 2016/05/30 Issue 2494: ZAP Proxy is not showing the HTTP CONNECT Request in history tab
// ZAP: 2016/06/20 Removed unnecessary/unused constructor
// ZAP: 2016/06/21 Prevent deadlock between EDT and threads adding messages to the History tab
// ZAP: 2017/01/30 Use HistoryTableModel.
// ZAP: 2017/03/02 Issue 1634 Improve URL export.
// ZAP: 2017/03/28 Issue 3253 Allow URLs to be exported per context.
// ZAP: 2017/04/07 Added getUIName()
// ZAP: 2017/05/01 Issue 3446 - Add ability to export a Site Map via Context Menu.
// ZAP: 2017/05/02 Move alert related code to ExtensionAlert.
// ZAP: 2017/05/03 Register and process events from HistoryReference.
// ZPA: 2017/06/05 Sync HistoryReference cache.
// ZAP: 2017/06/13 Handle notification of notes set and deprecate/remove code no longer needed.
// ZAP: 2017/10/20 Move methods to delete history entries (Issue 3626).
// ZAP: 2017/11/06 Added (un)registerProxy (Issue 3983)
// ZAP: 2017/11/16 Update the table on sessionChanged (Issue 3207).
// ZAP: 2017/11/22 Delete just the history references selected (Issue 4065).
// ZAP: 2018/01/29 Add getter to expose historyReferencesTable of History tab (Issue 4000).
// ZAP: 2018/02/14 Remove unnecessary boxing / unboxing
// ZAP: 2018/03/12 Use the same help page in request editors.
package org.parosproxy.paros.extension.history;
import java.awt.EventQueue;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.apache.commons.collections.map.ReferenceMap;
import org.apache.commons.httpclient.URIException;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.core.proxy.ProxyServer;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.ExtensionHookView;
import org.parosproxy.paros.extension.SessionChangedListener;
import org.parosproxy.paros.extension.manualrequest.ManualRequestEditorDialog;
import org.parosproxy.paros.extension.manualrequest.http.impl.ManualHttpRequestEditorDialog;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.model.HistoryReferenceEventPublisher;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.model.SiteMap;
import org.parosproxy.paros.model.SiteNode;
import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.ZAP;
import org.zaproxy.zap.eventBus.Event;
import org.zaproxy.zap.eventBus.EventConsumer;
import org.zaproxy.zap.extension.alert.AlertEventPublisher;
import org.zaproxy.zap.extension.alert.ExtensionAlert;
import org.zaproxy.zap.extension.help.ExtensionHelp;
import org.zaproxy.zap.extension.history.HistoryFilterPlusDialog;
import org.zaproxy.zap.extension.history.ManageTagsDialog;
import org.zaproxy.zap.extension.history.NotesAddDialog;
import org.zaproxy.zap.extension.history.PopupMenuExportContextURLs;
import org.zaproxy.zap.extension.history.PopupMenuExportSelectedURLs;
import org.zaproxy.zap.extension.history.PopupMenuExportURLs;
import org.zaproxy.zap.extension.history.PopupMenuNote;
import org.zaproxy.zap.extension.history.PopupMenuPurgeHistory;
import org.zaproxy.zap.extension.history.PopupMenuTag;
import org.zaproxy.zap.view.table.HistoryReferencesTable;
public class ExtensionHistory extends ExtensionAdaptor implements SessionChangedListener {
public static final String NAME = "ExtensionHistory";
private static final HistoryTableModel EMPTY_MODEL = new HistoryTableModel();
private LogPanel logPanel = null; // @jve:decl-index=0:visual-constraint="161,134"
private ProxyListenerLog proxyListener = null;
private HistoryTableModel historyTableModel;
// ZAP: added filter plus dialog
private HistoryFilterPlusDialog filterPlusDialog = null;
private PopupMenuPurgeHistory popupMenuPurgeHistory = null;
private ManualRequestEditorDialog resendDialog = null;
private PopupMenuExportMessage popupMenuExportMessage2 = null;
private PopupMenuExportResponse popupMenuExportResponse2 = null;
private PopupMenuTag popupMenuTag = null;
// ZAP: Added Export URLs
private PopupMenuExportURLs popupMenuExportURLs = null;
private PopupMenuExportSelectedURLs popupMenuExportSelectedURLs = null;
private PopupMenuExportContextURLs popupMenuExportContextURLs = null;
// ZAP: Added history notes
private PopupMenuNote popupMenuNote = null;
private NotesAddDialog dialogNotesAdd = null;
private ManageTagsDialog manageTags = null;
private boolean showJustInScope = false;
private boolean linkWithSitesTree;
private String linkWithSitesTreeBaseUri;
// Used to cache hrefs not added into the historyList
@SuppressWarnings("unchecked")
private Map<Integer, HistoryReference> historyIdToRef = Collections.synchronizedMap(new ReferenceMap());
/**
* Flag that indicates whether or not the session is changing. To prevent updating the table more than once when opening a
* session.
*
* @see #sessionAboutToChange(Session)
* @see #sessionScopeChanged(Session)
* @see #sessionChanged(Session)
*/
private boolean sessionChanging;
private Logger logger = Logger.getLogger(ExtensionHistory.class);
public ExtensionHistory() {
super(NAME);
this.setOrder(16);
}
@Override
public String getUIName() {
return Constant.messages.getString("history.name");
}
/**
* This method initializes logPanel
*
* @return org.parosproxy.paros.extension.history.LogPanel
*/
private LogPanel getLogPanel() {
if (logPanel == null) {
logPanel = new LogPanel(getView());
logPanel.setName(Constant.messages.getString("history.panel.title")); // ZAP: i18n
// ZAP: Added History (calendar) icon
logPanel.setIcon(new ImageIcon(ExtensionHistory.class.getResource("/resource/icon/16/025.png"))); // 'calendar' icon
// Dont allow this tab to be hidden
logPanel.setHideable(false);
logPanel.setExtension(this);
logPanel.setModel(historyTableModel);
}
return logPanel;
}
/**
* @deprecated (2.6.0) No longer used/needed.
*/
@Deprecated
public void clearLogPanelDisplayQueue() {
}
public HistoryReference getSelectedHistoryReference () {
return getLogPanel().getSelectedHistoryReference();
}
public List<HistoryReference> getSelectedHistoryReferences () {
return getLogPanel().getSelectedHistoryReferences();
}
@Override
public void init() {
super.init();
historyTableModel = new HistoryTableModel();
EventConsumerImpl eventConsumerImpl = new EventConsumerImpl();
ZAP.getEventBus().registerConsumer(eventConsumerImpl, AlertEventPublisher.getPublisher().getPublisherName());
ZAP.getEventBus().registerConsumer(eventConsumerImpl, HistoryReferenceEventPublisher.getPublisher().getPublisherName());
}
@SuppressWarnings("deprecation")
@Override
public void hook(ExtensionHook extensionHook) {
super.hook(extensionHook);
extensionHook.addSessionListener(this);
extensionHook.addProxyListener(getProxyListenerLog());
extensionHook.addConnectionRequestProxyListener(getProxyListenerLog());
if (getView() != null) {
ExtensionHookView pv = extensionHook.getHookView();
pv.addStatusPanel(getLogPanel());
extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuTag());
// ZAP: Added history notes
extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuNote());
// extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuExportMessage());
// extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuExportResponse());
extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuPurgeHistory());
// same as PopupMenuExport but for File menu
// ZAP: Move 'export' menu items to Report menu
extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportMessage2());
extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportResponse2());
extensionHook.getHookMenu().addReportMenuItem(extensionHook.getHookMenu().getMenuSeparator());
extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportURLs());
extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportSelectedURLs());
extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportContextURLs());
extensionHook.getHookMenu().addReportMenuItem(extensionHook.getHookMenu().getMenuSeparator());
extensionHook.getHookMenu().addPopupMenuItem(createPopupMenuExportURLs());
extensionHook.getHookMenu().addPopupMenuItem(createPopupMenuExportSelectedURLs());
ExtensionHelp.enableHelpKey(this.getLogPanel(), "ui.tabs.history");
}
}
@Override
public void sessionChanged(final Session session) {
sessionChanging = false;
sessionChanged();
}
private ProxyListenerLog getProxyListenerLog() {
if (proxyListener == null) {
proxyListener = new ProxyListenerLog(getModel(), getView(), this);
}
return proxyListener;
}
public void registerProxy(ProxyServer ps) {
ps.addProxyListener(this.getProxyListenerLog());
}
public void unregisterProxy(ProxyServer ps) {
ps.removeProxyListener(this.getProxyListenerLog());
}
public void removeFromHistoryList(final HistoryReference href) {
if (!View.isInitialised() || EventQueue.isDispatchThread()) {
this.historyTableModel.removeEntry(href.getHistoryId());
historyIdToRef.remove(href.getHistoryId());
} else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
removeFromHistoryList(href);
}
});
}
}
public void notifyHistoryItemChanged(HistoryReference href) {
notifyHistoryItemChanged(href.getHistoryId());
}
private void notifyHistoryItemChanged(final int historyId) {
if (!View.isInitialised() || EventQueue.isDispatchThread()) {
this.historyTableModel.refreshEntryRow(historyId);
} else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
notifyHistoryItemChanged(historyId);
}
});
}
}
private void notifyHistoryItemsChanged() {
if (!View.isInitialised() || EventQueue.isDispatchThread()) {
this.historyTableModel.refreshEntryRows();
} else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
notifyHistoryItemsChanged();
}
});
}
}
public void delete(HistoryReference href) {
if (href != null) {
this.historyIdToRef.remove(href.getHistoryId());
href.delete();
}
}
public HistoryReference getHistoryReference (int historyId) {
HistoryReference href = historyTableModel.getHistoryReference(historyId);
if (href != null) {
return href;
}
href = historyIdToRef.get(historyId);
if (href == null) {
try {
href = new HistoryReference(historyId);
if (href.getHistoryType() != HistoryReference.TYPE_SCANNER_TEMPORARY) {
addToMap(href);
}
} catch (Exception e) {
return null;
}
}
return href;
}
public int getLastHistoryId() {
return Model.getSingleton().getDb().getTableHistory().lastIndex();
}
public void addHistory (HttpMessage msg, int type) {
try {
this.addHistory(new HistoryReference(Model.getSingleton().getSession(), type, msg));
} catch (final Exception e) {
logger.error(e.getMessage(), e);
}
}
private void addToMap (HistoryReference historyRef) {
historyIdToRef.put(historyRef.getHistoryId(), historyRef);
}
public void addHistory (HistoryReference historyRef) {
if (Constant.isLowMemoryOptionSet()) {
return;
}
try {
synchronized (historyTableModel) {
if (isHistoryTypeToShow(historyRef.getHistoryType())) {
final String uri = historyRef.getURI().toString();
if (this.showJustInScope && ! getModel().getSession().isInScope(uri)) {
// Not in scope
addToMap(historyRef);
return;
} else if (linkWithSitesTree && linkWithSitesTreeBaseUri != null
&& !uri.startsWith(linkWithSitesTreeBaseUri)) {
// Not under the selected node
addToMap(historyRef);
return;
}
if (getView() != null) {
// Dont do this in daemon mode
HistoryFilterPlusDialog dialog = getFilterPlusDialog();
HistoryFilter historyFilter = dialog.getFilter();
if (historyFilter != null && !historyFilter.matches(historyRef)) {
// Not in filter
addToMap(historyRef);
return;
}
addHistoryInEventQueue(historyRef);
}
}
}
} catch (final Exception e) {
logger.error(e.getMessage(), e);
}
}
/**
* Tells whether or not the messages with the given history type should be shown in the History tab.
*
* @param historyType the history type that will be checked
* @return {@code true} if it should be shown, {@code false} otherwise
*/
private static boolean isHistoryTypeToShow(int historyType) {
return historyType == HistoryReference.TYPE_PROXIED || historyType == HistoryReference.TYPE_ZAP_USER
|| historyType == HistoryReference.TYPE_AUTHENTICATION || historyType == HistoryReference.TYPE_PROXY_CONNECT;
}
private void addHistoryInEventQueue(final HistoryReference ref) {
if (!View.isInitialised() || EventQueue.isDispatchThread()) {
historyTableModel.addHistoryReference(ref);
} else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
addHistoryInEventQueue(ref);
}
});
}
}
private void searchHistory(HistoryFilter historyFilter) {
Session session = getModel().getSession();
synchronized (historyTableModel) {
try {
// ZAP: Added type argument.
List<Integer> list = getModel().getDb().getTableHistory().getHistoryIdsOfHistType(
session.getSessionId(), HistoryReference.TYPE_PROXIED, HistoryReference.TYPE_ZAP_USER,
HistoryReference.TYPE_PROXY_CONNECT);
buildHistory(list, historyFilter);
} catch (DatabaseException e) {
logger.error(e.getMessage(), e);
}
}
}
private void buildHistory(List<Integer> dbList, HistoryFilter historyFilter) {
HistoryReference historyRef = null;
synchronized (historyTableModel) {
if (getView() != null) {
getLogPanel().setModel(EMPTY_MODEL);
}
historyTableModel.clear();
for (int i=0; i<dbList.size(); i++) {
int historyId = dbList.get(i);
try {
SiteNode sn = getModel().getSession().getSiteTree().getSiteNode(historyId);
if (sn != null && sn.getHistoryReference() != null &&
sn.getHistoryReference().getHistoryId() == historyId) {
historyRef = sn.getHistoryReference();
} else {
historyRef = getHistoryReference(historyId);
if (sn != null) {
sn.setHistoryReference(historyRef);
}
}
final String uri = historyRef.getURI().toString();
if (this.showJustInScope && ! getModel().getSession().isInScope(uri)) {
// Not in scope
continue;
} else if (linkWithSitesTree && linkWithSitesTreeBaseUri != null
&& !uri.startsWith(linkWithSitesTreeBaseUri)) {
// Not under the selected node
continue;
}
if (historyFilter != null && !historyFilter.matches(historyRef)) {
// Not in filter
continue;
}
historyRef.loadAlerts();
historyTableModel.addHistoryReference(historyRef);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
if (getView() != null) {
getLogPanel().setModel(historyTableModel);
}
}
}
private HistoryFilterPlusDialog getFilterPlusDialog() {
if (filterPlusDialog == null) {
filterPlusDialog =
new HistoryFilterPlusDialog(getView().getMainFrame(), true);
}
return filterPlusDialog;
}
protected int showFilterPlusDialog() {
HistoryFilterPlusDialog dialog = getFilterPlusDialog();
dialog.setModal(true);
try {
dialog.setAllTags(getModel().getDb().getTableTag().getAllTags());
} catch (DatabaseException e) {
logger.error(e.getMessage(), e);
}
int exit = dialog.showDialog();
int result = 0; // cancel, state unchanged
HistoryFilter historyFilter = dialog.getFilter();
if (exit == JOptionPane.OK_OPTION) {
searchHistory(historyFilter);
logPanel.setFilterStatus(historyFilter);
result = 1; // applied
} else if (exit == JOptionPane.NO_OPTION) {
searchHistory(historyFilter);
logPanel.setFilterStatus(historyFilter);
result = -1; // reset
}
return result;
}
private PopupMenuPurgeHistory getPopupMenuPurgeHistory() {
if (popupMenuPurgeHistory == null) {
popupMenuPurgeHistory = new PopupMenuPurgeHistory(this);
}
return popupMenuPurgeHistory;
}
/**
* This method initializes resendDialog
*
* @return org.parosproxy.paros.extension.history.ResendDialog
*/
public ManualRequestEditorDialog getResendDialog() {
if (resendDialog == null) {
resendDialog = new ManualHttpRequestEditorDialog(true, "resend", "ui.dialogs.manreq");
resendDialog.setTitle(Constant.messages.getString("manReq.dialog.title")); // ZAP: i18n
}
return resendDialog;
}
/**
* This method initializes popupMenuExport1
*
* @return org.parosproxy.paros.extension.history.PopupMenuExport
*/
private PopupMenuExportMessage getPopupMenuExportMessage2() {
if (popupMenuExportMessage2 == null) {
popupMenuExportMessage2 = new PopupMenuExportMessage();
popupMenuExportMessage2.setExtension(this);
}
return popupMenuExportMessage2;
}
/**
* This method initializes popupMenuExportResponse2
*
* @return org.parosproxy.paros.extension.history.PopupMenuExportResponse
*/
private PopupMenuExportResponse getPopupMenuExportResponse2() {
if (popupMenuExportResponse2 == null) {
popupMenuExportResponse2 = new PopupMenuExportResponse();
popupMenuExportResponse2.setExtension(this);
}
return popupMenuExportResponse2;
}
private PopupMenuTag getPopupMenuTag() {
if (popupMenuTag == null) {
popupMenuTag = new PopupMenuTag(this);
}
return popupMenuTag;
}
private PopupMenuNote getPopupMenuNote() {
if (popupMenuNote == null) {
popupMenuNote = new PopupMenuNote(this);
}
return popupMenuNote;
}
private void populateNotesAddDialogAndSetVisible(HistoryReference ref, String note) {
dialogNotesAdd.setNote(note);
dialogNotesAdd.setHistoryRef(ref);
dialogNotesAdd.setVisible(true);
}
public void showNotesAddDialog(HistoryReference ref, String note) {
if (dialogNotesAdd == null) {
dialogNotesAdd = new NotesAddDialog(getView().getMainFrame(), false);
populateNotesAddDialogAndSetVisible(ref, note);
} else if (!dialogNotesAdd.isVisible()) {
populateNotesAddDialogAndSetVisible(ref, note);
}
}
/**
* @deprecated (2.7.0) No longer used/needed.
*/
@Deprecated
public void hideNotesAddDialog() {
}
/**
* @deprecated (2.7.0) Use {@link ExtensionAlert#showAlertAddDialog(HistoryReference)} instead.
* @param ref the {@code HistoryReference} that will have the new alert, if created.
*/
@Deprecated
public void showAlertAddDialog(HistoryReference ref) {
ExtensionAlert extAlert = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
if (extAlert == null) {
return;
}
extAlert.showAlertAddDialog(ref);
}
/**
* Sets the {@code HttpMessage} and the history type of the
* {@code HistoryReference} that will be created if the user creates the
* alert. The current session will be used to create the
* {@code HistoryReference}. The alert created will be added to the newly
* created {@code HistoryReference}.
* <p>
* Should be used when the alert is added to a temporary
* {@code HistoryReference} as the temporary {@code HistoryReference}s are
* deleted when the session is closed.
* </p>
*
* @deprecated (2.7.0) Use {@link ExtensionAlert#showAlertAddDialog(HttpMessage, int)} instead.
* @param httpMessage
* the {@code HttpMessage} that will be used to create the
* {@code HistoryReference}, must not be {@code null}
* @param historyType
* the type of the history reference that will be used to create
* the {@code HistoryReference}
*
* @see Model#getSession()
* @see HistoryReference#HistoryReference(org.parosproxy.paros.model.Session,
* int, HttpMessage)
*/
@Deprecated
public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
ExtensionAlert extAlert = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
if (extAlert == null) {
return;
}
extAlert.showAlertAddDialog(httpMessage, historyType);
}
/**
* @deprecated (2.7.0) Use {@link ExtensionAlert#showAlertEditDialog(Alert)} instead.
* @param alert the alert to edit
*/
@Deprecated
public void showAlertAddDialog(Alert alert) {
ExtensionAlert extAlert = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
if (extAlert == null) {
return;
}
extAlert.showAlertEditDialog(alert);
}
private void populateManageTagsDialogAndSetVisible(HistoryReference ref, List<String> tags) {
try {
manageTags.setAllTags(getModel().getDb().getTableTag().getAllTags());
} catch (DatabaseException e) {
logger.error(e.getMessage(), e);
}
manageTags.setTags(tags);
manageTags.setHistoryRef(ref);
manageTags.setVisible(true);
}
public void showManageTagsDialog(HistoryReference ref, List<String> tags) {
if (manageTags == null) {
manageTags = new ManageTagsDialog(getView().getMainFrame(), false);
populateManageTagsDialogAndSetVisible(ref, tags);
} else if (!manageTags.isVisible()) {
populateManageTagsDialogAndSetVisible(ref, tags);
}
}
private PopupMenuExportURLs getPopupMenuExportURLs() {
if (popupMenuExportURLs == null) {
popupMenuExportURLs = createPopupMenuExportURLs();
}
return popupMenuExportURLs;
}
private PopupMenuExportURLs createPopupMenuExportURLs() {
return new PopupMenuExportURLs(Constant.messages.getString("exportUrls.popup"), this);
}
private PopupMenuExportSelectedURLs getPopupMenuExportSelectedURLs() {
if (popupMenuExportSelectedURLs == null) {
popupMenuExportSelectedURLs = createPopupMenuExportSelectedURLs();
}
return popupMenuExportSelectedURLs;
}
private PopupMenuExportSelectedURLs createPopupMenuExportSelectedURLs() {
return new PopupMenuExportSelectedURLs(Constant.messages.getString("exportUrls.popup.selected"), this);
}
private PopupMenuExportContextURLs getPopupMenuExportContextURLs() {
if (popupMenuExportContextURLs == null) {
popupMenuExportContextURLs = new PopupMenuExportContextURLs(
Constant.messages.getString("context.export.urls.menu"), this);
}
return popupMenuExportContextURLs;
}
public void showInHistory(HistoryReference href) {
this.getLogPanel().display(href);
this.getLogPanel().setTabFocus();
}
@Override
public void sessionAboutToChange(final Session session) {
sessionChanging = true;
if (getView() == null || EventQueue.isDispatchThread()) {
historyTableModel.clear();
historyIdToRef.clear();
if (getView() != null) {
getView().displayMessage(null);
}
} else {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
sessionAboutToChange(session);
}
});
} catch (Exception e) {
// ZAP: Added logging.
logger.error(e.getMessage(), e);
}
}
}
@Override
public String getAuthor() {
return Constant.PAROS_TEAM;
}
public boolean isShowJustInScope() {
return showJustInScope;
}
public void setShowJustInScope(boolean showJustInScope) {
this.showJustInScope = showJustInScope;
if (showJustInScope) {
linkWithSitesTree = false;
}
// Refresh with the next option
searchHistory(getFilterPlusDialog().getFilter());
}
public void purge(SiteMap map, SiteNode node) {
SiteNode child = null;
synchronized (map) {
while (node.getChildCount() > 0) {
try {
child = (SiteNode) node.getChildAt(0);
purge(map, child);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
if (node.isRoot()) {
return;
}
// delete reference in node
removeFromHistoryList(node.getHistoryReference());
ExtensionAlert extAlert =
Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
if (node.getHistoryReference() != null) {
deleteAlertsFromExtensionAlert(extAlert, node.getHistoryReference());
node.getHistoryReference().delete();
map.removeHistoryReference(node.getHistoryReference().getHistoryId());
}
// delete past reference in node
while (node.getPastHistoryReference().size() > 0) {
HistoryReference ref = node.getPastHistoryReference().get(0);
deleteAlertsFromExtensionAlert(extAlert, ref);
removeFromHistoryList(ref);
delete(ref);
node.getPastHistoryReference().remove(0);
map.removeHistoryReference(ref.getHistoryId());
}
map.removeNodeFromParent(node);
}
}
private static void deleteAlertsFromExtensionAlert(ExtensionAlert extAlert, HistoryReference historyReference) {
if (extAlert == null) {
return;
}
extAlert.deleteHistoryReferenceAlerts(historyReference);
}
void setLinkWithSitesTree(boolean linkWithSitesTree, String baseUri) {
this.linkWithSitesTree = linkWithSitesTree;
this.linkWithSitesTreeBaseUri = baseUri;
if (linkWithSitesTree) {
this.showJustInScope = false;
}
searchHistory(getFilterPlusDialog().getFilter());
}
void updateLinkWithSitesTreeBaseUri(String baseUri) {
this.linkWithSitesTreeBaseUri = baseUri;
searchHistory(getFilterPlusDialog().getFilter());
}
@Override
public void sessionScopeChanged(Session session) {
if (sessionChanging) {
return;
}
sessionChanged();
}
private void sessionChanged() {
if (getView() != null) {
searchHistory(getFilterPlusDialog().getFilter());
} else {
searchHistory(null);
}
}
@Override
public void sessionModeChanged(Mode mode) {
// Ignore
}
@Override
public boolean supportsLowMemory() {
return true;
}
/**
* Part of the core set of features that should be supported by all db types
*/
@Override
public boolean supportsDb(String type) {
return true;
}
/**
* @since TODO add version
*/
public HistoryReferencesTable getHistoryReferencesTable() {
return logPanel.getHistoryReferenceTable();
}
private class EventConsumerImpl implements EventConsumer {
@Override
public void eventReceived(Event event) {
switch (event.getEventType()) {
case HistoryReferenceEventPublisher.EVENT_NOTE_SET:
case HistoryReferenceEventPublisher.EVENT_TAG_ADDED:
case HistoryReferenceEventPublisher.EVENT_TAG_REMOVED:
case HistoryReferenceEventPublisher.EVENT_TAGS_SET:
notifyHistoryItemChanged(
Integer.valueOf(event.getParameters().get(HistoryReferenceEventPublisher.FIELD_HISTORY_REFERENCE_ID)));
break;
case AlertEventPublisher.ALERT_ADDED_EVENT:
case AlertEventPublisher.ALERT_CHANGED_EVENT:
case AlertEventPublisher.ALERT_REMOVED_EVENT:
notifyHistoryItemChanged(Integer.valueOf(event.getParameters().get(AlertEventPublisher.HISTORY_REFERENCE_ID)));
break;
case AlertEventPublisher.ALL_ALERTS_REMOVED_EVENT:
notifyHistoryItemsChanged();
break;
default:
}
}
}
/**
* Deletes the given history references from the {@link LogPanel History tab} and the session (database), along with the
* corresponding {@link SiteNode}s and {@link Alert}s.
*
* @param hrefs the history entries to delete.
* @see View#getDefaultDeleteKeyStroke()
* @since 2.7.0
*/
public void purgeHistory(List<HistoryReference> hrefs) {
if (getView() != null && hrefs.size() > 1) {
int result = getView().showConfirmDialog(Constant.messages.getString("history.purge.warning"));
if (result != JOptionPane.YES_OPTION) {
return;
}
}
synchronized (this) {
for (HistoryReference href : hrefs) {
purgeHistory(href);
}
}
}
private void purgeHistory(HistoryReference href) {
if (href == null) {
return;
}
removeFromHistoryList(href);
ExtensionAlert extAlert = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
if (extAlert != null) {
extAlert.deleteHistoryReferenceAlerts(href);
}
SiteNode node = href.getSiteNode();
if (node != null) {
SiteMap map = Model.getSingleton().getSession().getSiteTree();
if (node.getHistoryReference() != href) {
node.getPastHistoryReference().remove(href);
} else if (!node.getPastHistoryReference().isEmpty()) {
node.setHistoryReference(node.getPastHistoryReference().remove(0));
node.getPastHistoryReference().remove(href);
} else {
if (node.isLeaf()) {
SiteNode parent = node.getParent();
map.removeNodeFromParent(node);
purgeTemporaryParents(map, parent);
} else {
try {
node.setHistoryReference(map.createReference(node, href, href.getHttpMessage()));
} catch (URIException | HttpMalformedHeaderException | NullPointerException | DatabaseException e) {
logger.error("Failed to create temporary node:", e);
}
}
}
map.removeHistoryReference(href.getHistoryId());
}
delete(href);
}
private void purgeTemporaryParents(SiteMap map, SiteNode node) {
if (node == null || node.isRoot() || !node.isLeaf()
|| node.getHistoryReference().getHistoryType() != HistoryReference.TYPE_TEMPORARY) {
return;
}
SiteNode parent = node.getParent();
purge(map, node);
purgeTemporaryParents(map, parent);
}
}
|
package betterwithaddons.tileentity;
import betterwithaddons.block.BlockLoom;
import betterwithaddons.block.ModBlocks;
import betterwithaddons.interaction.InteractionCondensedOutputs;
import betterwithmods.api.BWMAPI;
import betterwithmods.api.tile.ICrankable;
import betterwithmods.api.tile.IMechanicalPower;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class TileEntityLoom extends TileEntityBase implements IMechanicalPower, ITickable, ICrankable {
private int spinupProcess = 0;
private int power = 0;
@Override
public int getMechanicalOutput(EnumFacing facing) {
return -1;
}
@Override
public int getMechanicalInput(EnumFacing facing) {
IBlockState state = world.getBlockState(pos);
if(state.getBlock() != getBlock())
return 0;
if(facing != state.getValue(BlockLoom.FACING))
return BWMAPI.IMPLEMENTATION.getPowerOutput(world, pos.offset(facing), facing.getOpposite());
return 0;
}
@Override
public int getMaximumInput(EnumFacing facing) {
return 1;
}
@Override
public int getMinimumInput(EnumFacing facing) {
return 0;
}
@Override
public BlockLoom getBlock() {
return ModBlocks.loom;
}
@Override
public World getBlockWorld() {
return getWorld();
}
@Override
public BlockPos getBlockPos() {
return getPos();
}
@Override
public void writeDataToNBT(NBTTagCompound compound) {
compound.setInteger("ProcessTime",spinupProcess);
}
@Override
public void readDataFromNBT(NBTTagCompound compound) {
spinupProcess = compound.getInteger("ProcessTime");
}
@Override
public void update() {
if(this.getBlockWorld().isRemote)
return;
power = calculateInput();
getBlock().setActive(world,pos,power > 0);
if(power > 0) {
spinupProcess++;
if (spinupProcess > InteractionCondensedOutputs.SPINUP_TIME) {
IBlockState state = world.getBlockState(pos);
if (state.getBlock() == getBlock())
getBlock().spinUpAllAttached(world, pos, state);
spinupProcess = 0;
}
}
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import cc.arduino.Constants;
import cc.arduino.UpdatableBoardsLibsFakeURLsHandler;
import cc.arduino.contributions.*;
import cc.arduino.contributions.libraries.*;
import cc.arduino.contributions.libraries.ui.LibraryManagerUI;
import cc.arduino.contributions.packages.ContributedPlatform;
import cc.arduino.contributions.packages.ContributionInstaller;
import cc.arduino.contributions.packages.ContributionsIndexer;
import cc.arduino.contributions.packages.ui.ContributionManagerUI;
import cc.arduino.files.DeleteFilesOnShutdown;
import cc.arduino.packages.DiscoveryManager;
import cc.arduino.view.Event;
import cc.arduino.view.JMenuUtils;
import cc.arduino.view.SplashScreenHelper;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
import processing.app.helpers.*;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.helpers.filefilters.OnlyFilesWithExtension;
import processing.app.javax.swing.filechooser.FileNameExtensionFilter;
import processing.app.legacy.PApplet;
import processing.app.macosx.ThinkDifferent;
import processing.app.packages.LibraryList;
import processing.app.packages.UserLibrary;
import processing.app.syntax.PdeKeywords;
import processing.app.syntax.SketchTextAreaDefaultInputMap;
import processing.app.tools.MenuScroller;
import processing.app.tools.ZipDeflater;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.Timer;
import java.util.function.Predicate;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static processing.app.I18n.tr;
/**
* The base class for the main processing application.
* Primary role of this class is for platform identification and
* general interaction with the system (launching URLs, loading
* files and images, etc) that comes from that.
*/
public class Base {
public static final Predicate<UserLibrary> CONTRIBUTED = library -> library.getTypes() == null || library.getTypes().isEmpty() || library.getTypes().contains("Contributed");
public static final Predicate<UserLibrary> RETIRED = library -> library.getTypes() != null && library.getTypes().contains("Retired");
private static final int RECENT_SKETCHES_MAX_SIZE = 5;
private static boolean commandLine;
public static volatile Base INSTANCE;
public static SplashScreenHelper splashScreenHelper = new SplashScreenHelper(SplashScreen.getSplashScreen());
public static Map<String, Object> FIND_DIALOG_STATE = new HashMap<String, Object>();
private final ContributionInstaller contributionInstaller;
private final LibraryInstaller libraryInstaller;
private ContributionsSelfCheck contributionsSelfCheck;
// set to true after the first time the menu is built.
// so that the errors while building don't show up again.
boolean builtOnce;
// classpath for all known libraries for p5
// (both those in the p5/libs folder and those with lib subfolders
// found in the sketchbook)
static public String librariesClassPath;
// Location for untitled items
static File untitledFolder;
// p5 icon for the window
// static Image icon;
// int editorCount;
List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>());
Editor activeEditor;
// these menus are shared so that the board and serial port selections
// are the same for all windows (since the board and serial port that are
// actually used are determined by the preferences, which are shared)
private List<JMenu> boardsCustomMenus;
private List<JMenuItem> programmerMenus;
private PdeKeywords pdeKeywords;
private final List<JMenuItem> recentSketchesMenuItems;
static public void main(String args[]) throws Exception {
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
System.setProperty("java.net.useSystemProxies", "true");
splashScreenHelper.splashText(tr("Loading configuration..."));
if (OSUtils.isMacOS()) {
ThinkDifferent.init();
}
try {
guardedMain(args);
} catch (Throwable e) {
e.printStackTrace(System.err);
System.exit(255);
}
}
static public void guardedMain(String args[]) throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread(DeleteFilesOnShutdown.INSTANCE));
BaseNoGui.initLogger();
initLogger();
BaseNoGui.initPlatform();
BaseNoGui.getPlatform().init();
BaseNoGui.initPortableFolder();
BaseNoGui.initParameters(args);
System.setProperty("swing.aatext", PreferencesData.get("editor.antialias", "true"));
BaseNoGui.initVersion();
// if (System.getProperty("mrj.version") != null) {
// //String jv = System.getProperty("java.version");
// String ov = System.getProperty("os.version");
// if (ov.startsWith("10.5")) {
// System.setProperty("apple.laf.useScreenMenuBar", "true");
/*
commandLine = false;
if (args.length >= 2) {
if (args[0].startsWith("--")) {
commandLine = true;
}
}
if (PApplet.javaVersion < 1.5f) {
//System.err.println("no way man");
Base.showError("Need to install Java 1.5",
"This version of Processing requires \n" +
"Java 1.5 or later to run properly.\n" +
"Please visit java.com to upgrade.", null);
}
*/
// // Set the look and feel before opening the window
// try {
// platform.setLookAndFeel();
// } catch (Exception e) {
// System.err.println("Non-fatal error while setting the Look & Feel.");
// System.err.println("The error message follows, however Processing should run fine.");
// System.err.println(e.getMessage());
// //e.printStackTrace();
// Use native popups so they don't look so crappy on osx
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
// Don't put anything above this line that might make GUI,
// because the platform has to be inited properly first.
// Make sure a full JDK is installed
//initRequirements();
// setup the theme coloring fun
Theme.init();
// Set the look and feel before opening the window
try {
BaseNoGui.getPlatform().setLookAndFeel();
} catch (Exception e) {
// ignore
}
// Create a location for untitled sketches
untitledFolder = FileUtils.createTempFolder("untitled" + new Random().nextInt(Integer.MAX_VALUE), ".tmp");
DeleteFilesOnShutdown.add(untitledFolder);
INSTANCE = new Base(args);
}
static public void initLogger() {
Handler consoleHandler = new ConsoleLogger();
consoleHandler.setLevel(Level.ALL);
consoleHandler.setFormatter(new LogFormatter("%1$tl:%1$tM:%1$tS [%4$7s] %2$s: %5$s%n"));
Logger globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(consoleHandler.getLevel());
// Remove default
Handler[] handlers = globalLogger.getHandlers();
for(Handler handler : handlers) {
globalLogger.removeHandler(handler);
}
Logger root = Logger.getLogger("");
handlers = root.getHandlers();
for(Handler handler : handlers) {
root.removeHandler(handler);
}
globalLogger.addHandler(consoleHandler);
Logger.getLogger("cc.arduino.packages.autocomplete").setParent(globalLogger);
Logger.getLogger("br.com.criativasoft.cpluslibparser").setParent(globalLogger);
Logger.getLogger(Base.class.getPackage().getName()).setParent(globalLogger);
}
static protected void setCommandLine() {
commandLine = true;
}
static protected boolean isCommandLine() {
return commandLine;
}
// Returns a File object for the given pathname. If the pathname
// is not absolute, it is interpreted relative to the current
// directory when starting the IDE (which is not the same as the
// current working directory!).
static public File absoluteFile(String path) {
return BaseNoGui.absoluteFile(path);
}
public Base(String[] args) throws Exception {
BaseNoGui.notifier = new GUIUserNotifier(this);
this.recentSketchesMenuItems = new LinkedList<JMenuItem>();
CommandlineParser parser = new CommandlineParser(args);
parser.parseArgumentsPhase1();
BaseNoGui.checkInstallationFolder();
String sketchbookPath = BaseNoGui.getSketchbookPath();
// If no path is set, get the default sketchbook folder for this platform
if (sketchbookPath == null) {
File defaultFolder = getDefaultSketchbookFolderOrPromptForIt();
if (BaseNoGui.getPortableFolder() != null)
PreferencesData.set("sketchbook.path", BaseNoGui.getPortableSketchbookFolder());
else
PreferencesData.set("sketchbook.path", defaultFolder.getAbsolutePath());
if (!defaultFolder.exists()) {
defaultFolder.mkdirs();
}
}
splashScreenHelper.splashText(tr("Initializing packages..."));
BaseNoGui.initPackages();
splashScreenHelper.splashText(tr("Preparing boards..."));
rebuildBoardsMenu();
rebuildProgrammerMenu();
// Setup board-dependent variables.
onBoardOrPortChange();
this.pdeKeywords = new PdeKeywords();
this.pdeKeywords.reload();
contributionInstaller = new ContributionInstaller(BaseNoGui.indexer, BaseNoGui.getPlatform(), new GPGDetachedSignatureVerifier());
libraryInstaller = new LibraryInstaller(BaseNoGui.librariesIndexer, BaseNoGui.getPlatform());
parser.parseArgumentsPhase2();
for (String path : parser.getFilenames()) {
// Correctly resolve relative paths
File file = absoluteFile(path);
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
if (OSUtils.isWindows()) {
try {
file = file.getCanonicalFile();
} catch (IOException e) {
e.printStackTrace();
}
}
boolean showEditor = parser.isGuiMode();
if (!parser.isForceSavePrefs())
PreferencesData.setDoSave(showEditor);
if (handleOpen(file, nextEditorLocation(), showEditor, false) == null) {
String mess = I18n.format(tr("Failed to open sketch: \"{0}\""), path);
// Open failure is fatal in upload/verify mode
if (parser.isVerifyOrUploadMode())
showError(null, mess, 2);
else
showWarning(null, mess, null);
}
}
// Save the preferences. For GUI mode, this happens in the quit
// handler, but for other modes we should also make sure to save
// them.
PreferencesData.save();
if (parser.isInstallBoard()) {
ContributionsIndexer indexer = new ContributionsIndexer(BaseNoGui.getSettingsFolder(), BaseNoGui.getPlatform(), new GPGDetachedSignatureVerifier());
ProgressListener progressListener = new ConsoleProgressListener();
List<String> downloadedPackageIndexFiles = contributionInstaller.updateIndex(progressListener);
contributionInstaller.deleteUnknownFiles(downloadedPackageIndexFiles);
indexer.parseIndex();
indexer.syncWithFilesystem(BaseNoGui.getHardwareFolder());
String[] boardToInstallParts = parser.getBoardToInstall().split(":");
ContributedPlatform selected = null;
if (boardToInstallParts.length == 3) {
selected = indexer.getIndex().findPlatform(boardToInstallParts[0], boardToInstallParts[1], VersionHelper.valueOf(boardToInstallParts[2]).toString());
} else if (boardToInstallParts.length == 2) {
List<ContributedPlatform> platformsByName = indexer.getIndex().findPlatforms(boardToInstallParts[0], boardToInstallParts[1]);
Collections.sort(platformsByName, new DownloadableContributionVersionComparator());
if (!platformsByName.isEmpty()) {
selected = platformsByName.get(platformsByName.size() - 1);
}
}
if (selected == null) {
System.out.println(tr("Selected board is not available"));
System.exit(1);
}
ContributedPlatform installed = indexer.getInstalled(boardToInstallParts[0], boardToInstallParts[1]);
if (!selected.isReadOnly()) {
contributionInstaller.install(selected, progressListener);
}
if (installed != null && !installed.isReadOnly()) {
contributionInstaller.remove(installed);
}
System.exit(0);
} else if (parser.isInstallLibrary()) {
LibrariesIndexer indexer = new LibrariesIndexer(BaseNoGui.getSettingsFolder(), new ContributionsIndexer(BaseNoGui.getSettingsFolder(), BaseNoGui.getPlatform(), new GPGDetachedSignatureVerifier()));
ProgressListener progressListener = new ConsoleProgressListener();
indexer.parseIndex();
BaseNoGui.onBoardOrPortChange();
indexer.setSketchbookLibrariesFolder(BaseNoGui.getSketchbookLibrariesFolder());
indexer.setLibrariesFolders(BaseNoGui.getLibrariesPath());
libraryInstaller.updateIndex(progressListener);
for (String library : parser.getLibraryToInstall().split(",")) {
String[] libraryToInstallParts = library.split(":");
ContributedLibrary selected = null;
if (libraryToInstallParts.length == 2) {
selected = indexer.getIndex().find(libraryToInstallParts[0], VersionHelper.valueOf(libraryToInstallParts[1]).toString());
} else if (libraryToInstallParts.length == 1) {
List<ContributedLibrary> librariesByName = indexer.getIndex().find(libraryToInstallParts[0]);
Collections.sort(librariesByName, new DownloadableContributionVersionComparator());
if (!librariesByName.isEmpty()) {
selected = librariesByName.get(librariesByName.size() - 1);
}
}
if (selected == null) {
System.out.println(tr("Selected library is not available"));
System.exit(1);
}
ContributedLibrary installed = indexer.getIndex().getInstalled(libraryToInstallParts[0]);
if (selected.isReadOnly()) {
libraryInstaller.remove(installed, progressListener);
} else {
libraryInstaller.install(selected, installed, progressListener);
}
}
System.exit(0);
} else if (parser.isVerifyOrUploadMode()) {
splashScreenHelper.close();
// Set verbosity for command line build
PreferencesData.set("build.verbose", "" + parser.isDoVerboseBuild());
PreferencesData.set("upload.verbose", "" + parser.isDoVerboseUpload());
PreferencesData.set("runtime.preserve.temp.files", Boolean.toString(parser.isPreserveTempFiles()));
// Make sure these verbosity preferences are only for the
// current session
PreferencesData.setDoSave(false);
Editor editor = editors.get(0);
if (parser.isUploadMode()) {
splashScreenHelper.splashText(tr("Verifying and uploading..."));
editor.exportHandler.run();
} else {
splashScreenHelper.splashText(tr("Verifying..."));
editor.runHandler.run();
}
// Error during build or upload
if (editor.status.isErr()) {
System.exit(1);
}
// No errors exit gracefully
System.exit(0);
} else if (parser.isGuiMode()) {
splashScreenHelper.splashText(tr("Starting..."));
installKeyboardInputMap();
// Check if there were previously opened sketches to be restored
restoreSketches();
// Create a new empty window (will be replaced with any files to be opened)
if (editors.isEmpty()) {
handleNew();
}
new Thread(new BuiltInCoreIsNewerCheck(this)).start();
// Check for updates
if (PreferencesData.getBoolean("update.check")) {
new UpdateCheck(this);
contributionsSelfCheck = new ContributionsSelfCheck(this, new UpdatableBoardsLibsFakeURLsHandler(this), BaseNoGui.indexer, contributionInstaller, BaseNoGui.librariesIndexer, libraryInstaller);
new Timer(false).schedule(contributionsSelfCheck, Constants.BOARDS_LIBS_UPDATABLE_CHECK_START_PERIOD);
}
} else if (parser.isNoOpMode()) {
// Do nothing (intended for only changing preferences)
System.exit(0);
} else if (parser.isGetPrefMode()) {
BaseNoGui.dumpPrefs(parser);
}
}
private void installKeyboardInputMap() {
UIManager.put("RSyntaxTextAreaUI.inputMap", new SketchTextAreaDefaultInputMap());
}
/**
* Post-constructor setup for the editor area. Loads the last
* sketch that was used (if any), and restores other Editor settings.
* The complement to "storePreferences", this is called when the
* application is first launched.
*
* @throws Exception
*/
protected boolean restoreSketches() throws Exception {
// figure out window placement
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
boolean windowPositionValid = true;
if (PreferencesData.get("last.screen.height") != null) {
// if screen size has changed, the window coordinates no longer
// make sense, so don't use them unless they're identical
int screenW = PreferencesData.getInteger("last.screen.width");
int screenH = PreferencesData.getInteger("last.screen.height");
if ((screen.width != screenW) || (screen.height != screenH)) {
windowPositionValid = false;
}
/*
int windowX = Preferences.getInteger("last.window.x");
int windowY = Preferences.getInteger("last.window.y");
if ((windowX < 0) || (windowY < 0) ||
(windowX > screenW) || (windowY > screenH)) {
windowPositionValid = false;
}
*/
} else {
windowPositionValid = false;
}
// Iterate through all sketches that were open last time p5 was running.
// If !windowPositionValid, then ignore the coordinates found for each.
// Save the sketch path and window placement for each open sketch
int count = PreferencesData.getInteger("last.sketch.count");
int opened = 0;
for (int i = count - 1; i >= 0; i
String path = PreferencesData.get("last.sketch" + i + ".path");
if (path == null) {
continue;
}
if (BaseNoGui.getPortableFolder() != null) {
File absolute = new File(BaseNoGui.getPortableFolder(), path);
try {
path = absolute.getCanonicalPath();
} catch (IOException e) {
// path unchanged.
}
}
int[] location;
if (windowPositionValid) {
String locationStr = PreferencesData.get("last.sketch" + i + ".location");
location = PApplet.parseInt(PApplet.split(locationStr, ','));
} else {
location = nextEditorLocation();
}
// If file did not exist, null will be returned for the Editor
if (handleOpen(new File(path), location, nextEditorLocation(), true, false, false) != null) {
opened++;
}
}
return (opened > 0);
}
/**
* Store list of sketches that are currently open.
* Called when the application is quitting and documents are still open.
*/
protected void storeSketches() {
// Save the width and height of the screen
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
PreferencesData.setInteger("last.screen.width", screen.width);
PreferencesData.setInteger("last.screen.height", screen.height);
String untitledPath = untitledFolder.getAbsolutePath();
// Save the sketch path and window placement for each open sketch
LinkedList<Editor> reverseEditors = new LinkedList<Editor>(editors);
Collections.reverse(reverseEditors);
int index = 0;
for (Editor editor : reverseEditors) {
String path = editor.getSketch().getMainFilePath();
// In case of a crash, save untitled sketches if they contain changes.
// (Added this for release 0158, may not be a good idea.)
if (path.startsWith(untitledPath) && !editor.getSketch().isModified()) {
continue;
}
if (BaseNoGui.getPortableFolder() != null) {
path = FileUtils.relativePath(BaseNoGui.getPortableFolder().toString(), path);
if (path == null) {
continue;
}
}
PreferencesData.set("last.sketch" + index + ".path", path);
int[] location = editor.getPlacement();
String locationStr = PApplet.join(PApplet.str(location), ",");
PreferencesData.set("last.sketch" + index + ".location", locationStr);
index++;
}
PreferencesData.setInteger("last.sketch.count", index);
}
protected void storeRecentSketches(Sketch sketch) {
if (sketch.isUntitled()) {
return;
}
Set<String> sketches = new LinkedHashSet<String>();
sketches.add(sketch.getMainFilePath());
sketches.addAll(PreferencesData.getCollection("recent.sketches"));
PreferencesData.setCollection("recent.sketches", sketches);
}
protected void removeRecentSketchPath(String path) {
Collection<String> sketches = new LinkedList<String>(PreferencesData.getCollection("recent.sketches"));
sketches.remove(path);
PreferencesData.setCollection("recent.sketches", sketches);
}
// Because of variations in native windowing systems, no guarantees about
// changes to the focused and active Windows can be made. Developers must
// never assume that this Window is the focused or active Window until this
// Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event.
protected void handleActivated(Editor whichEditor) {
activeEditor = whichEditor;
activeEditor.rebuildRecentSketchesMenu();
if (PreferencesData.getBoolean("editor.external")) {
try {
activeEditor.getSketch().load(true);
} catch (IOException e) {
// noop
}
}
// set the current window to be the console that's getting output
EditorConsole.setCurrentEditorConsole(activeEditor.console);
}
protected int[] nextEditorLocation() {
int defaultWidth = PreferencesData.getInteger("editor.window.width.default");
int defaultHeight = PreferencesData.getInteger("editor.window.height.default");
if (activeEditor == null) {
Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
// If no current active editor, use default placement
return new int[]{
(screen.width - defaultWidth) / 2,
(screen.height - defaultHeight) / 2,
defaultWidth, defaultHeight, 0
};
} else {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// With a currently active editor, open the new window
// using the same dimensions, but offset slightly.
synchronized (editors) {
final int OVER = 50;
// In release 0160, don't
//location = activeEditor.getPlacement();
Editor lastOpened = activeEditor;
int[] location = lastOpened.getPlacement();
// Just in case the bounds for that window are bad
location[0] += OVER;
location[1] += OVER;
if (location[0] == OVER ||
location[2] == OVER ||
location[0] + location[2] > screen.width ||
location[1] + location[3] > screen.height) {
// Warp the next window to a randomish location on screen.
return new int[]{
(int) (Math.random() * (screen.width - defaultWidth)),
(int) (Math.random() * (screen.height - defaultHeight)),
defaultWidth, defaultHeight, 0
};
}
return location;
}
}
}
boolean breakTime = false;
String[] months = {
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"
};
protected File createNewUntitled() throws IOException {
File newbieDir = null;
String newbieName = null;
// In 0126, untitled sketches will begin in the temp folder,
// and then moved to a new location because Save will default to Save As.
File sketchbookDir = BaseNoGui.getSketchbookFolder();
File newbieParentDir = untitledFolder;
// Use a generic name like sketch_031008a, the date plus a char
int index = 0;
//SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
//SimpleDateFormat formatter = new SimpleDateFormat("MMMdd");
//String purty = formatter.format(new Date()).toLowerCase();
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31
int month = cal.get(Calendar.MONTH); // 0..11
String purty = months[month] + PApplet.nf(day, 2);
do {
if (index == 26*26) {
// In 0166, avoid running past zz by sending people outdoors.
if (!breakTime) {
showWarning(tr("Time for a Break"),
tr("You've reached the limit for auto naming of new sketches\n" +
"for the day. How about going for a walk instead?"), null);
breakTime = true;
} else {
showWarning(tr("Sunshine"),
tr("No really, time for some fresh air for you."), null);
}
return null;
}
int multiples = index / 26;
if(multiples > 0){
newbieName = ((char) ('a' + (multiples-1))) + "" + ((char) ('a' + (index % 26))) + "";
}else{
newbieName = ((char) ('a' + index)) + "";
}
newbieName = "sketch_" + purty + newbieName;
newbieDir = new File(newbieParentDir, newbieName);
index++;
// Make sure it's not in the temp folder *and* it's not in the sketchbook
} while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists());
// Make the directory for the new sketch
newbieDir.mkdirs();
// Make an empty pde file
File newbieFile = new File(newbieDir, newbieName + ".ino");
if (!newbieFile.createNewFile()) {
throw new IOException();
}
FileUtils.copyFile(new File(getContentFile("examples"), "01.Basics" + File.separator + "BareMinimum" + File.separator + "BareMinimum.ino"), newbieFile);
return newbieFile;
}
/**
* Create a new untitled document in a new sketch window.
*
* @throws Exception
*/
public void handleNew() throws Exception {
try {
File file = createNewUntitled();
if (file != null) {
handleOpen(file, true);
}
} catch (IOException e) {
if (activeEditor != null) {
activeEditor.statusError(e);
}
}
}
/**
* Replace the sketch in the current window with a new untitled document.
*/
public void handleNewReplace() {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
// Actually replace things
handleNewReplaceImpl();
}
protected void handleNewReplaceImpl() {
try {
File file = createNewUntitled();
if (file != null) {
activeEditor.handleOpenInternal(file);
activeEditor.untitled = true;
}
} catch (IOException e) {
activeEditor.statusError(e);
}
}
public void handleOpenReplace(File file) {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
boolean loaded = activeEditor.handleOpenInternal(file);
if (!loaded) {
// replace the document without checking if that's ok
handleNewReplaceImpl();
}
}
/**
* Prompt for a sketch to open, and open it in a new window.
*
* @throws Exception
*/
public void handleOpenPrompt() throws Exception {
// get the frontmost window frame for placing file dialog
FileDialog fd = new FileDialog(activeEditor, tr("Open an Arduino sketch..."), FileDialog.LOAD);
File lastFolder = new File(PreferencesData.get("last.folder", BaseNoGui.getSketchbookFolder().getAbsolutePath()));
if (lastFolder.exists() && lastFolder.isFile()) {
lastFolder = lastFolder.getParentFile();
}
fd.setDirectory(lastFolder.getAbsolutePath());
// Only show .pde files as eligible bachelors
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".ino")
|| name.toLowerCase().endsWith(".pde");
}
});
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// User canceled selection
if (filename == null) return;
File inputFile = new File(directory, filename);
PreferencesData.set("last.folder", inputFile.getAbsolutePath());
handleOpen(inputFile);
}
/**
* Open a sketch in a new window.
*
* @param file File to open
* @return the Editor object, so that properties (like 'untitled')
* can be set by the caller
* @throws Exception
*/
public Editor handleOpen(File file) throws Exception {
return handleOpen(file, false);
}
public Editor handleOpen(File file, boolean untitled) throws Exception {
return handleOpen(file, nextEditorLocation(), true, untitled);
}
protected Editor handleOpen(File file, int[] location, boolean showEditor, boolean untitled) throws Exception {
return handleOpen(file, location, location, showEditor, true, untitled);
}
protected Editor handleOpen(File file, int[] storedLocation, int[] defaultLocation, boolean showEditor, boolean storeOpenedSketches, boolean untitled) throws Exception {
if (!file.exists()) return null;
// Cycle through open windows to make sure that it's not already open.
String path = file.getAbsolutePath();
for (Editor editor : editors) {
if (editor.getSketch().getMainFilePath().equals(path)) {
editor.toFront();
return editor;
}
}
Editor editor = new Editor(this, file, storedLocation, defaultLocation, BaseNoGui.getPlatform());
// Make sure that the sketch actually loaded
if (editor.getSketch() == null) {
return null; // Just walk away quietly
}
editor.untitled = untitled;
editors.add(editor);
if (storeOpenedSketches) {
// Store information on who's open and running
// (in case there's a crash or something that can't be recovered)
storeSketches();
storeRecentSketches(editor.getSketch());
rebuildRecentSketchesMenuItems();
PreferencesData.save();
}
// now that we're ready, show the window
// (don't do earlier, cuz we might move it based on a window being closed)
if (showEditor) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.setVisible(true);
}
});
}
return editor;
}
protected void rebuildRecentSketchesMenuItems() {
Set<File> recentSketches = new LinkedHashSet<File>() {
@Override
public boolean add(File file) {
if (size() >= RECENT_SKETCHES_MAX_SIZE) {
return false;
}
return super.add(file);
}
};
for (String path : PreferencesData.getCollection("recent.sketches")) {
File file = new File(path);
if (file.exists()) {
recentSketches.add(file);
}
}
recentSketchesMenuItems.clear();
for (final File recentSketch : recentSketches) {
JMenuItem recentSketchMenuItem = new JMenuItem(recentSketch.getParentFile().getName());
recentSketchMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
try {
handleOpen(recentSketch);
} catch (Exception e) {
e.printStackTrace();
}
}
});
recentSketchesMenuItems.add(recentSketchMenuItem);
}
}
/**
* Close a sketch as specified by its editor window.
*
* @param editor Editor object of the sketch to be closed.
* @return true if succeeded in closing, false if canceled.
*/
public boolean handleClose(Editor editor) {
// Check if modified
// boolean immediate = editors.size() == 1;
if (!editor.checkModified()) {
return false;
}
// Close the running window, avoid window boogers with multiple sketches
editor.internalCloseRunner();
if (editors.size() == 1) {
// This will store the sketch count as zero
storeSketches();
editors.remove(editor);
try {
Editor.serialMonitor.close();
} catch (Exception e) {
//ignore
}
rebuildRecentSketchesMenuItems();
// Save out the current prefs state
PreferencesData.save();
// Since this wasn't an actual Quit event, call System.exit()
System.exit(0);
} else {
// More than one editor window open,
// proceed with closing the current window.
editor.setVisible(false);
editor.dispose();
// for (int i = 0; i < editorCount; i++) {
// if (editor == editors[i]) {
// for (int j = i; j < editorCount-1; j++) {
// editors[j] = editors[j+1];
// editorCount--;
// // Set to null so that garbage collection occurs
// editors[editorCount] = null;
editors.remove(editor);
}
return true;
}
/**
* Handler for File → Quit.
*
* @return false if canceled, true otherwise.
*/
public boolean handleQuit() {
// If quit is canceled, this will be replaced anyway
// by a later handleQuit() that is not canceled.
storeSketches();
try {
Editor.serialMonitor.close();
} catch (Exception e) {
// ignore
}
if (handleQuitEach()) {
// make sure running sketches close before quitting
for (Editor editor : editors) {
editor.internalCloseRunner();
}
// Save out the current prefs state
PreferencesData.save();
if (!OSUtils.isMacOS()) {
// If this was fired from the menu or an AppleEvent (the Finder),
// then Mac OS X will send the terminate signal itself.
System.exit(0);
}
return true;
}
return false;
}
/**
* Attempt to close each open sketch in preparation for quitting.
*
* @return false if canceled along the way
*/
protected boolean handleQuitEach() {
for (Editor editor : editors) {
if (!editor.checkModified()) {
return false;
}
}
return true;
}
/**
* Asynchronous version of menu rebuild to be used on save and rename
* to prevent the interface from locking up until the menus are done.
*/
public void rebuildSketchbookMenus() {
//System.out.println("async enter");
//new Exception().printStackTrace();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//System.out.println("starting rebuild");
rebuildSketchbookMenu(Editor.sketchbookMenu);
rebuildToolbarMenu(Editor.toolbarMenu);
//System.out.println("done with rebuild");
}
});
//System.out.println("async exit");
}
protected void rebuildToolbarMenu(JMenu menu) {
JMenuItem item;
menu.removeAll();
// Add the single "Open" item
item = Editor.newJMenuItem(tr("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
menu.add(item);
menu.addSeparator();
// Add a list of all sketches and subfolders
boolean sketches = addSketches(menu, BaseNoGui.getSketchbookFolder());
if (sketches) menu.addSeparator();
// Add each of the subfolders of examples directly to the menu
boolean found = addSketches(menu, BaseNoGui.getExamplesFolder());
if (found) menu.addSeparator();
}
protected void rebuildSketchbookMenu(JMenu menu) {
menu.removeAll();
addSketches(menu, BaseNoGui.getSketchbookFolder());
JMenu librariesMenu = JMenuUtils.findSubMenuWithLabel(menu, "libraries");
if (librariesMenu != null) {
menu.remove(librariesMenu);
}
JMenu hardwareMenu = JMenuUtils.findSubMenuWithLabel(menu, "hardware");
if (hardwareMenu != null) {
menu.remove(hardwareMenu);
}
}
public LibraryList getIDELibs() {
LibraryList installedLibraries = new LibraryList(BaseNoGui.librariesIndexer.getInstalledLibraries());
List<UserLibrary> libs = installedLibraries.stream()
.filter(CONTRIBUTED.negate())
.filter(RETIRED.negate())
.collect(Collectors.toList());
return new LibraryList(libs);
}
public LibraryList getIDERetiredLibs() {
LibraryList installedLibraries = new LibraryList(BaseNoGui.librariesIndexer.getInstalledLibraries());
List<UserLibrary> libs = installedLibraries.stream()
.filter(RETIRED)
.collect(Collectors.toList());
return new LibraryList(libs);
}
public LibraryList getUserLibs() {
LibraryList installedLibraries = new LibraryList(BaseNoGui.librariesIndexer.getInstalledLibraries());
List<UserLibrary> libs = installedLibraries.stream().filter(CONTRIBUTED).collect(Collectors.toList());
return new LibraryList(libs);
}
private List<ContributedLibrary> getSortedLibraries() {
List<ContributedLibrary> installedLibraries = new LinkedList<ContributedLibrary>(BaseNoGui.librariesIndexer.getInstalledLibraries());
Collections.sort(installedLibraries, new LibraryByTypeComparator());
Collections.sort(installedLibraries, new LibraryOfSameTypeComparator());
return installedLibraries;
}
public void rebuildImportMenu(JMenu importMenu) {
if (importMenu == null)
return;
importMenu.removeAll();
JMenuItem menu = new JMenuItem(tr("Manage Libraries..."));
menu.addActionListener(e -> openLibraryManager(""));
importMenu.add(menu);
importMenu.addSeparator();
JMenuItem addLibraryMenuItem = new JMenuItem(tr("Add .ZIP Library..."));
addLibraryMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.this.handleAddLibrary();
Base.this.onBoardOrPortChange();
Base.this.rebuildImportMenu(Editor.importMenu);
Base.this.rebuildExamplesMenu(Editor.examplesMenu);
}
});
importMenu.add(addLibraryMenuItem);
importMenu.addSeparator();
// Split between user supplied libraries and IDE libraries
TargetPlatform targetPlatform = BaseNoGui.getTargetPlatform();
if (targetPlatform != null) {
List<ContributedLibrary> libs = getSortedLibraries();
String lastLibType = null;
for (ContributedLibrary lib : libs) {
if (lastLibType == null || !lastLibType.equals(lib.getTypes().get(0))) {
if (lastLibType != null) {
importMenu.addSeparator();
}
lastLibType = lib.getTypes().get(0);
JMenuItem platformItem = new JMenuItem(I18n.format(tr("{0} libraries"), lastLibType));
platformItem.setEnabled(false);
importMenu.add(platformItem);
}
AbstractAction action = new AbstractAction(lib.getName()) {
public void actionPerformed(ActionEvent event) {
UserLibrary l = (UserLibrary) getValue("library");
try {
activeEditor.getSketch().importLibrary(l);
} catch (IOException e) {
showWarning(tr("Error"), I18n.format("Unable to list header files in {0}", l.getSrcFolder()), e);
}
}
};
action.putValue("library", lib);
// Add new element at the bottom
JMenuItem item = new JMenuItem(action);
item.putClientProperty("library", lib);
importMenu.add(item);
}
}
}
public void rebuildExamplesMenu(JMenu menu) {
if (menu == null) {
return;
}
menu.removeAll();
// Add examples from distribution "example" folder
JMenuItem label = new JMenuItem(tr("Built-in Examples"));
label.setEnabled(false);
menu.add(label);
boolean found = addSketches(menu, BaseNoGui.getExamplesFolder());
if (found) {
menu.addSeparator();
}
// Add examples from libraries
LibraryList ideLibs = getIDELibs();
ideLibs.sort();
if (!ideLibs.isEmpty()) {
label = new JMenuItem(tr("Examples from Libraries"));
label.setEnabled(false);
menu.add(label);
}
for (UserLibrary lib : ideLibs) {
addSketchesSubmenu(menu, lib);
}
LibraryList retiredIdeLibs = getIDERetiredLibs();
retiredIdeLibs.sort();
if (!retiredIdeLibs.isEmpty()) {
JMenu retired = new JMenu(tr("RETIRED"));
menu.add(retired);
for (UserLibrary lib : retiredIdeLibs) {
addSketchesSubmenu(retired, lib);
}
}
LibraryList userLibs = getUserLibs();
if (userLibs.size() > 0) {
menu.addSeparator();
userLibs.sort();
label = new JMenuItem(tr("Examples from Custom Libraries"));
label.setEnabled(false);
menu.add(label);
for (UserLibrary lib : userLibs) {
addSketchesSubmenu(menu, lib);
}
}
}
private static String priorPlatformFolder;
public void onBoardOrPortChange() {
BaseNoGui.onBoardOrPortChange();
// reload keywords when package/platform changes
TargetPlatform tp = BaseNoGui.getTargetPlatform();
if (tp != null) {
String platformFolder = tp.getFolder().getAbsolutePath();
if (priorPlatformFolder == null || !priorPlatformFolder.equals(platformFolder)) {
pdeKeywords = new PdeKeywords();
pdeKeywords.reload();
priorPlatformFolder = platformFolder;
for (Editor editor : editors) {
editor.updateKeywords(pdeKeywords);
}
}
}
// Update editors status bar
for (Editor editor : editors) {
editor.onBoardOrPortChange();
}
}
public void openLibraryManager(String dropdownItem) {
if (contributionsSelfCheck != null) {
contributionsSelfCheck.cancel();
}
@SuppressWarnings("serial")
LibraryManagerUI managerUI = new LibraryManagerUI(activeEditor, BaseNoGui.librariesIndexer, libraryInstaller) {
@Override
protected void onIndexesUpdated() throws Exception {
BaseNoGui.initPackages();
rebuildBoardsMenu();
rebuildProgrammerMenu();
onBoardOrPortChange();
updateUI();
if (StringUtils.isNotEmpty(dropdownItem)) {
selectDropdownItemByClassName(dropdownItem);
}
}
};
managerUI.setLocationRelativeTo(activeEditor);
managerUI.updateUI();
managerUI.setVisible(true);
// Manager dialog is modal, waits here until closed
//handleAddLibrary();
onBoardOrPortChange();
rebuildImportMenu(Editor.importMenu);
rebuildExamplesMenu(Editor.examplesMenu);
}
public void openBoardsManager(final String filterText, String dropdownItem) throws Exception {
if (contributionsSelfCheck != null) {
contributionsSelfCheck.cancel();
}
@SuppressWarnings("serial")
ContributionManagerUI managerUI = new ContributionManagerUI(activeEditor, BaseNoGui.indexer, contributionInstaller) {
@Override
protected void onIndexesUpdated() throws Exception {
BaseNoGui.initPackages();
rebuildBoardsMenu();
rebuildProgrammerMenu();
updateUI();
if (StringUtils.isNotEmpty(dropdownItem)) {
selectDropdownItemByClassName(dropdownItem);
}
if (StringUtils.isNotEmpty(filterText)) {
setFilterText(filterText);
}
}
};
managerUI.setLocationRelativeTo(activeEditor);
managerUI.updateUI();
managerUI.setVisible(true);
// Installer dialog is modal, waits here until closed
// Reload all boards (that may have been installed/updated/removed)
BaseNoGui.initPackages();
rebuildBoardsMenu();
rebuildProgrammerMenu();
onBoardOrPortChange();
}
public void rebuildBoardsMenu() throws Exception {
boardsCustomMenus = new LinkedList<>();
// The first custom menu is the "Board" selection submenu
JMenu boardMenu = new JMenu(tr("Board"));
boardMenu.putClientProperty("removeOnWindowDeactivation", true);
MenuScroller.setScrollerFor(boardMenu);
boardMenu.add(new JMenuItem(new AbstractAction(tr("Boards Manager...")) {
public void actionPerformed(ActionEvent actionevent) {
String filterText = "";
String dropdownItem = "";
if (actionevent instanceof Event) {
filterText = ((Event) actionevent).getPayload().get("filterText").toString();
dropdownItem = ((Event) actionevent).getPayload().get("dropdownItem").toString();
}
try {
openBoardsManager(filterText, dropdownItem);
} catch (Exception e) {
//TODO show error
e.printStackTrace();
}
}
}));
boardsCustomMenus.add(boardMenu);
// If there are no platforms installed we are done
if (BaseNoGui.packages.size() == 0)
return;
// Separate "Install boards..." command from installed boards
boardMenu.add(new JSeparator());
// Generate custom menus for all platforms
Set<String> customMenusTitles = new HashSet<String>();
for (TargetPackage targetPackage : BaseNoGui.packages.values()) {
for (TargetPlatform targetPlatform : targetPackage.platforms()) {
customMenusTitles.addAll(targetPlatform.getCustomMenus().values());
}
}
for (String customMenuTitle : customMenusTitles) {
JMenu customMenu = new JMenu(tr(customMenuTitle));
customMenu.putClientProperty("removeOnWindowDeactivation", true);
boardsCustomMenus.add(customMenu);
}
List<JMenuItem> menuItemsToClickAfterStartup = new LinkedList<JMenuItem>();
ButtonGroup boardsButtonGroup = new ButtonGroup();
Map<String, ButtonGroup> buttonGroupsMap = new HashMap<String, ButtonGroup>();
// Cycle through all packages
boolean first = true;
for (TargetPackage targetPackage : BaseNoGui.packages.values()) {
// For every package cycle through all platform
for (TargetPlatform targetPlatform : targetPackage.platforms()) {
// Add a separator from the previous platform
if (!first)
boardMenu.add(new JSeparator());
first = false;
// Add a title for each platform
String platformLabel = targetPlatform.getPreferences().get("name");
if (platformLabel != null && !targetPlatform.getBoards().isEmpty()) {
JMenuItem menuLabel = new JMenuItem(tr(platformLabel));
menuLabel.setEnabled(false);
boardMenu.add(menuLabel);
}
// Cycle through all boards of this platform
for (TargetBoard board : targetPlatform.getBoards().values()) {
JMenuItem item = createBoardMenusAndCustomMenus(boardsCustomMenus, menuItemsToClickAfterStartup,
buttonGroupsMap,
board, targetPlatform, targetPackage);
boardMenu.add(item);
boardsButtonGroup.add(item);
}
}
}
if (menuItemsToClickAfterStartup.isEmpty()) {
menuItemsToClickAfterStartup.add(selectFirstEnabledMenuItem(boardMenu));
}
for (JMenuItem menuItemToClick : menuItemsToClickAfterStartup) {
menuItemToClick.setSelected(true);
menuItemToClick.getAction().actionPerformed(new ActionEvent(this, -1, ""));
}
}
private JRadioButtonMenuItem createBoardMenusAndCustomMenus(
final List<JMenu> boardsCustomMenus, List<JMenuItem> menuItemsToClickAfterStartup,
Map<String, ButtonGroup> buttonGroupsMap,
TargetBoard board, TargetPlatform targetPlatform, TargetPackage targetPackage)
throws Exception {
String selPackage = PreferencesData.get("target_package");
String selPlatform = PreferencesData.get("target_platform");
String selBoard = PreferencesData.get("board");
String boardId = board.getId();
String packageName = targetPackage.getId();
String platformName = targetPlatform.getId();
// Setup a menu item for the current board
@SuppressWarnings("serial")
Action action = new AbstractAction(board.getName()) {
public void actionPerformed(ActionEvent actionevent) {
BaseNoGui.selectBoard((TargetBoard) getValue("b"));
filterVisibilityOfSubsequentBoardMenus(boardsCustomMenus, (TargetBoard) getValue("b"), 1);
onBoardOrPortChange();
rebuildImportMenu(Editor.importMenu);
rebuildExamplesMenu(Editor.examplesMenu);
}
};
action.putValue("b", board);
JRadioButtonMenuItem item = new JRadioButtonMenuItem(action);
if (selBoard.equals(boardId) && selPackage.equals(packageName)
&& selPlatform.equals(platformName)) {
menuItemsToClickAfterStartup.add(item);
}
PreferencesMap customMenus = targetPlatform.getCustomMenus();
for (final String menuId : customMenus.keySet()) {
String title = customMenus.get(menuId);
JMenu menu = getBoardCustomMenu(tr(title));
if (board.hasMenu(menuId)) {
PreferencesMap boardCustomMenu = board.getMenuLabels(menuId);
for (String customMenuOption : boardCustomMenu.keySet()) {
@SuppressWarnings("serial")
Action subAction = new AbstractAction(tr(boardCustomMenu.get(customMenuOption))) {
public void actionPerformed(ActionEvent e) {
PreferencesData.set("custom_" + menuId, ((TargetBoard) getValue("board")).getId() + "_" + getValue("custom_menu_option"));
onBoardOrPortChange();
}
};
subAction.putValue("board", board);
subAction.putValue("custom_menu_option", customMenuOption);
if (!buttonGroupsMap.containsKey(menuId)) {
buttonGroupsMap.put(menuId, new ButtonGroup());
}
JRadioButtonMenuItem subItem = new JRadioButtonMenuItem(subAction);
menu.add(subItem);
buttonGroupsMap.get(menuId).add(subItem);
String selectedCustomMenuEntry = PreferencesData.get("custom_" + menuId);
if (selBoard.equals(boardId) && (boardId + "_" + customMenuOption).equals(selectedCustomMenuEntry)) {
menuItemsToClickAfterStartup.add(subItem);
}
}
}
}
return item;
}
private void filterVisibilityOfSubsequentBoardMenus(List<JMenu> boardsCustomMenus, TargetBoard board,
int fromIndex) {
for (int i = fromIndex; i < boardsCustomMenus.size(); i++) {
JMenu menu = boardsCustomMenus.get(i);
for (int m = 0; m < menu.getItemCount(); m++) {
JMenuItem menuItem = menu.getItem(m);
menuItem.setVisible(menuItem.getAction().getValue("board").equals(board));
}
menu.setVisible(ifThereAreVisibleItemsOn(menu));
if (menu.isVisible()) {
JMenuItem visibleSelectedOrFirstMenuItem = selectVisibleSelectedOrFirstMenuItem(menu);
if (!visibleSelectedOrFirstMenuItem.isSelected()) {
visibleSelectedOrFirstMenuItem.setSelected(true);
visibleSelectedOrFirstMenuItem.getAction().actionPerformed(null);
}
}
}
}
private static boolean ifThereAreVisibleItemsOn(JMenu menu) {
for (int i = 0; i < menu.getItemCount(); i++) {
if (menu.getItem(i).isVisible()) {
return true;
}
}
return false;
}
private JMenu getBoardCustomMenu(String label) throws Exception {
for (JMenu menu : boardsCustomMenus) {
if (label.equals(menu.getText())) {
return menu;
}
}
throw new Exception("Custom menu not found!");
}
public List<JMenuItem> getProgrammerMenus() {
return programmerMenus;
}
private static JMenuItem selectVisibleSelectedOrFirstMenuItem(JMenu menu) {
JMenuItem firstVisible = null;
for (int i = 0; i < menu.getItemCount(); i++) {
JMenuItem item = menu.getItem(i);
if (item != null && item.isVisible()) {
if (item.isSelected()) {
return item;
}
if (firstVisible == null) {
firstVisible = item;
}
}
}
if (firstVisible != null) {
return firstVisible;
}
throw new IllegalStateException("Menu has no enabled items");
}
private static JMenuItem selectFirstEnabledMenuItem(JMenu menu) {
for (int i = 1; i < menu.getItemCount(); i++) {
JMenuItem item = menu.getItem(i);
if (item != null && item.isEnabled()) {
return item;
}
}
throw new IllegalStateException("Menu has no enabled items");
}
public void rebuildProgrammerMenu() {
programmerMenus = new LinkedList<>();
ButtonGroup group = new ButtonGroup();
for (TargetPackage targetPackage : BaseNoGui.packages.values()) {
for (TargetPlatform targetPlatform : targetPackage.platforms()) {
for (String programmer : targetPlatform.getProgrammers().keySet()) {
String id = targetPackage.getId() + ":" + programmer;
@SuppressWarnings("serial")
AbstractAction action = new AbstractAction(targetPlatform.getProgrammer(programmer).get("name")) {
public void actionPerformed(ActionEvent actionevent) {
PreferencesData.set("programmer", "" + getValue("id"));
}
};
action.putValue("id", id);
JMenuItem item = new JRadioButtonMenuItem(action);
if (PreferencesData.get("programmer").equals(id)) {
item.setSelected(true);
}
group.add(item);
programmerMenus.add(item);
}
}
}
}
/**
* Scan a folder recursively, and add any sketches found to the menu
* specified. Set the openReplaces parameter to true when opening the sketch
* should replace the sketch in the current window, or false when the
* sketch should open in a new window.
*/
protected boolean addSketches(JMenu menu, File folder) {
if (folder == null)
return false;
if (!folder.isDirectory()) return false;
File[] files = folder.listFiles();
// If a bad folder or unreadable or whatever, this will come back null
if (files == null) return false;
// Alphabetize files, since it's not always alpha order
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File file, File file2) {
return file.getName().compareToIgnoreCase(file2.getName());
}
});
boolean ifound = false;
for (File subfolder : files) {
if (FileUtils.isSCCSOrHiddenFile(subfolder)) {
continue;
}
if (!subfolder.isDirectory()) continue;
if (addSketchesSubmenu(menu, subfolder.getName(), subfolder)) {
ifound = true;
}
}
return ifound;
}
private boolean addSketchesSubmenu(JMenu menu, UserLibrary lib) {
return addSketchesSubmenu(menu, lib.getName(), lib.getInstalledFolder());
}
private boolean addSketchesSubmenu(JMenu menu, String name, File folder) {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = e.getActionCommand();
File file = new File(path);
if (file.exists()) {
try {
handleOpen(file);
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
showWarning(tr("Sketch Does Not Exist"),
tr("The selected sketch no longer exists.\n"
+ "You may need to restart Arduino to update\n"
+ "the sketchbook menu."), null);
}
}
};
File entry = new File(folder, name + ".ino");
if (!entry.exists() && (new File(folder, name + ".pde")).exists())
entry = new File(folder, name + ".pde");
// if a .pde file of the same prefix as the folder exists..
if (entry.exists()) {
if (!BaseNoGui.isSanitaryName(name)) {
if (!builtOnce) {
String complaining = I18n
.format(
tr("The sketch \"{0}\" cannot be used.\n"
+ "Sketch names must contain only basic letters and numbers\n"
+ "(ASCII-only with no spaces, "
+ "and it cannot start with a number).\n"
+ "To get rid of this message, remove the sketch from\n"
+ "{1}"), name, entry.getAbsolutePath());
showMessage(tr("Ignoring sketch with bad name"), complaining);
}
return false;
}
JMenuItem item = new JMenuItem(name);
item.addActionListener(listener);
item.setActionCommand(entry.getAbsolutePath());
menu.add(item);
return true;
}
// don't create an extra menu level for a folder named "examples"
if (folder.getName().equals("examples"))
return addSketches(menu, folder);
// not a sketch folder, but maybe a subfolder containing sketches
JMenu submenu = new JMenu(name);
boolean found = addSketches(submenu, folder);
if (found) {
menu.add(submenu);
MenuScroller.setScrollerFor(submenu);
}
return found;
}
protected void addLibraries(JMenu menu, LibraryList libs) throws IOException {
LibraryList list = new LibraryList(libs);
list.sort();
for (UserLibrary lib : list) {
@SuppressWarnings("serial")
AbstractAction action = new AbstractAction(lib.getName()) {
public void actionPerformed(ActionEvent event) {
UserLibrary l = (UserLibrary) getValue("library");
try {
activeEditor.getSketch().importLibrary(l);
} catch (IOException e) {
showWarning(tr("Error"), I18n.format("Unable to list header files in {0}", l.getSrcFolder()), e);
}
}
};
action.putValue("library", lib);
// Add new element at the bottom
JMenuItem item = new JMenuItem(action);
item.putClientProperty("library", lib);
menu.add(item);
// XXX: DAM: should recurse here so that library folders can be nested
}
}
/**
* Given a folder, return a list of the header files in that folder (but not
* the header files in its sub-folders, as those should be included from
* within the header files at the top-level).
*/
static public String[] headerListFromIncludePath(File path) throws IOException {
String[] list = path.list(new OnlyFilesWithExtension(".h"));
if (list == null) {
throw new IOException();
}
return list;
}
/**
* Show the About box.
*/
@SuppressWarnings("serial")
public void handleAbout() {
final Image image = getLibImage("about.png", activeEditor);
final Window window = new Window(activeEditor) {
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setFont(new Font("SansSerif", Font.PLAIN, 11));
g.setColor(Color.black);
g.drawString("Arduino " + BaseNoGui.VERSION_NAME_LONG, 28, 16);
if (BaseNoGui.teensyduino_version != null) {
FontMetrics m = g.getFontMetrics(g.getFont());
String td = "Teensyduino " + BaseNoGui.teensyduino_version;
g.drawString(td, 448 - m.stringWidth(td), 16);
}
}
};
window.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
window.dispose();
}
});
int w = image.getWidth(activeEditor);
int h = image.getHeight(activeEditor);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
window.setBounds((screen.width - w) / 2, (screen.height - h) / 2, w, h);
window.setLocationRelativeTo(activeEditor);
window.setVisible(true);
}
/**
* Show the Preferences window.
*/
public void handlePrefs() {
cc.arduino.view.preferences.Preferences dialog = new cc.arduino.view.preferences.Preferences(activeEditor, this);
if (activeEditor != null) {
dialog.setLocationRelativeTo(activeEditor);
}
dialog.setVisible(true);
}
// XXX: Remove this method and make librariesIndexer non-static
static public LibraryList getLibraries() {
return BaseNoGui.librariesIndexer.getInstalledLibraries();
}
public List<JMenu> getBoardsCustomMenus() {
return boardsCustomMenus;
}
public File getDefaultSketchbookFolderOrPromptForIt() {
File sketchbookFolder = BaseNoGui.getDefaultSketchbookFolder();
if (sketchbookFolder == null) {
sketchbookFolder = promptSketchbookLocation();
}
// create the folder if it doesn't exist already
boolean result = true;
if (!sketchbookFolder.exists()) {
result = sketchbookFolder.mkdirs();
}
if (!result) {
showError(tr("You forgot your sketchbook"),
tr("Arduino cannot run because it could not\n" +
"create a folder to store your sketchbook."), null);
}
return sketchbookFolder;
}
/**
* Check for a new sketchbook location.
*/
static protected File promptSketchbookLocation() {
File folder = null;
folder = new File(System.getProperty("user.home"), "sketchbook");
if (!folder.exists()) {
folder.mkdirs();
return folder;
}
String prompt = tr("Select (or create new) folder for sketches...");
folder = selectFolder(prompt, null, null);
if (folder == null) {
System.exit(0);
}
return folder;
}
/**
* Implements the cross-platform headache of opening URLs
* TODO This code should be replaced by PApplet.link(),
* however that's not a static method (because it requires
* an AppletContext when used as an applet), so it's mildly
* trickier than just removing this method.
*/
static public void openURL(String url) {
try {
BaseNoGui.getPlatform().openURL(url);
} catch (Exception e) {
showWarning(tr("Problem Opening URL"),
I18n.format(tr("Could not open the URL\n{0}"), url), e);
}
}
/**
* Used to determine whether to disable the "Show Sketch Folder" option.
*
* @return true If a means of opening a folder is known to be available.
*/
static protected boolean openFolderAvailable() {
return BaseNoGui.getPlatform().openFolderAvailable();
}
/**
* Implements the other cross-platform headache of opening
* a folder in the machine's native file browser.
*/
static public void openFolder(File file) {
try {
BaseNoGui.getPlatform().openFolder(file);
} catch (Exception e) {
showWarning(tr("Problem Opening Folder"),
I18n.format(tr("Could not open the folder\n{0}"), file.getAbsolutePath()), e);
}
}
static public File selectFolder(String prompt, File folder, Component parent) {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(prompt);
if (folder != null) {
fc.setSelectedFile(folder);
}
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returned = fc.showOpenDialog(parent);
if (returned == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
}
return null;
}
/**
* Give this Frame a Processing icon.
*/
static public void setIcon(Frame frame) {
// don't use the low-res icon on Mac OS X; the window should
// already have the right icon from the .app file.
if (OSUtils.isMacOS()) return;
// don't use the low-res icon on Linux
if (OSUtils.isLinux()){
Image image = Toolkit.getDefaultToolkit().createImage(BaseNoGui.getContentFile("/lib/arduino.png").getAbsolutePath());
frame.setIconImage(image);
return;
}
Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE);
frame.setIconImage(image);
}
/**
* Registers key events for a Ctrl-W and ESC with an ActionListener
* that will take care of disposing the window.
*/
static public void registerWindowCloseKeys(JRootPane root,
ActionListener disposer) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
stroke = KeyStroke.getKeyStroke('W', modifiers);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
static public void showReference(String filename) {
showReference("reference/www.arduino.cc/en", filename);
}
static public void showReference(String prefix, String filename) {
File referenceFolder = getContentFile(prefix);
File referenceFile = new File(referenceFolder, filename);
if (!referenceFile.exists())
referenceFile = new File(referenceFolder, filename + ".html");
if(referenceFile.exists()){
openURL(referenceFile.getAbsolutePath());
}else{
showWarning(tr("Problem Opening URL"), I18n.format(tr("Could not open the URL\n{0}"), referenceFile), null);
}
}
public static void showEdisonGettingStarted() {
showReference("reference/Edison_help_files", "ArduinoIDE_guide_edison");
}
static public void showArduinoGettingStarted() {
if (OSUtils.isMacOS()) {
showReference("Guide/MacOSX");
} else if (OSUtils.isWindows()) {
showReference("Guide/Windows");
} else {
openURL("http:
}
}
static public void showReference() {
showReference("Reference/HomePage");
}
static public void showEnvironment() {
showReference("Guide/Environment");
}
static public void showTroubleshooting() {
showReference("Guide/Troubleshooting");
}
static public void showFAQ() {
showReference("Main/FAQ");
}
/**
* "No cookie for you" type messages. Nothing fatal or all that
* much of a bummer, but something to notify the user about.
*/
static public void showMessage(String title, String message) {
BaseNoGui.showMessage(title, message);
}
/**
* Non-fatal error message with optional stack trace side dish.
*/
static public void showWarning(String title, String message, Exception e) {
BaseNoGui.showWarning(title, message, e);
}
static public void showError(String title, String message, Throwable e) {
showError(title, message, e, 1);
}
static public void showError(String title, String message, int exit_code) {
showError(title, message, null, exit_code);
}
/**
* Show an error message that's actually fatal to the program.
* This is an error that can't be recovered. Use showWarning()
* for errors that allow P5 to continue running.
*/
static public void showError(String title, String message, Throwable e, int exit_code) {
BaseNoGui.showError(title, message, e, exit_code);
}
static public File getContentFile(String name) {
return BaseNoGui.getContentFile(name);
}
/**
* Get an image associated with the current color theme.
*/
static public Image getThemeImage(String name, Component who) {
return getLibImage("theme/" + name, who);
}
/**
* Return an Image object from inside the Processing lib folder.
*/
static public Image getLibImage(String name, Component who) {
Toolkit tk = Toolkit.getDefaultToolkit();
File imageLocation = new File(getContentFile("lib"), name);
Image image = tk.getImage(imageLocation.getAbsolutePath());
MediaTracker tracker = new MediaTracker(who);
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
}
return image;
}
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
return BaseNoGui.countLines(what);
}
/**
* Same as PApplet.loadBytes(), however never does gzip decoding.
*/
static public byte[] loadBytesRaw(File file) throws IOException {
int size = (int) file.length();
FileInputStream input = null;
try {
input = new FileInputStream(file);
byte buffer[] = new byte[size];
int offset = 0;
int bytesRead;
while ((bytesRead = input.read(buffer, offset, size - offset)) != -1) {
offset += bytesRead;
if (bytesRead == 0) break;
}
return buffer;
} finally {
IOUtils.closeQuietly(input);
}
}
/**
* Read from a file with a bunch of attribute/value pairs
* that are separated by = and ignore comments with #.
*/
static public HashMap<String, String> readSettings(File inputFile) {
HashMap<String, String> outgoing = new HashMap<String, String>();
if (!inputFile.exists()) return outgoing; // return empty hash
String lines[] = PApplet.loadStrings(inputFile);
for (int i = 0; i < lines.length; i++) {
int hash = lines[i].indexOf('
String line = (hash == -1) ?
lines[i].trim() : lines[i].substring(0, hash).trim();
if (line.length() == 0) continue;
int equals = line.indexOf('=');
if (equals == -1) {
System.err.println("ignoring illegal line in " + inputFile);
System.err.println(" " + line);
continue;
}
String attr = line.substring(0, equals).trim();
String valu = line.substring(equals + 1).trim();
outgoing.put(attr, valu);
}
return outgoing;
}
static public void copyFile(File sourceFile,
File targetFile) throws IOException {
InputStream from = null;
OutputStream to = null;
try {
from = new BufferedInputStream(new FileInputStream(sourceFile));
to = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buffer = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1) {
to.write(buffer, 0, bytesRead);
}
to.flush();
} finally {
IOUtils.closeQuietly(from);
IOUtils.closeQuietly(to);
}
targetFile.setLastModified(sourceFile.lastModified());
}
/**
* Grab the contents of a file as a string.
*/
static public String loadFile(File file) throws IOException {
return BaseNoGui.loadFile(file);
}
/**
* Spew the contents of a String object out to a file.
*/
static public void saveFile(String str, File file) throws IOException {
BaseNoGui.saveFile(str, file);
}
/**
* Copy a folder from one place to another. This ignores all dot files and
* folders found in the source directory, to avoid copying silly .DS_Store
* files and potentially troublesome .svn folders.
*/
static public void copyDir(File sourceDir,
File targetDir) throws IOException {
targetDir.mkdirs();
String files[] = sourceDir.list();
if (files == null) {
throw new IOException("Unable to list files from " + sourceDir);
}
for (String file : files) {
// Ignore dot files (.DS_Store), dot folders (.svn) while copying
if (file.charAt(0) == '.') continue;
//if (files[i].equals(".") || files[i].equals("..")) continue;
File source = new File(sourceDir, file);
File target = new File(targetDir, file);
if (source.isDirectory()) {
//target.mkdirs();
copyDir(source, target);
target.setLastModified(source.lastModified());
} else {
copyFile(source, target);
}
}
}
/**
* Remove all files in a directory and the directory itself.
*/
static public void removeDir(File dir) {
BaseNoGui.removeDir(dir);
}
/**
* Recursively remove all files within a directory,
* used with removeDir(), or when the contents of a dir
* should be removed, but not the directory itself.
* (i.e. when cleaning temp files from lib/build)
*/
static public void removeDescendants(File dir) {
BaseNoGui.removeDescendants(dir);
}
/**
* Calculate the size of the contents of a folder.
* Used to determine whether sketches are empty or not.
* Note that the function calls itself recursively.
*/
static public int calcFolderSize(File folder) {
int size = 0;
String files[] = folder.list();
// null if folder doesn't exist, happens when deleting sketch
if (files == null) return -1;
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || (files[i].equals("..")) ||
files[i].equals(".DS_Store")) continue;
File fella = new File(folder, files[i]);
if (fella.isDirectory()) {
size += calcFolderSize(fella);
} else {
size += (int) fella.length();
}
}
return size;
}
/**
* Recursively creates a list of all files within the specified folder,
* and returns a list of their relative paths.
* Ignores any files/folders prefixed with a dot.
*/
static public String[] listFiles(String path, boolean relative) {
return listFiles(new File(path), relative);
}
static public String[] listFiles(File folder, boolean relative) {
String path = folder.getAbsolutePath();
Vector<String> vector = new Vector<String>();
listFiles(relative ? (path + File.separator) : "", path, vector);
String outgoing[] = new String[vector.size()];
vector.copyInto(outgoing);
return outgoing;
}
static protected void listFiles(String basePath,
String path, Vector<String> vector) {
File folder = new File(path);
String list[] = folder.list();
if (list == null) return;
for (int i = 0; i < list.length; i++) {
if (list[i].charAt(0) == '.') continue;
File file = new File(path, list[i]);
String newPath = file.getAbsolutePath();
if (newPath.startsWith(basePath)) {
newPath = newPath.substring(basePath.length());
}
vector.add(newPath);
if (file.isDirectory()) {
listFiles(basePath, newPath, vector);
}
}
}
public void handleAddLibrary() {
JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home"));
fileChooser.setDialogTitle(tr("Select a zip file or a folder containing the library you'd like to add"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.setFileFilter(new FileNameExtensionFilter(tr("ZIP files or folders"), "zip"));
Dimension preferredSize = fileChooser.getPreferredSize();
fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200));
int returnVal = fileChooser.showOpenDialog(activeEditor);
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File sourceFile = fileChooser.getSelectedFile();
File tmpFolder = null;
try {
// unpack ZIP
if (!sourceFile.isDirectory()) {
try {
tmpFolder = FileUtils.createTempFolder();
ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder);
zipDeflater.deflate();
File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs());
if (foldersInTmpFolder.length != 1) {
throw new IOException(tr("Zip doesn't contain a library"));
}
sourceFile = foldersInTmpFolder[0];
} catch (IOException e) {
activeEditor.statusError(e);
return;
}
}
File libFolder = sourceFile;
if (FileUtils.isSubDirectory(new File(PreferencesData.get("sketchbook.path")), libFolder)) {
activeEditor.statusError(tr("A subfolder of your sketchbook is not a valid library"));
return;
}
if (FileUtils.isSubDirectory(libFolder, new File(PreferencesData.get("sketchbook.path")))) {
activeEditor.statusError(tr("You can't import a folder that contains your sketchbook"));
return;
}
String libName = libFolder.getName();
if (!BaseNoGui.isSanitaryName(libName)) {
String mess = I18n.format(tr("The library \"{0}\" cannot be used.\n"
+ "Library names must contain only basic letters and numbers.\n"
+ "(ASCII only and no spaces, and it cannot start with a number)"),
libName);
activeEditor.statusError(mess);
return;
}
String[] headers;
if (new File(libFolder, "library.properties").exists()) {
headers = BaseNoGui.headerListFromIncludePath(UserLibrary.create(libFolder).getSrcFolder());
} else {
headers = BaseNoGui.headerListFromIncludePath(libFolder);
}
if (headers.length == 0) {
activeEditor.statusError(tr("Specified folder/zip file does not contain a valid library"));
return;
}
// copy folder
File destinationFolder = new File(BaseNoGui.getSketchbookLibrariesFolder(), sourceFile.getName());
if (!destinationFolder.mkdir()) {
activeEditor.statusError(I18n.format(tr("A library named {0} already exists"), sourceFile.getName()));
return;
}
try {
FileUtils.copy(sourceFile, destinationFolder);
} catch (IOException e) {
activeEditor.statusError(e);
return;
}
activeEditor.statusNotice(tr("Library added to your libraries. Check \"Include library\" menu"));
} catch (IOException e) {
// FIXME error when importing. ignoring :(
} finally {
// delete zip created temp folder, if exists
FileUtils.recursiveDelete(tmpFolder);
}
}
public static DiscoveryManager getDiscoveryManager() {
return BaseNoGui.getDiscoveryManager();
}
public Editor getActiveEditor() {
return activeEditor;
}
public boolean hasActiveEditor() {
return activeEditor != null;
}
public List<Editor> getEditors() {
return new LinkedList<>(editors);
}
public PdeKeywords getPdeKeywords() {
return pdeKeywords;
}
public List<JMenuItem> getRecentSketchesMenuItems() {
return recentSketchesMenuItems;
}
}
|
// Coffee-Graph
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package bolt.web.coffee.command;
import com.beust.jcommander.Parameter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* This class is used with JCommander annotations to populate the runtime arguments passed to coffee graph.
*
* @author Matt Bolt
*/
public final class CoffeeGraphCommand {
@Parameter(description = "file.coffee ... [directory]")
public List<File> files = new ArrayList<File>();
@Parameter(names = {"--print", "-p"}, description = "Prints the ordered .coffee files on a single line.")
public boolean print = false;
@Parameter(names = {"--println", "-pl"}, description = "Prints the ordered .coffee files, one per line.")
public boolean println = false;
@Parameter(names = {"--tree", "-t"}, description = "Prints a dependency tree.")
public boolean tree = false;
@Parameter(names = {"--compile", "-c"}, description = "Performs an ordered file join and compilation to JavaScript")
public boolean compile = false;
@Parameter(names = {"--bare", "-b"}, description = "Compiles the CoffeeScript source without a security wrapper.")
public boolean bare = false;
@Parameter(names = {"-o" }, description = "The file to output the dependency graph to.")
public File outputFile = new File("lib/coffee-graph.js");
@Parameter(names = {"--help", "-h"}, description = "Show the coffee-graph command line usage.")
public boolean help = false;
@Parameter(names = {"--version", "-v"}, description = "Displays the current version of coffee-graph.")
public boolean version = false;
public CoffeeGraphCommand() {
}
@Override
public String toString() {
return new StringBuilder("[CoffeeGraphCommand - ")
.append("print: ").append(print).append(", ")
.append("println: ").append(println).append(", ")
.append("tree: ").append(tree).append(", ")
.append("compile: ").append(compile).append(", ")
.append("files: ").append(files).append(", ")
.append("outputFile: ").append(outputFile).append(", ")
.append("]").toString();
}
}
|
package hudson.plugins.disk_usage;
import hudson.Plugin;
import hudson.Util;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Job;
import hudson.model.Jobs;
import hudson.model.ManagementLink;
import hudson.triggers.Trigger;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.ServletException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* Entry point of the the plugin.
*
* @author dvrzalik
* @plugin
*/
public class DiskUsagePlugin extends Plugin {
private transient final DiskUsageThread duThread = new DiskUsageThread();
private static DiskUsage diskUsageSum;
@Override
public void start() throws Exception {
ManagementLink.LIST.add(new ManagementLink() {
public final String[] COLUMNS = new String[]{"Project name", "Builds", "Workspace"};
public String getIconFileName() {
return "/plugin/disk-usage/icons/diskusage48.png";
}
public String getDisplayName() {
return "Disk usage";
}
public String getUrlName() {
return "plugin/disk-usage/";
}
public String getDescription() {
return "Displays per-project disk usage";
}
});
}
/**
* @return DiskUsage for given project (shortcut for the view). Never null.
*/
public static DiskUsage getDiskUsage(Job project) {
ProjectDiskUsageAction action = project.getAction(ProjectDiskUsageAction.class);
if (action != null) {
return action.getDiskUsage();
}
return new DiskUsage(0, 0);
}
//Another shortcut
public static String getProjectUrl(Job project) {
return Util.encode(project.getAbsoluteUrl());
}
/**
* @return Project list sorted by occupied disk space
*/
public static List getProjectList() {
Comparator<AbstractProject> comparator = new Comparator<AbstractProject>() {
public int compare(AbstractProject o1, AbstractProject o2) {
DiskUsage du1 = getDiskUsage(o1);
DiskUsage du2 = getDiskUsage(o2);
long result = du2.wsUsage + du2.buildUsage - du1.wsUsage - du1.buildUsage;
if(result > 0) return 1;
if(result < 0) return -1;
return 0;
}
};
List<AbstractProject> projectList = Util.createSubList(Hudson.getInstance().getItems(), AbstractProject.class);
Collections.sort(projectList, comparator);
//calculate sum
DiskUsage sum = new DiskUsage(0, 0);
for(AbstractProject project: projectList) {
DiskUsage du = getDiskUsage(project);
sum.buildUsage += du.buildUsage;
sum.wsUsage += du.wsUsage;
}
diskUsageSum = sum;
return projectList;
}
public static DiskUsage getDiskUsageSum() {
return diskUsageSum;
}
public void doRecordDiskUsage(StaplerRequest req, StaplerResponse res) throws ServletException, IOException {
duThread.doRun();
res.forwardToPreviousPage(req);
}
}
|
package scal.io.liger.view;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import scal.io.liger.Constants;
import scal.io.liger.MediaHelper;
import scal.io.liger.R;
import scal.io.liger.Utility;
import scal.io.liger.model.Card;
import scal.io.liger.model.ClipCard;
import scal.io.liger.model.ClipMetadata;
import scal.io.liger.model.MediaFile;
public class ClipCardView extends ExampleCardView implements AdapterView.OnItemSelectedListener {
public static final String TAG = "ClipCardView";
public ClipCard mCardModel;
private ArrayList<View> mDisplayedClips = new ArrayList<>(); // Views representing clips currently displayed
private int mCardFooterHeight; // The mClipsExpanded height of the card footer (e.g: Capture import buttons)
private boolean mClipsExpanded = false; // Is the clip stack expanded
private final float PRIMARY_CLIP_ALPHA = 1.0f;
private final float SECONDARY_CLIP_ALPHA = .7f;
public ClipCardView(Context context, Card cardModel) {
super();
mContext = context;
mCardModel = (ClipCard) cardModel;
Resources r = context.getResources();
mCardFooterHeight = r.getDimensionPixelSize(R.dimen.clip_card_footer_height);
}
@Override
public View getCardView(Context context) {
if (mCardModel == null) {
return null;
}
View view = LayoutInflater.from(context).inflate(R.layout.card_clip, null);
final ViewGroup collapsableContainer = (ViewGroup) view.findViewById(R.id.collapsable);
final ViewGroup clipCandidatesContainer = (ViewGroup) view.findViewById(R.id.clipCandidates);
TextView headerText = (TextView) view.findViewById(R.id.headerText);
TextView bodyText = (TextView) view.findViewById(R.id.bodyText);
Spinner spinner = (Spinner) view.findViewById(R.id.overflowSpinner);
setupSpinner(spinner);
// - get element from your dataset at this position
// - replace the contents of the view with that element
ViewGroup.LayoutParams params = collapsableContainer.getLayoutParams();
params.height = 0;
collapsableContainer.setLayoutParams(params);
// TODO: If the recycled view previously belonged to a different
// card type, tear down and rebuild the view as in onCreateViewHolder.
final ArrayList<ClipMetadata> clipsToDisplay = mCardModel.getClips();
if (clipsToDisplay.size() > 0) clipCandidatesContainer.removeAllViews(); // Remove any prior clip views
View.OnClickListener clipCardOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getTag(R.id.view_tag_clip_primary) != null && (boolean) v.getTag(R.id.view_tag_clip_primary)) {
// Clicked clip is primary
Log.i("select", "primary");
if (mClipsExpanded) {
// Collapse clip view, without change
toggleClipExpansion(clipsToDisplay, clipCandidatesContainer);
toggleFooterVisibility(collapsableContainer);
} else {
//show trim dialog
}
} else {
// Clicked view is not primary clip
if (mClipsExpanded && v.getTag(R.id.view_tag_clip_primary) != null) {
// Clicked view is secondary clip and clips are expanded
// This indicates a new secondary clip was selected
Log.i("select", "new primary clip selected");
// If clips expanded, this event means we've been selected as the
// new primary clip!
setNewSelectedClip(v);
}
toggleClipExpansion(clipsToDisplay, clipCandidatesContainer);
toggleFooterVisibility(collapsableContainer);
}
}
};
// mSecondaryClipCardOnClickListener = new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Log.i("select", "secondary");
// if (mClipsExpanded) {
// Log.i("select", "new primary clip selected");
// // If clips expanded, this event means we've been selected as the
// // new primary clip!
// setNewSelectedClip(v);
// toggleClipExpansion(clipsToDisplay, clipCandidatesContainer);
// toggleFooterVisibility(collapsableContainer);
Log.i("clip", String.format("adding %d clips for cardclip ",clipsToDisplay.size()));
for (int x = 0; x < clipsToDisplay.size(); x++) {
// Create view for new clip
MediaFile mediaFile = mCardModel.loadMediaFile(clipsToDisplay.get(x));
View clipThumb = inflateAndAddThumbnailForClip(clipCandidatesContainer, mediaFile, x, clipsToDisplay.size() - 1);
clipThumb.setOnClickListener(clipCardOnClickListener);
if ( x != clipsToDisplay.size() - 1) {
// Clicking on any but the top clip triggers expansion
clipThumb.setTag(R.id.view_tag_clip_primary, false);
} else {
clipThumb.setTag(R.id.view_tag_clip_primary, true);
}
mDisplayedClips.add(clipThumb);
}
headerText.setText(mCardModel.getClipType().toUpperCase());
// Expand / Collapse footer on click
headerText.setOnClickListener(clipCardOnClickListener);
// Expand / Collapse clip stack on thumbnail click
// clipCandidatesContainer.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// toggleClipExpansion(clipsToDisplay, clipCandidatesContainer);
// toggleFooterVisibility(footerHeight, collapsableContainer);
bodyText.setText(mCardModel.getHeader());
// final VideoView vvCardVideo = ((VideoView) view.findViewById(R.id.vv_card_video));
// final ImageView ivCardPhoto = ((ImageView) view.findViewById(R.id.iv_card_photo));
// TextView tvHeader = ((TextView) view.findViewById(R.id.tv_header));
// TextView tvType = ((TextView) view.findViewById(R.id.tv_type));
// Button btnRecord = ((Button) view.findViewById(R.id.btn_record_media));
// final ToggleButton btnMediaPlay = ((ToggleButton) view.findViewById(R.id.tb_card_audio));
// tvHeader.setText(mCardModel.getHeader());
// tvType.setText(mCardModel.getClipType());
// final String clipMedium = mCardModel.getClipMedium();
// final String cardMediaId = mCardModel.getStoryPathReference().getId() + "::" + mCardModel.getId() + "::" + MEDIA_PATH_KEY;
// //set up media display
// String p = null;
// if ((mCardModel.getClips() != null) && (mCardModel.getClips().size() > 0)) {
// MediaFile mf = mCardModel.getSelectedMediaFile();
// if (mf == null) {
// Log.e(this.getClass().getName(), "no media file was found");
// } else {
// p = mf.getPath();
// final File mediaFile = getValidFile(p, mCardModel.getExampleMediaPath());
// if (mediaFile == null) {
// String clipType = mCardModel.getClipType();
// if (clipType.equals(Constants.CHARACTER)) {
// ivCardPhoto.setImageDrawable(mContext.getResources().getDrawable(R.drawable.cliptype_close));
// } else if (clipType.equals(Constants.ACTION)) {
// ivCardPhoto.setImageDrawable(mContext.getResources().getDrawable(R.drawable.cliptype_medium));
// } else if (clipType.equals(Constants.RESULT)){
// ivCardPhoto.setImageDrawable(mContext.getResources().getDrawable(R.drawable.cliptype_long));
// } else {
// //TODO handle invalid clip type
// ivCardPhoto.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_launcher));
// ivCardPhoto.setVisibility(View.VISIBLE);
// } else if (mediaFile.exists() && !mediaFile.isDirectory()) {
// if (clipMedium.equals(Constants.VIDEO)) {
// //set up image as preview
// Bitmap videoFrame = Utility.getFrameFromVideo(mediaFile.getPath());
// if(null != videoFrame) {
// ivCardPhoto.setImageBitmap(videoFrame);
// ivCardPhoto.setVisibility(View.VISIBLE);
// btnMediaPlay.setVisibility(View.VISIBLE);
// btnMediaPlay.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Uri video = Uri.parse(mediaFile.getPath());
// vvCardVideo.setVideoURI(video);
// vvCardVideo.seekTo(5);
// vvCardVideo.setMediaController(null);
// vvCardVideo.setVisibility(View.VISIBLE);
// ivCardPhoto.setVisibility(View.GONE);
// btnMediaPlay.setVisibility(View.GONE);
// vvCardVideo.start();
// //revert back to image on video completion
// vvCardVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
// public void onCompletion(MediaPlayer mp) {
// vvCardVideo.setVisibility(View.GONE);
// ivCardPhoto.setVisibility(View.VISIBLE);
// btnMediaPlay.setVisibility(View.VISIBLE);
// btnMediaPlay.setChecked(false);
// } else if (clipMedium.equals(Constants.PHOTO)) {
// Uri uri = Uri.parse(mediaFile.getPath());
// ivCardPhoto.setImageURI(uri);
// ivCardPhoto.setVisibility(View.VISIBLE);
// } else if (clipMedium.equals(Constants.AUDIO)) {
// Uri myUri = Uri.parse(mediaFile.getPath());
// final MediaPlayer mediaPlayer = new MediaPlayer();
// mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// //set background image
// String clipType = mCardModel.getClipType();
// int drawable = R.drawable.ic_launcher;
// if (clipType.equals(Constants.CHARACTER)) {
// drawable = R.drawable.cliptype_close;
// } else if (clipType.equals(Constants.ACTION)) {
// drawable = R.drawable.cliptype_medium;
// } else if (clipType.equals(Constants.RESULT)){
// drawable = R.drawable.cliptype_long;
// ivCardPhoto.setImageDrawable(mContext.getResources().getDrawable(drawable));
// ivCardPhoto.setVisibility(View.VISIBLE);
// //set up media player
// try {
// mediaPlayer.setDataSource(mContext, myUri);
// mediaPlayer.prepare();
// } catch (IOException e) {
// e.printStackTrace();
// btnMediaPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// if (isChecked) {
// mediaPlayer.seekTo(5);
// mediaPlayer.start();
// } else {
// mediaPlayer.pause();
// mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
// @Override
// public void onCompletion(MediaPlayer arg0) {
// btnMediaPlay.setChecked(false);
// mediaPlayer.seekTo(5);
// btnMediaPlay.setVisibility(View.VISIBLE);
// } else {
// //TODO handle invalid-medium error
// //set correct listener for record button
// btnRecord.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = null;
// int requestId = -1;
// if(clipMedium.equals(Constants.VIDEO)) {
// intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// requestId = Constants.REQUEST_VIDEO_CAPTURE;
// } else if(clipMedium.equals(Constants.PHOTO)) {
// intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// requestId = Constants.REQUEST_IMAGE_CAPTURE;
// } else if(clipMedium.equals(Constants.AUDIO)) {
// intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
// requestId = Constants.REQUEST_AUDIO_CAPTURE;
// if (null != intent && intent.resolveActivity(mContext.getPackageManager()) != null) {
// mContext.getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().putString(Constants.PREFS_CALLING_CARD_ID, cardMediaId).apply(); // FIXME should be done off the ui thread
// ((Activity) mContext).startActivityForResult(intent, requestId);
// supports automated testing
view.setTag(mCardModel.getId());
return view;
}
/**
* Note: zOrder 0 is the bottom of the clip list.
* @return the view inflated and added to clipCandidatesContainer
*/
private View inflateAndAddThumbnailForClip(@NonNull ViewGroup clipCandidatesContainer, @Nullable MediaFile mediaFile, int zOrder, int zTop) {
Resources r = clipCandidatesContainer.getContext().getResources();
int topMarginPerZ = r.getDimensionPixelSize(R.dimen.clip_stack_margin_top);
LayoutInflater inflater = (LayoutInflater) clipCandidatesContainer.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView thumbnail = (ImageView) inflater.inflate(R.layout.clip_thumbnail, clipCandidatesContainer, false);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) thumbnail.getLayoutParams();
params.topMargin = topMarginPerZ * (zTop - zOrder);
//Log.i("inflate", String.format("Inflating thumbnail for z %d with top margin %d", zOrder, params.topMargin));
thumbnail.setLayoutParams(params);
//set clip thumbnail image
setThumbnailForClip(thumbnail, mediaFile);
if (zOrder != zTop)
thumbnail.setAlpha(SECONDARY_CLIP_ALPHA);
else
thumbnail.setAlpha(PRIMARY_CLIP_ALPHA);
clipCandidatesContainer.addView(thumbnail);
return thumbnail;
}
private void setThumbnailForClip(@NonNull ImageView thumbnail, MediaFile media) {
String mediaPath = null;
if ((mCardModel.getClips() != null) && (mCardModel.getClips().size() > 0)) {
if (media == null) {
Log.e(TAG, "no media file was found");
} else {
mediaPath = media.getPath();
}
}
final File mediaFile = getValidFile(mediaPath, mCardModel.getExampleMediaPath());
if (mediaFile == null) {
// Clip has no attached media. Show generic drawable based on clip type
String clipType = mCardModel.getClipType();
if (clipType.equals(Constants.CHARACTER)) {
thumbnail.setImageDrawable(mContext.getResources().getDrawable(R.drawable.cliptype_close));
} else if (clipType.equals(Constants.ACTION)) {
thumbnail.setImageDrawable(mContext.getResources().getDrawable(R.drawable.cliptype_medium));
} else if (clipType.equals(Constants.RESULT)){
thumbnail.setImageDrawable(mContext.getResources().getDrawable(R.drawable.cliptype_long));
} else {
//TODO handle invalid clip type
thumbnail.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_launcher));
}
thumbnail.setVisibility(View.VISIBLE);
} else if (mediaFile.exists() && !mediaFile.isDirectory()) {
// Clip has attached media. Show an appropriate preview
// e.g: A thumbnail for video
String clipMedium = mCardModel.getClipMedium();
if (clipMedium.equals(Constants.VIDEO)) {
//set up image as preview
Bitmap videoFrame = Utility.getFrameFromVideo(mediaFile.getPath());
if(null != videoFrame) {
thumbnail.setImageBitmap(videoFrame);
}
thumbnail.setVisibility(View.VISIBLE);
// btnMediaPlay.setVisibility(View.VISIBLE);
// btnMediaPlay.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Uri video = Uri.parse(mediaFile.getPath());
// vvCardVideo.setVideoURI(video);
// vvCardVideo.seekTo(5);
// vvCardVideo.setMediaController(null);
// vvCardVideo.setVisibility(View.VISIBLE);
// thumbnail.setVisibility(View.GONE);
// btnMediaPlay.setVisibility(View.GONE);
// vvCardVideo.start();
// //revert back to image on video completion
// vvCardVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
// public void onCompletion(MediaPlayer mp) {
// vvCardVideo.setVisibility(View.GONE);
// ivCardPhoto.setVisibility(View.VISIBLE);
// btnMediaPlay.setVisibility(View.VISIBLE);
// btnMediaPlay.setChecked(false);
} else if (clipMedium.equals(Constants.PHOTO)) {
Uri uri = Uri.parse(mediaFile.getPath());
thumbnail.setImageURI(uri);
thumbnail.setVisibility(View.VISIBLE);
} else if (clipMedium.equals(Constants.AUDIO)) {
Uri myUri = Uri.parse(mediaFile.getPath());
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set background image
String clipType = mCardModel.getClipType();
int drawable = R.drawable.ic_launcher;
if (clipType.equals(Constants.CHARACTER)) {
drawable = R.drawable.cliptype_close;
} else if (clipType.equals(Constants.ACTION)) {
drawable = R.drawable.cliptype_medium;
} else if (clipType.equals(Constants.RESULT)){
drawable = R.drawable.cliptype_long;
}
thumbnail.setImageDrawable(mContext.getResources().getDrawable(drawable));
thumbnail.setVisibility(View.VISIBLE);
// //set up media player
// try {
// mediaPlayer.setDataSource(mContext, myUri);
// mediaPlayer.prepare();
// } catch (IOException e) {
// e.printStackTrace();
// btnMediaPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// if (isChecked) {
// mediaPlayer.seekTo(5);
// mediaPlayer.start();
// } else {
// mediaPlayer.pause();
// mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
// @Override
// public void onCompletion(MediaPlayer arg0) {
// btnMediaPlay.setChecked(false);
// mediaPlayer.seekTo(5);
// btnMediaPlay.setVisibility(View.VISIBLE);
} else {
//TODO handle invalid-medium error
}
}
}
private final int STAGGERED_ANIMATION_GAP_MS = 70;
private void toggleClipExpansion(List<ClipMetadata> clipsToDisplay, ViewGroup clipCandidatesContainer) {
// When this method is called all clips in holder.displayedClips should be
// added to holder.clipCandidatesContainer in order (e.g: First item is highest z order)
final int clipCandidateCount = clipsToDisplay.size();
if (clipsToDisplay.size() < 2) {
// If less than 2 clips, there's no reason to expand / collapse
return;
}
// Dp to px
Resources r = clipCandidatesContainer.getContext().getResources();
int topMargin = r.getDimensionPixelSize(R.dimen.clip_stack_margin_top); // Margin between clip thumbs
int clipHeight = r.getDimensionPixelSize(R.dimen.clip_thumb_height); // Height of each clip thumb
int howtoHeight = r.getDimensionPixelSize(R.dimen.card_howto_height); // Height of howto card that appears at stack top
final View howtoCard = ((View) clipCandidatesContainer.getParent()).findViewById(R.id.howtoCard);
float finalHowToOpacity = mClipsExpanded ? 0f : 1f;
ObjectAnimator howtoAnim = ObjectAnimator.ofFloat(howtoCard, "alpha", 1 - finalHowToOpacity, finalHowToOpacity);
howtoAnim.setStartDelay((long) (STAGGERED_ANIMATION_GAP_MS * (clipCandidateCount + 1) * finalHowToOpacity));
howtoAnim.start();
// Loop over all clip views except the last
for (int i = 0; i < clipCandidateCount; i ++) {
int viewIdx = i;
if (mClipsExpanded) {
// when mClipsExpanded : 0, 1
// when compressing : 1, 0
viewIdx = (clipCandidateCount - 1) - i;
}
final View child = mDisplayedClips.get(viewIdx);
final ViewGroup.LayoutParams params = child.getLayoutParams();
int marginPerChild = topMargin + clipHeight;
ValueAnimator animator;
//int startAnimationMargin;
int stopAnimationMargin;
int marginMultiplier = (clipCandidateCount - 1) - viewIdx;
if (mClipsExpanded) {
// compress
stopAnimationMargin = (topMargin * marginMultiplier); // howtoCard is leaving
// Remove pressable background drawables
child.setBackgroundResource(R.drawable.clip_card_unselected);
} else {
// expand
stopAnimationMargin = (marginMultiplier * marginPerChild) + (howtoHeight + topMargin);
// Add pressable background drawable
child.setBackgroundResource(R.drawable.clip_card_selectable_bg);
}
Log.i("anim", String.format("Animating margin from %d to %d", ((ViewGroup.MarginLayoutParams) params).topMargin, stopAnimationMargin));
animator = ValueAnimator.ofInt(((ViewGroup.MarginLayoutParams) params).topMargin, stopAnimationMargin);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
((ViewGroup.MarginLayoutParams) params).topMargin = (int) valueAnimator.getAnimatedValue();
child.setLayoutParams(params);
}
});
animator.setStartDelay((1+ i) * STAGGERED_ANIMATION_GAP_MS);
animator.start();
//Log.i("anim", "View idx " + viewIdx + " animating with delay " + (1+ i) * 400 + " to margin " + stopAnimationMargin);
}
mClipsExpanded = !mClipsExpanded;
}
private void toggleFooterVisibility(final ViewGroup collapsable) {
final ViewGroup.LayoutParams params = collapsable.getLayoutParams();
ValueAnimator animator = null;
if (collapsable.getHeight() < mCardFooterHeight) {
// Expand
animator = ValueAnimator.ofInt(0, mCardFooterHeight);
} else {
// Collapse
animator = ValueAnimator.ofInt(mCardFooterHeight, 0);
}
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
params.height = (Integer) valueAnimator.getAnimatedValue();
collapsable.setLayoutParams(params);
}
});
animator.start();
}
//returns stored mediaPath (if exists) or exampleMediaPath (if exists)
@Override
public File getValidFile(String mediaPath, String exampleMediaPath) {
File mediaFile = null;
if (mediaPath != null) {
mediaFile = MediaHelper.loadFileFromPath(mCardModel.getStoryPathReference().buildPath(mediaPath));
} else if (exampleMediaPath != null) {
mediaFile = MediaHelper.loadFileFromPath(mCardModel.getStoryPathReference().buildPath(exampleMediaPath));
}
return mediaFile;
}
private void setupSpinner(Spinner spinner) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(mContext,
R.array.clipcard_overflow, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner.
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
/** Spinner OnItemSelectedListener */
private int mItemSelectedCount = 0;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// This fixes the issue but intro's a new problem:
// Whenever the 0 position element is the first selected I get
// scal.io.liger W/InputEventReceiver Attempted to finish an input event but the input event receiver has already been disposed.
// instead of a callback here. wtf.
//Log.i("spinner", "count " + mItemSelectedCount + " position " + position);
mItemSelectedCount++;
if (mItemSelectedCount > 1)
Toast.makeText(mContext, "Selected " + (String) parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
/** End Spinner OnItemSelectedListener */
private void setNewSelectedClip(View newSelectedClip) {
// Put the passed clipThumbnail at the top of the stack
// The top of the stack is the end of mDisplayedClips
Log.i("swap", String.format("Swapping card %d for %d", mDisplayedClips.indexOf(newSelectedClip), mDisplayedClips.size()-1));
View oldSelectedClip = mDisplayedClips.get(mDisplayedClips.size()-1);
mDisplayedClips.remove(mDisplayedClips.indexOf(newSelectedClip));
mDisplayedClips.add(newSelectedClip);
newSelectedClip.bringToFront();
// Swap alphas
oldSelectedClip.setAlpha(SECONDARY_CLIP_ALPHA);
newSelectedClip.setAlpha(PRIMARY_CLIP_ALPHA);
// Change view tags indicating primary / secondary status
oldSelectedClip.setTag(R.id.view_tag_clip_primary, false);
newSelectedClip.setTag(R.id.view_tag_clip_primary, true);
}
private View.OnTouchListener mClipSelectionListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("select", "setting clip selected");
v.setBackgroundResource(R.drawable.clip_card_selected);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
Log.i("select", "setting clip unselected");
v.setBackgroundResource(0);
break;
}
return false;
}// onTouch()
};
}
|
package io.domisum.lib.auxiliumlib;
import io.domisum.lib.auxiliumlib.annotations.API;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.stream.Stream;
public class FileLineStream
implements Closeable
{
private final Stream<?> closeable;
private final Deque<String> currentLines = new ArrayDeque<>();
private final Iterator<String> iterator;
// INIT
public FileLineStream(File file)
{
try
{
var linesStream = Files.lines(file.toPath());
closeable = linesStream;
iterator = linesStream.iterator();
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@Override
public void close()
throws IOException
{
closeable.close();
}
// STREAM
@API
public String discardLinesUntil(String marker)
throws IOException
{
while(currentLines.size() > 0)
{
String cl = currentLines.removeFirst();
if(cl.contains(marker))
return cl;
}
return findLineInIterator(marker, false);
}
@API
public String findLine(String marker)
throws IOException
{
for(String cl : currentLines)
if(cl.contains(marker))
return cl;
return findLineInIterator(marker, true);
}
private String findLineInIterator(String marker, boolean addLinesToCurrent)
throws IOException
{
while(iterator.hasNext())
{
String line = iterator.next();
if(addLinesToCurrent)
currentLines.add(line);
if(line.contains(marker))
return line;
}
throw new IOException(PHR.r("Could not find line containing '{}'", marker));
}
@API
public Iterator<String> iterateAndDiscard()
{
return new LineIterator();
}
private class LineIterator
implements Iterator<String>
{
@Override
public boolean hasNext()
{
if(currentLines.size() > 0)
return true;
return iterator.hasNext();
}
@Override
public String next()
{
if(currentLines.size() > 0)
return currentLines.removeFirst();
return iterator.next();
}
}
}
|
package com.bakerbeach.market.core.api.model;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface Order {
public final static String STATUS_TMP = "tmp";
public final static String STATUS_SUBMITTED = "submitted";
@Deprecated
public final static String STATUS_SUBMIT = "submit";
public final static String STATUS_ACCEPTED = "accepted";
public final static String STATUS_CANCELED = "canceled";
String getId();
void setId(String id);
String getShopCode();
void setShopCode(String shopCode);
@Deprecated
String getCurrency();
String getCurrencyCode();
void setCurrencyCode(String currencyCode);
BigDecimal getTotal();
void setTotal(BigDecimal total);
String getCustomerId();
void setCustomerId(String customerId);
Address getShippingAddress();
void setShippingAddress(Address shippingAddress);
Address getBillingAddress();
void setBillingAddress(Address billingAddress);
@Deprecated
List<OrderItem> getItems();
Map<String, OrderItem> getAllItems();
OrderItem getItem(String key);
@Deprecated
void addItem(Object newOrderItem);
void addItem(OrderItem item);
Map<String, Object> getAllAttributes();
void addAttributes(Map<String, Object> map);
@Deprecated
HashMap<String, Object> getAttributes();
@Deprecated
HashMap<String, Object> getAdditionalInformations();
@Deprecated
String getOrderStatus();
String getStatus();
void setStatus(String status);
String getCustomerEmail();
void setCustomerEmail(String customerEmail);
Date getUpdatedAt();
void setUpdatedAt(Date date);
Date getCreatedAt();
void setCreatedAt(Date createdAt);
String getPaymentCode();
void setPaymentCode(String paymentCode);
String getPaymentTransactionId();
OrderItem newItem();
}
|
package io.github.data4all.util;
import io.github.data4all.model.data.Node;
import java.util.LinkedList;
import java.util.List;
/**
* @author Richard
*
*/
public class RectangleFunction {
/**
* Transforms a quadrangle into a rectangle.
*
* @param nodes
* List of the nodes of the quadrangle
* @return result List of the nodes of the now rectangle.
*/
public static List<Node> transformIntoRectangle(List<Node> nodes) {
if (nodes.size() >= 4) {
Node a = nodes.get(0);
Node b = nodes.get(1);
Node c = nodes.get(2);
Node d = nodes.get(3);
double ax = a.getLat();
double ay = a.getLon();
double bx = b.getLat();
double by = b.getLon();
double cx = c.getLat();
double cy = c.getLon();
double dx = d.getLat();
double dy = d.getLon();
double abx = bx - ax;
double aby = by - ay;
double bcx = cx - bx;
double bcy = cy - by;
double cdx = dx - cx;
double cdy = dy - cy;
double dax = ax - dx;
double day = ay - dy;
double abLength = Math.sqrt((abx * abx) + (aby * aby));
double bcLength = Math.sqrt((bcx * bcx) + (bcy * bcy));
double cdLength = Math.sqrt((cdx * cdx) + (cdy * cdy));
double daLength = Math.sqrt((dax * dax) + (day * day));
double alpha = Math.acos(((-1 * dax * abx) + (-1 * day * aby)
/ (daLength * abLength)));
double beta = Math.acos(((-1 * abx * bcx) + (-1 * aby * bcy))
/ (abLength * bcLength));
double gamma = Math.acos(((-1 * bcx * cdx) + (-1 * bcy * cdy))
/ (bcLength * cdLength));
double delta = Math.acos(((-1 * cdx * dax) + (-1 * cdy * day)
/ (cdLength * daLength)));
double alphaMinus = (Math.PI / 2) - alpha;
double betaMinus = (Math.PI / 2) - beta;
double gammaMinus = (Math.PI / 2) - gamma;
double deltaMinus = (Math.PI / 2) - delta;
List<Node> result = new LinkedList<Node>();
double temp;
switch (closestTo90(alphaMinus, betaMinus, gammaMinus, deltaMinus)) {
case 1:
temp = abx;
abx = (temp * Math.cos(alphaMinus))
- (aby * Math.sin(alphaMinus));
aby = (temp * Math.sin(alphaMinus))
+ (aby * Math.cos(alphaMinus));
bx = ax + abx;
by = ay + aby;
cx = bx + (-1) * dax;
cy = by + (-1) * day;
break;
case 2:
temp = bcx;
bcx = (temp * Math.cos(betaMinus))
- (bcy * Math.sin(betaMinus));
bcy = (temp * Math.sin(betaMinus))
+ (bcy * Math.cos(betaMinus));
cx = bx + bcx;
cy = by + bcy;
dx = cx + (-1) * abx;
dy = cy + (-1) * aby;
break;
case 3:
temp = cdx;
cdx = (temp * Math.cos(gammaMinus))
- (cdy * Math.sin(gammaMinus));
cdy = (temp * Math.sin(gammaMinus))
+ (cdy * Math.cos(gammaMinus));
dx = cx + cdx;
dy = cy + cdy;
ax = dx + (-1) * bcx;
ay = dy + (-1) * bcy;
break;
case 4:
temp = dax;
dax = (temp * Math.cos(deltaMinus))
- (day * Math.sin(deltaMinus));
day = (temp * Math.sin(deltaMinus))
+ (day * Math.cos(deltaMinus));
ax = dx + dax;
ay = dy + day;
bx = ax + (-1) * cdx;
by = ay + (-1) * cdy;
break;
}
a.setLat(ax);
a.setLon(ay);
b.setLat(bx);
b.setLon(by);
c.setLat(cx);
c.setLon(cy);
d.setLat(dx);
d.setLon(dy);
result.add(a);
result.add(b);
result.add(c);
result.add(d);
result.add(a);
return result;
}
return nodes;
}
private static int closestTo90(double a, double b, double c, double d) {
if (Math.abs(a) > Math.abs(b)) {
if (Math.abs(b) > Math.abs(c)) {
if (Math.abs(c) > Math.abs(d)) {
return 4;
} else {
return 3;
}
} else {
if (Math.abs(b) > Math.abs(d)) {
return 4;
} else {
return 2;
}
}
} else {
if (Math.abs(a) > Math.abs(c)) {
if (Math.abs(c) > Math.abs(d)) {
return 4;
} else {
return 3;
}
} else {
if (Math.abs(a) > Math.abs(d)) {
return 4;
} else {
return 1;
}
}
}
}
}
|
package com.blamejared.mcbot.commands;
import java.awt.Color;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.blamejared.mcbot.commands.api.Argument;
import com.blamejared.mcbot.commands.api.Command;
import com.blamejared.mcbot.commands.api.CommandBase;
import com.blamejared.mcbot.commands.api.CommandContext;
import com.blamejared.mcbot.commands.api.CommandException;
import com.blamejared.mcbot.util.BakedMessage;
import com.blamejared.mcbot.util.DefaultNonNull;
import com.blamejared.mcbot.util.NonNull;
import com.blamejared.mcbot.util.Nullable;
import com.blamejared.mcbot.util.PaginatedMessageFactory;
import com.blamejared.mcbot.util.Threads;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import lombok.Value;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.util.EmbedBuilder;
@Command
public class CommandCurse extends CommandBase {
@Value
@DefaultNonNull
private static final class ModInfo implements Comparable<ModInfo> {
String name;
String URL;
String[] tags;
long downloads;
@Nullable Document modpage;
@Override
public int compareTo(@SuppressWarnings("null") ModInfo o) {
return getName().compareTo(o.getName());
}
}
private static final Argument<String> ARG_USERNAME = new WordArgument("username", "The curse username of the mod author.", true);
public CommandCurse() {
super("curse", false, Collections.emptyList(), Lists.newArrayList(ARG_USERNAME));
}
private final Random rand = new Random();
@Override
public void process(CommandContext ctx) throws CommandException {
long time = System.currentTimeMillis();
String user = ctx.getArg(ARG_USERNAME);
String title = "Information on: " + user;
rand.setSeed(user.hashCode());
int color = Color.HSBtoRGB(rand.nextFloat(), 1, 1);
String authorName = ctx.getMessage().getAuthor().getDisplayName(ctx.getGuild()) + " requested";
String authorIcon = ctx.getMessage().getAuthor().getAvatarURL();
IMessage waitMsg = ctx.reply("Please wait, this may take a while...");
ctx.getChannel().setTypingStatus(true);
PaginatedMessageFactory.Builder msgbuilder = PaginatedMessageFactory.INSTANCE.builder(ctx.getChannel());
try {
Document doc;
try {
doc = getDocumentSafely(String.format("https://mods.curse.com/members/%s/projects", user));
} catch (HttpStatusException e) {
if (e.getStatusCode() / 100 == 4) {
throw new CommandException("User " + user + " does not exist.");
}
throw e;
}
String avatar = doc.getElementsByClass("avatar").first().child(0).child(0).attr("src");
Set<ModInfo> mods = new TreeSet<>();
Element nextPageButton = null;
// Always run first page
do {
// After first page
if (nextPageButton != null) {
doc = getDocumentSafely("https://mods.curse.com" + nextPageButton.child(0).attr("href"));
}
// Get all detail titles, map to their only child (<a> tag)
doc.getElementsByTag("dt").stream().map(ele -> ele.child(0)).forEach(ele -> {
ctx.getChannel().setTypingStatus(true); // make sure this stays active
// Mod name is the text, mod URL is the link target
@SuppressWarnings("null")
@NonNull
String mod = ele.text();
@SuppressWarnings("null")
@NonNull
String url = ele.attr("href");
// Navigate up to <dl> and grab second child, which is the <dd> with tags, get all <a> tags from them
@SuppressWarnings("null")
@NonNull
String[] tags = ele.parent().parent().child(1).getElementsByTag("a").stream().map(e -> e.text()).toArray(String[]::new);
try {
Document modpage = getDocumentSafely("https://mods.curse.com" + url);
long downloads = Long.parseLong(modpage.getElementsByClass("downloads").get(0).html().split(" Total")[0].trim().replaceAll(",", ""));
url = "http://mods.curse.com" + url.replaceAll(" ", "-");
mods.add(new ModInfo(mod, url, tags, downloads, modpage));
} catch (IOException e) {
e.printStackTrace();
mods.add(new ModInfo(mod, url, tags, 0, null));
}
});
// Try to find the next page button
nextPageButton = doc.select(".b-pagination-item.next-page").first();
// If it's present, process it
} while (nextPageButton != null);
if (mods.isEmpty()) {
throw new CommandException("User does not have any visible projects.");
}
// Load main curseforge page and get the total mod download count
long globalDownloads = getDocumentSafely("https://minecraft.curseforge.com/projects").getElementsByClass("category-info").stream()
.filter(e -> e.child(0).child(0).text().equals("Mods"))
.findFirst()
.map(e -> e.getElementsByTag("p").first().text())
.map(s -> s.substring(s.lastIndexOf("more than"), s.lastIndexOf("downloads"))) // trim out the relevant part of the string
.map(s -> s.replaceAll("(more than|,)", "").trim()) // delete excess characters
.map(Long::parseLong)
.orElseThrow(() -> new CommandException("Could not load global downloads"));
long totalDownloads = mods.stream().mapToLong(ModInfo::getDownloads).sum();
EmbedBuilder mainpg = new EmbedBuilder()
.withTitle(title)
.withDesc("Main page")
.withColor(color)
.withAuthorName(authorName)
.withAuthorIcon(authorIcon)
.withThumbnail(avatar)
.appendField("Total downloads", NumberFormat.getIntegerInstance().format(totalDownloads) + " (" + formatPercent(((double) totalDownloads / globalDownloads)) + ")", false)
.appendField("Project count", Integer.toString(mods.size()), false);
StringBuilder top3 = new StringBuilder();
mods.stream().sorted((m1, m2) -> Long.compare(m2.getDownloads(), m1.getDownloads())).limit(3)
.forEach(mod -> top3.append("[").append(mod.getName()).append("](").append(mod.getURL()).append(")").append(": ")
.append(NumberFormat.getIntegerInstance().format(mod.getDownloads())).append('\n'));
mainpg.appendField("Top 3", top3.toString(), false);
msgbuilder.addPage(new BakedMessage().withEmbed(mainpg.build()));
final int modsPerPage = 10;
final int pages = (mods.size() / modsPerPage) + 1;
for (int i = 0; i < pages; i++) {
final EmbedBuilder page = new EmbedBuilder()
.withTitle(title)
.withDesc("Mods page " + (i + 1) + "/" + pages)
.withColor(color)
.withAuthorName(authorName)
.withAuthorIcon(authorIcon)
.withThumbnail(avatar);
mods.stream().skip(modsPerPage * i).limit(modsPerPage).forEach(mod -> {
StringBuilder desc = new StringBuilder();
desc.append("[Link](" + mod.getURL() + ")\n");
desc.append("Tags: ").append(Joiner.on(" | ").join(mod.getTags())).append("\n");
desc.append("Downloads: ")
.append(DecimalFormat.getIntegerInstance().format(mod.getDownloads()))
.append(" (").append(formatPercent((double) mod.getDownloads() / totalDownloads)).append(" of total)\n");
String role = mod.getModpage() == null ? "Error!" : mod.getModpage().getElementsByClass("authors").first().children().stream()
.filter(el -> StringUtils.containsIgnoreCase(el.children().text(), user))
.findFirst()
.map(Element::ownText)
.map(s -> s.trim().substring(0, s.indexOf(':')))
.orElse("Unknown");
page.appendField(mod.getName() + " | " + role + "", desc.toString(), false);
});
msgbuilder.addPage(new BakedMessage().withEmbed(page.build()));
}
waitMsg.delete();
} catch (IOException e) {
throw new CommandException(e);
} finally {
waitMsg.delete();
ctx.getChannel().setTypingStatus(false);
}
msgbuilder.setParent(ctx.getMessage()).setProtected(false).build().send();
System.out.println("Took: " + (System.currentTimeMillis()-time));
}
private Document getDocumentSafely(String url) throws IOException {
Document ret = null;
while (ret == null) {
try {
ret = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1").get();
} catch (SocketTimeoutException e) {
System.out.println("Caught timeout loading URL: " + url);
System.out.println("Retrying in 5 seconds...");
Threads.sleep(5000);
} catch (IOException e) {
throw e;
}
}
return ret;
}
private final String formatPercent(double pct) {
NumberFormat pctFmt = DecimalFormat.getPercentInstance();
pctFmt.setMaximumFractionDigits(pct >= 0.1 ? 0 : pct >= 0.01 ? 1 : 4);
return pctFmt.format(pct);
}
public String getDescription() {
return "Displays download counts for all of a modder's curse projects.";
}
}
|
package com.ds.listing.services;
import com.ds.listing.model.Listing;
import com.ds.listing.model.Book;
import com.ds.listing.model.NameValuePair;
import com.ebay.sdk.call.*;
import com.ebay.sdk.util.eBayUtil;
import com.ebay.soap.eBLBaseComponents.*;
import com.ebay.sdk.ApiContext;
import java.util.ArrayList;
import java.util.List;
import com.ds.listing.rest.UnsoldListData;
public class eBayListingService {
private ApiContext apiContext;
private static final String STOCK_DESCRIPTION = "<h3 style='text-align: center;'><span style='color:
public eBayListingService(ApiContext apiContext) {
this.apiContext = apiContext;
}
public Listing getItem(String id) {
try {
GetItemCall api = new GetItemCall(apiContext);
ItemType item = api.getItem(id);
return populateListing(item);
} catch (Exception ignored) {
}
return null;
}
public ArrayList<RecommendationsType> getCategories(){
try {
GetCategoriesCall api = new GetCategoriesCall(apiContext);
GetCategoriesCall apiChild = new GetCategoriesCall(apiContext);
api.setLevelLimit(1);
apiChild.setLevelLimit(2);
apiChild.addDetailLevel(DetailLevelCodeType.RETURN_ALL);
CategoryType[] parents = api.getCategories();
for (CategoryType parent : parents) {
if (parent.getCategoryName().equals("Books")){
String[] cat = new String[1];
cat[0] = parent.getCategoryID();
apiChild.setParentCategory(cat);
}
}
CategoryType[] categories = apiChild.getCategories();
ArrayList<String> catId = new ArrayList<>();
for(CategoryType child : categories){
if(!child.getCategoryName().equals("Books")){
catId.add(child.getCategoryID());
}
}
GetCategorySpecificsCall catApi = new GetCategorySpecificsCall(apiContext);
catApi.setCategoryID((String[])catId.toArray());
RecommendationsType[] rec = catApi.getCategorySpecifics();
ArrayList<RecommendationsType> retList = new ArrayList<>();
for(RecommendationsType item : rec){
retList.add(item);
}
return retList;
}catch (Exception ignored){
}
return null;
}
public void getCurrentListings(int page, int resultPerPage, UnsoldListData data) {
ArrayList<Listing> retValues = new ArrayList<>();
try {
GetMyeBaySellingCall api = new GetMyeBaySellingCall(apiContext);
ItemListCustomizationType unsoldList = new ItemListCustomizationType();
unsoldList.setSort(ItemSortTypeCodeType.END_TIME);
unsoldList.setInclude(true);
unsoldList.setDurationInDays(60);
api.addDetailLevel(DetailLevelCodeType.RETURN_ALL);
PaginationType pt = new PaginationType();
pt.setEntriesPerPage(resultPerPage);
int totalNumberOfPages;
unsoldList.setPagination(pt);
api.setUnsoldList(unsoldList);
pt.setPageNumber(page);
api.getMyeBaySelling();
PaginatedItemArrayType unsoldItems = api.getReturnedUnsoldList();
if(unsoldItems != null){
PaginationResultType pr = unsoldItems.getPaginationResult();
totalNumberOfPages = pr.getTotalNumberOfPages();
ItemArrayType itemArray = unsoldItems.getItemArray();
ItemType[] items = itemArray.getItem();
for(ItemType item : items){
GetItemCall itemApi = new GetItemCall(apiContext);
itemApi.addDetailLevel(DetailLevelCodeType.RETURN_ALL);
ItemType fullItem = itemApi.getItem(item.getItemID());
try{
retValues.add(populateListing(fullItem));
}catch(Exception ignored){
ignored.printStackTrace();
System.out.println("unable to add record: " + ignored.getMessage());
}
}
data.setNumPages(totalNumberOfPages);
data.setNumResults(pr.getTotalNumberOfEntries());
data.setListings(retValues);
System.out.println("Results #" + retValues.size());
}
} catch (Exception ignored) {
System.out.println("unknown error");
}
}
private Listing populateListing(ItemType item) throws Exception {
Listing listing = new Listing();
listing.setEbayTitle(item.getTitle());
listing.setEbayListingId(item.getItemID());
if (item.getConditionDescription() != null) {
listing.setConditionDescription(item.getConditionDescription());
}
if (item.getStorefront() != null) {
listing.setStoreCategory(item.getStorefront().getStoreCategoryID());
long fabid = 28162;
if (item.getStorefront().getStoreCategoryID() == fabid) {
throw new Exception("not a book");
}
}
if (item.getStartPrice() != null) {
listing.setEbayPrice(item.getStartPrice().getValue());
}
Book b = new Book();
if (item.getProductListingDetails() != null) {
b.setIsbn(item.getProductListingDetails().getISBN());
}
if (item.getShippingDetails() != null) {
b.setWeightMajor(item.getShippingDetails().getCalculatedShippingRate().getWeightMajor().getValue());
b.setWeightMinor(item.getShippingDetails().getCalculatedShippingRate().getWeightMinor().getValue());
b.setDepth(item.getShippingDetails().getCalculatedShippingRate().getPackageDepth().getValue());
b.setWidth(item.getShippingDetails().getCalculatedShippingRate().getPackageLength().getValue());
b.setHeight(item.getShippingDetails().getCalculatedShippingRate().getPackageDepth().getValue());
}
listing.setBook(b);
if (item.getPrimaryCategory() != null) {
listing.setCategory(item.getPrimaryCategory().getCategoryID());
}
listing.setEbayCondition(item.getConditionID());
if (item.getSellingStatus() != null) {
listing.setQuantity(item.getQuantity() - item.getSellingStatus().getQuantitySold());
} else {
listing.setQuantity(item.getQuantity());
}
listing.setEbayDescription(STOCK_DESCRIPTION);
return listing;
}
public boolean addListing(Listing listing) {
try {
ItemType item = buildItemType(listing);
AddFixedPriceItemCall api = new AddFixedPriceItemCall(apiContext);
api.setItem(item);
FeesType fees = api.addFixedPriceItem();
double listingFee = eBayUtil.findFeeByName(fees.getFee(), "ListingFee").getFee().getValue();
System.out.println("Listing fee is: " + Double.toString(listingFee));
listing.setEbayListingId(item.getItemID());
return true;
} catch (Exception e) {
System.out.println("Error adding item");
return false;
}
}
private ItemType buildItemType(Listing listing) {
ItemType item = new ItemType();
item.setTitle(listing.getEbayTitle());
item.setListingType(ListingTypeCodeType.FIXED_PRICE_ITEM);
item.setCurrency(CurrencyCodeType.USD);
setPrice(item, listing.getEbayPrice());
item.setQuantity(listing.getQuantity());
item.setListingDuration(ListingDurationCodeType.DAYS_30.value());
item.setPostalCode("40065");
item.setLocation("Shelbyville");
item.setCountry(CountryCodeType.US);
//Generate Category Type
CategoryType cat = new CategoryType();
cat.setCategoryID(listing.getCategory());
item.setPrimaryCategory(cat);
item.setConditionID(listing.getEbayCondition());
item.setConditionDescription(listing.getConditionDescription());
item.setDescription(listing.getEbayDescription());
//Generate Listing Designer Type
ListingDesignerType design = new ListingDesignerType();
design.setThemeID(223353102);
item.setListingDesigner(design);
setItemSpecifics(item, listing);
setStoreFront(item, listing.getStoreCategory());
setPicture(item, listing);
setPrimaryCategory(item, listing.getCategory());
setProductLiting(item, listing.getBook().getIsbn());
item.setCategoryBasedAttributesPrefill(true);
item.setCategoryMappingAllowed(true);
BuyerPaymentMethodCodeType[] pymtMethods = new BuyerPaymentMethodCodeType[4];
pymtMethods[0] = BuyerPaymentMethodCodeType.VISA_MC;
pymtMethods[1] = BuyerPaymentMethodCodeType.DISCOVER;
pymtMethods[2] = BuyerPaymentMethodCodeType.AM_EX;
pymtMethods[3] = BuyerPaymentMethodCodeType.PAY_PAL;
item.setPaymentMethods(pymtMethods);
item.setPayPalEmailAddress("kmhenry70@hotmail.com");
item.setDispatchTimeMax(0);
setShippingDetails(item, listing);
setReturnPolicy(item);
return item;
}
private void setReturnPolicy(ItemType item) {
ReturnPolicyType rpt = new ReturnPolicyType();
rpt.setReturnsAcceptedOption("ReturnsAccepted");
rpt.setExtendedHolidayReturns(true);
rpt.setRefundOption("MoneyBack");
rpt.setReturnsWithinOption("Days_30");
rpt.setShippingCostPaidByOption("Buyer");
item.setReturnPolicy(rpt);
}
private void setShippingDetails(ItemType item, Listing listing) {
ShippingDetailsType sdt = new ShippingDetailsType();
CalculatedShippingRateType csrt = new CalculatedShippingRateType();
csrt.setOriginatingPostalCode("40065");
MeasureType w, d, l;
w = new MeasureType();
d = new MeasureType();
l = new MeasureType();
w.setUnit("in");
d.setUnit("in");
l.setUnit("in");
w.setValue(listing.getBook().getWidth());
d.setValue(listing.getBook().getDepth());
l.setValue(listing.getBook().getHeight());
csrt.setPackageDepth(d);
csrt.setPackageWidth(w);
csrt.setPackageLength(l);
MeasureType weightMajor, weightMinor;
weightMajor = new MeasureType();
weightMinor = new MeasureType();
weightMajor.setUnit("lb");
weightMinor.setUnit("oz");
weightMajor.setValue(listing.getBook().getWeightMajor());
weightMinor.setValue(listing.getBook().getWeightMinor());
csrt.setWeightMajor(weightMajor);
csrt.setWeightMinor(weightMinor);
csrt.setShippingPackage(ShippingPackageCodeType.PACKAGE_THICK_ENVELOPE);
csrt.setShippingIrregular(true);
sdt.setCalculatedShippingRate(csrt);
sdt.setGlobalShipping(true);
InternationalShippingServiceOptionsType ss = new InternationalShippingServiceOptionsType();
ss.setShippingServicePriority(1);
ss.setShippingService("USPSFirstClassMailInternational");
String[] values = new String[1];
values[0] = "WorldWide";
ss.setShipToLocation(values);
sdt.setInternationalShippingServiceOption(0, ss);
sdt.setShippingType(ShippingTypeCodeType.FLAT_DOMESTIC_CALCULATED_INTERNATIONAL);
ShippingServiceOptionsType[] sso = new ShippingServiceOptionsType[2];
sso[0].setShippingServicePriority(1);
sso[0].setShippingService("USPSMedia");
sso[1].setShippingServicePriority(2);
sso[1].setShippingService("USPSPriorityFlatRateEnvelope");
AmountType samt = new AmountType();
samt.setCurrencyID(CurrencyCodeType.USD);
samt.setValue(0.00);
sso[0].setShippingServiceCost(samt);
AmountType samt2 = new AmountType();
samt2.setCurrencyID(CurrencyCodeType.USD);
samt2.setValue(4.95);
sdt.setShippingServiceOptions(sso);
item.setShippingDetails(sdt);
}
private void setProductLiting(ItemType item, String isbn) {
ProductListingDetailsType pldt = new ProductListingDetailsType();
pldt.setISBN(isbn);
item.setProductListingDetails(pldt);
}
private void setPrimaryCategory(ItemType item, String category) {
CategoryType ct = new CategoryType();
ct.setCategoryID(category);
item.setPrimaryCategory(ct);
}
private void setPicture(ItemType item, Listing listing) {
PictureDetailsType pdt = new PictureDetailsType();
pdt.setGalleryType(GalleryTypeCodeType.GALLERY);
String[] imageURLS = new String[12];
for (int i = 0; i < 12; i++) {
imageURLS[i] = "http://kmhenry70.com/images/" + listing.getBook().getAsin() + ".jpg";
}
pdt.setPictureURL(imageURLS);
item.setPictureDetails(pdt);
}
private void setItemSpecifics(ItemType item, Listing listing) {
NameValueListArrayType itemSpecificsArrayType = new NameValueListArrayType();
ArrayList<NameValueListType> itemSpecificsArray = new ArrayList<>();
for (NameValuePair pair : listing.getNvps()) {
NameValueListType itemSpecific = new NameValueListType();
itemSpecific.setName(pair.getName());
itemSpecific.setValue(new String[]{pair.getValue()});
itemSpecificsArray.add(itemSpecific);
}
itemSpecificsArrayType.setNameValueList(itemSpecificsArray.toArray(new NameValueListType[itemSpecificsArray.size()]));
item.setItemSpecifics(itemSpecificsArrayType);
}
private void setStoreFront(ItemType item, long storeCategory) {
StorefrontType storeFront = new StorefrontType();
storeFront.setStoreCategoryID(storeCategory);
item.setStorefront(storeFront);
}
private void setPrice(ItemType item, Double price) {
AmountType amt = new AmountType();
amt.setCurrencyID(CurrencyCodeType.USD);
amt.setValue(price);
item.setStartPrice(amt);
}
}
|
package io.github.nucleuspowered.nucleus;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.github.nucleuspowered.nucleus.modules.core.config.CoreConfigAdapter;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.HoverAction;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColor;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyle;
import org.spongepowered.api.text.format.TextStyles;
import org.spongepowered.api.text.serializer.TextSerializers;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
public class ChatUtil {
private final NucleusPlugin plugin;
private final Pattern urlParser =
Pattern.compile("(?<first>(^|\\s))(?<colour>(&[0-9a-flmnork])+)?(?<url>(http(s)?://)?([A-Za-z0-9]+\\.)+[A-Za-z0-9]{2,}\\S*)",
Pattern.CASE_INSENSITIVE);
private final Pattern tokenParser = Pattern.compile("^\\{\\{(?<capture>[\\S]+)}}", Pattern.CASE_INSENSITIVE);
private final Pattern tokenParserLookAhead = Pattern.compile("(?=\\{\\{(?<capture>[\\S]+)}})", Pattern.CASE_INSENSITIVE);
private final Pattern enhancedUrlParser =
Pattern.compile("(?<first>(^|\\s))(?<colour>(&[0-9a-flmnork])+)?"
+ "((?<url>(http(s)?://)?([A-Za-z0-9]+\\.)+[A-Za-z0-9]{2,}\\S*)|"
+ "(?<specialUrl>(\\[(?<msg>.+)\\]\\((?<sUrl>(http(s)?://)?([A-Za-z0-9]+\\.)+[A-Za-z0-9]{2,}[^\\s)]*)\\)))|"
+ "(?<specialCmd>(\\[(?<sMsg>.+)\\]\\((?<sCmd>/.+)\\))))",
Pattern.CASE_INSENSITIVE);
private CoreConfigAdapter cca = null;
public static final StyleTuple EMPTY = new StyleTuple(TextColors.NONE, TextStyles.NONE);
public ChatUtil(NucleusPlugin plugin) {
this.plugin = plugin;
}
public final Text getMessageFromTemplate(String templates, CommandSource cs, final boolean trimTrailingSpace) {
return getMessageFromTemplate(Lists.newArrayList(templates), cs, trimTrailingSpace, Maps.newHashMap(), Maps.newHashMap()).get(0);
}
public final Text getMessageFromTemplateWithVariables(String templates, CommandSource cs, final boolean trimTrailingSpace, Map<String, Object> variables) {
return getMessageFromTemplate(Lists.newArrayList(templates), cs, trimTrailingSpace, Maps.newHashMap(), variables).get(0);
}
public final List<Text> getMessageFromTemplate(List<String> templates, CommandSource cs, final boolean trimTrailingSpace) {
return getMessageFromTemplate(templates, cs, trimTrailingSpace, Maps.newHashMap(), Maps.newHashMap());
}
public final Text getMessageFromTemplate(String templates, CommandSource cs, final boolean trimTrailingSpace,
Map<String, Function<CommandSource, Optional<Text>>> tokensArray, Map<String, Object> variables) {
return getMessageFromTemplate(Lists.newArrayList(templates), cs, trimTrailingSpace, tokensArray, variables).get(0);
}
public final List<Text> getMessageFromTemplate(List<String> templates, CommandSource cs, final boolean trimTrailingSpace,
Map<String, Function<CommandSource, Optional<Text>>> tokensArray, Map<String, Object> variables) {
List<Text> texts = Lists.newArrayList();
templates.forEach(template -> {
StyleTuple st = new StyleTuple(TextColors.WHITE, TextStyles.NONE);
boolean trimNext = trimTrailingSpace;
Text.Builder tb = Text.builder();
String[] items = tokenParserLookAhead.split(template);
Matcher tokenCheck = tokenParser.matcher("");
for (String textElement : items) {
if (tokenCheck.reset(textElement).find(0)) {
textElement = textElement.replace(tokenCheck.group(), "");
String tokenName = tokenCheck.group("capture");
// Token processing here.
Optional<Text> tokenResult;
if (tokensArray.containsKey(tokenName.toLowerCase())) {
tokenResult = tokensArray.get(tokenName.toLowerCase()).apply(cs);
} else {
tokenResult = plugin.getTokenHandler().getTextFromToken(tokenName, cs, variables);
}
if (tokenResult.isPresent()) {
tb.append(Text.builder().color(st.colour).style(st.style).append(tokenResult.get()).build());
} else {
tb.append(Text.EMPTY);
}
trimNext = false;
}
if (trimNext) {
textElement = textElement.replaceAll("^\\s+", "");
}
if (!textElement.isEmpty()) {
// Just convert the colour codes, but that's it.
Text r = TextSerializers.FORMATTING_CODE.deserialize(textElement);
tb.append(Text.of(st.colour, st.style, r));
st = getLastColourAndStyle(r, st);
trimNext = false;
}
}
texts.add(tb.build());
});
return texts;
}
public Text addLinksToText(Text message, @Nullable Player player) {
return addLinksToAmpersandFormattedString(TextSerializers.FORMATTING_CODE.serialize(message), player, enhancedUrlParser);
}
public Text addUrlsToAmpersandFormattedString(String message) {
return addLinksToAmpersandFormattedString(message, null, urlParser);
}
public Text addLinksToAmpersandFormattedString(String message, @Nullable Player player, Pattern parser) {
Preconditions.checkNotNull(message, "message");
if (message.isEmpty()) {
return Text.EMPTY;
}
Matcher m = parser.matcher(message);
if (!m.find()) {
return TextSerializers.FORMATTING_CODE.deserialize(message);
}
List<Text> texts = Lists.newArrayList();
String remaining = message;
StyleTuple st = ChatUtil.EMPTY;
do {
// We found a URL. We split on the URL that we have.
String[] textArray = remaining.split(parser.pattern(), 2);
Text first = Text.builder().color(st.colour).style(st.style)
.append(TextSerializers.FORMATTING_CODE.deserialize(textArray[0])).build();
// Add this text to the list regardless.
texts.add(first);
// If we have more to do, shove it into the "remaining" variable.
if (textArray.length == 2) {
remaining = textArray[1];
} else {
remaining = null;
}
// Get the last colour & styles
String colourMatch = m.group("colour");
if (colourMatch != null && !colourMatch.isEmpty()) {
first = TextSerializers.FORMATTING_CODE.deserialize(m.group("colour") + " ");
}
st = getLastColourAndStyle(first, st);
// Build the URL
String whiteSpace = m.group("first");
if (m.group("url") != null) {
String url = m.group("url");
texts.add(getTextForUrl(url, url, whiteSpace, st));
} else if (m.group("specialUrl") != null) {
String url = m.group("sUrl");
String msg = m.group("msg");
texts.add(getTextForUrl(url, msg, whiteSpace, st));
} else {
// Must be rules.
String cmd = m.group("sCmd");
String msg = m.group("sMsg");
if (player != null) {
cmd = cmd.replace("{{player}}", player.getName());
}
msg = String.join("", whiteSpace, msg);
texts.add(Text.builder(msg).color(st.colour).style(st.style)
.onHover(TextActions.showText(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("chat.command.click", cmd)))
.onClick(TextActions.runCommand(cmd))
.build());
}
} while (remaining != null && m.find());
// Add the last bit.
if (remaining != null) {
texts.add(Text.builder().color(st.colour).style(st.style)
.append(TextSerializers.FORMATTING_CODE.deserialize(remaining)).build());
}
// Join it all together.
return Text.join(texts);
}
private Text getTextForUrl(String url, String msg, String whiteSpace, StyleTuple st) {
String toParse = TextSerializers.FORMATTING_CODE.stripCodes(url);
if (!whiteSpace.isEmpty()) {
msg = String.join("", whiteSpace, msg);
}
try {
URL urlObj;
if (!toParse.startsWith("http:
urlObj = new URL("http://" + toParse);
} else {
urlObj = new URL(toParse);
}
return Text.builder(msg).color(st.colour).style(st.style)
.onHover(TextActions.showText(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("chat.url.click", url)))
.onClick(TextActions.openUrl(urlObj))
.build();
} catch (MalformedURLException e) {
// URL parsing failed, just put the original text in here.
initCoreConfigAdapter();
plugin.getLogger().warn(plugin.getMessageProvider().getMessageWithFormat("chat.url.malformed", url));
if (this.cca.getNodeOrDefault().isDebugmode()) {
e.printStackTrace();
}
return Text.builder(url).color(st.colour).style(st.style).build();
}
}
public StyleTuple getLastColourAndStyle(Text text, @Nullable StyleTuple current) {
List<Text> texts = flatten(text);
TextColor tc = TextColors.NONE;
TextStyle ts = TextStyles.NONE;
for (int i = texts.size() - 1; i > -1; i
// If we have both a Text Colour and a Text Style, then break out.
if (tc != TextColors.NONE && ts != TextStyles.NONE) {
break;
}
if (tc == TextColors.NONE) {
tc = texts.get(i).getColor();
}
if (ts == TextStyles.NONE) {
ts = texts.get(i).getStyle();
}
}
if (current == null) {
return new StyleTuple(tc, ts);
}
return new StyleTuple(tc != TextColors.NONE ? tc : current.colour, ts != TextStyles.NONE ? ts : current.style);
}
private List<Text> flatten(Text text) {
List<Text> texts = Lists.newArrayList(text);
if (!text.getChildren().isEmpty()) {
text.getChildren().forEach(x -> texts.addAll(flatten(x)));
}
return texts;
}
public Text addCommandToName(CommandSource p) {
Text.Builder text = Text.builder(p.getName());
if (p instanceof User) {
return addCommandToNameInternal(text, (User)p);
}
return text.build();
}
public Text addCommandToDisplayName(CommandSource p) {
Text name = getName(p);
if (p instanceof User) {
return addCommandToNameInternal(name, (User)p);
}
return name;
}
private Text addCommandToNameInternal(Text name, User user) {
return addCommandToNameInternal(name.toBuilder(), user);
}
private Text addCommandToNameInternal(Text.Builder name, User user) {
initCoreConfigAdapter();
String cmd = cca.getNodeOrDefault().getCommandOnNameClick();
if (cmd == null || cmd.isEmpty()) {
return name.build();
}
if (!cmd.startsWith("/")) {
cmd = "/" + cmd;
}
if (!cmd.endsWith(" ")) {
cmd = cmd + " ";
}
final String commandToRun = cmd.replaceAll("\\{\\{player\\}\\}", user.getName());
Optional<HoverAction<?>> ha = name.getHoverAction();
Text.Builder hoverAction;
if (ha.isPresent() && (ha.get() instanceof HoverAction.ShowText)) {
HoverAction.ShowText h = (HoverAction.ShowText)ha.get();
hoverAction = h.getResult().toBuilder();
hoverAction.append(Text.NEW_LINE);
} else {
hoverAction = Text.builder();
}
hoverAction.append(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("name.hover.command", commandToRun));
return name.onClick(TextActions.suggestCommand(commandToRun)).onHover(TextActions.showText(hoverAction.toText())).build();
}
private Text getName(CommandSource cs) {
if (cs instanceof Player) {
return plugin.getNameUtil().getName((Player)cs);
}
return Text.of(cs.getName());
}
private void initCoreConfigAdapter() {
if (this.cca == null) {
this.cca = plugin.getInjector().getInstance(CoreConfigAdapter.class);
}
}
public static final class StyleTuple {
public final TextColor colour;
public final TextStyle style;
StyleTuple(TextColor colour, TextStyle style) {
this.colour = colour;
this.style = style;
}
}
}
|
package com.dumptruckman.minecraft.actionmenu;
import org.bukkit.Effect;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.Image;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Map;
import java.util.WeakHashMap;
/**
* A menu, which contains a menu model (the menu items) and manages the selection of menu items.
* <p/>
* This is the main class for menus in ActionMenuPlus. This and {@link MenuView} are the only classes you must track
* externally.
* <p/>
* This menu is backed by a {@link MenuModel} which contains all of the menu items and functions similarly to an
* {@link java.util.ArrayList}.
* <p/>
* All of the methods for manipulating the selection of the menu are available here. Additionally, some simple methods
* exist here for manipulating the model of the menu. For more advanced model operations refer to the model returned
* by {@link #getModel()}.
* <p/>
* As Menu extends {@link MenuItem} it is important to note that a Menu may be added to the contents of another menu!
* Anyone implementing a {@link MenuView} should take this into considering as you may want to display a nested menu
* entirely differently.
*/
public class Menu extends MenuItem implements Iterable<MenuItem> {
private final boolean multiSelection;
private final boolean wrapSelections;
@NotNull
private final Map<Player, MenuSelector> menuSelectorMap;
@NotNull
private MenuModel model;
/**
* Creates a new Menu with the given menu item text and an empty model.
* <p/>
* This Menu will have a single selection for all users and the selector will wrap around the contents of the menu.
* See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
*/
@NotNull
public static Menu newMenu(@NotNull final String title) {
return new Menu(title);
}
/**
* Creates a new Menu with the given menu item text and model.
* <p/>
* This Menu will have a single selection for all users and the selector will wrap around the contents of the menu.
* See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
* @param model the model to use for the menu which holds the menu items.
*/
@NotNull
public static Menu newMenu(@NotNull final String title, @NotNull final MenuModel model) {
return new Menu(title, model);
}
/**
* Creates a new Menu with the given menu item text and an empty model.
* <p/>
* This Menu will have a unique selection for each user and the selector will wrap around the contents of the menu.
* See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
*/
@NotNull
public static Menu newMultiSelectorMenu(@NotNull final String title) {
return new Menu(title, new MenuModel(), true, true);
}
/**
* Creates a new Menu with the given menu item text and model.
* <p/>
* This Menu will have a unique selection for each user and the selector will wrap around the contents of the menu.
* See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
* @param model the model to use for the menu which holds the menu items.
*/
@NotNull
public static Menu newMultiSelectorMenu(@NotNull final String title, @NotNull final MenuModel model) {
return new Menu(title, model, true, true);
}
/**
* Creates a new Menu with the given menu item text and an empty model.
* <p/>
* This Menu will have a single selection for all users and the selector will not wrap around the contents of the
* menu. See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection
* wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
*/
@NotNull
public static Menu newNoWrapMenu(@NotNull final String title) {
return new Menu(title, new MenuModel(), false, false);
}
/**
* Creates a new Menu with the given menu item text and model.
* <p/>
* This Menu will have a unique selection for each user and the selector will not wrap around the contents of the
* menu. See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection
* wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
* @param model the model to use for the menu which holds the menu items.
*/
@NotNull
public static Menu newNoWrapMenu(@NotNull final String title, @NotNull final MenuModel model) {
return new Menu(title, model, false, false);
}
/**
* Creates a new Menu with the given menu item text and an empty model.
* <p/>
* This Menu will have a unique selection for each user and the selector will not wrap around the contents of the
* menu. See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection
* wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
*/
@NotNull
public static Menu newNoWrapMultiSelectorMenu(@NotNull final String title) {
return new Menu(title, new MenuModel(), true, false);
}
/**
* Creates a new Menu with the given menu item text and model.
* <p/>
* This Menu will have a single selection for all users and the selector will not wrap around the contents of the
* menu. See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection
* wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
* @param model the model to use for the menu which holds the menu items.
*/
@NotNull
public static Menu newNoWrapMultiSelectorMenu(@NotNull final String title, @NotNull final MenuModel model) {
return new Menu(title, model, true, false);
}
/**
* Constructs a Menu with the given menu item text and an empty model.
* <p/>
* This Menu will have a single selection for all users and the selector will wrap around the contents of the menu.
* See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
*/
protected Menu(@NotNull final String title) {
this(title, new MenuModel());
}
/**
* Constructs a Menu with the given menu item text and model.
* <p/>
* This Menu will have a single selection for all users and the selector will wrap around the contents of the menu.
* See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
* @param model the model to use for the menu which holds the menu items.
*/
protected Menu(@NotNull final String title, @NotNull final MenuModel model) {
this(title, model, false, true);
}
/**
* Constructs a Menu with the given menu item text and model.
* <p/>
* With this constructor you may specify whether or not to use a single selection for all users or a unique
* selection for each user. You may also specify whether the menu selection should wrap around the menu contents.
* See {@link com.dumptruckman.minecraft.actionmenu.MenuSelector#isWrapping()} for details on selection wrapping.
*
* @param title the text of this menu which can act as it's title or what it will appear as in other menus.
* @param model the model to use for the menu which holds the menu items.
* @param multiSelection true to use a unique selection for every menu user or false to use a single selection for
* all users.
* @param wrapSelections true to enable selection wrapping. See {@link MenuSelector#isWrapping()} for details on
* selection wrapping.
*/
protected Menu(@NotNull final String title, @NotNull final MenuModel model,
final boolean multiSelection, final boolean wrapSelections) {
super(title);
this.model = model;
this.multiSelection = multiSelection;
this.wrapSelections = wrapSelections;
if (!multiSelection) {
menuSelectorMap = new HashMap<Player, MenuSelector>(1);
} else {
menuSelectorMap = new WeakHashMap<Player, MenuSelector>();
}
setupSelectors(model);
}
private void setupSelectors(@NotNull final MenuModel model) {
if (!multiSelection) {
menuSelectorMap.put(null, new MenuSelector(model, wrapSelections));
} else {
menuSelectorMap.clear();
}
}
/**
* Gets the selected item for the given user.
*
* @param user the user to get the selected item for.
* @return the selected item of the menu for the given user or null if no item is selected.
*/
@Nullable
public final MenuItem getSelectedItem(@NotNull final Player user) {
return getSelector(user).getSelectedItem();
}
/**
* Gets the selected index for the given user.
* <p/>
* A less-than-zero results indicates that there no valid selection for the menu for the given user.
*
* @param user the user to get the selected index for.
* @return the selected index of the menu for the given user.
*/
public final int getSelectedIndex(@NotNull final Player user) {
return getSelector(user).getSelectedIndex();
}
/**
* Selects the next <em>selectable</em> item in the model for the given user, wrapping to the beginning if
* {@link MenuSelector#isWrapping()} returns true.
*
* @param user The user who is changing the selection.
*/
public final void selectNext(@NotNull final Player user) {
getSelector(user).selectNext();
}
/**
* Selects the previous <em>selectable</em> item in the model for the given user, wrapping to the end if
* {@link MenuSelector#isWrapping()} returns true.
*
* @param user The user who is changing the selection.
*/
public final void selectPrevious(@NotNull final Player user) {
getSelector(user).selectPrevious();
}
/**
* Selects the specified index for the given user.
* <p/>
* If the specified index is outside the bounds of the model or points to a non-selectable item, this will do
* nothing and the selection index will remain as it was.
*
* @param user The user who is changing the selection.
* @param index the index to select.
*/
public final void selectIndex(@NotNull final Player user, final int index) {
getSelector(user).selectIndex(index);
}
/**
* Clears the current selection for the given user.
* <p/>
* This will cause {@link #getSelectedItem(org.bukkit.entity.Player)} to return null.
*
* @param user the user to clear the selection for.
*/
public final void clearSelection(@NotNull final Player user) {
getSelector(user).clearSelection();
}
/**
* Gets the selector for the given user.
* <p/>
* If this menu is not using multi-selector mode, this will always return the same object. However, changing the
* menu's model with {@link #setModel(MenuModel)} will cause new selectors to be created.
*
* @param user the user to get the selector for.
* @return the menu selector for the given user.
*/
@NotNull
private MenuSelector getSelector(@NotNull final Player user) {
if (!multiSelection) {
return menuSelectorMap.get(null);
} else {
if (!menuSelectorMap.containsKey(user)) {
menuSelectorMap.put(user, new MenuSelector(model, wrapSelections));
}
return menuSelectorMap.get(user);
}
}
/**
* Gets the model for this menu.
* <p/>
* This model allows you to perform more advanced operations on the list of menu items contained in this menu.
*
* @return the model for this menu.
*/
@NotNull
public final MenuModel getModel() {
return model;
}
/**
* Sets the model for this menu.
*
* @param model the new model to use for this menu.
*/
public final void setModel(@NotNull final MenuModel model) {
this.model = model;
this.setupSelectors(model);
}
/** {@inheritDoc} */
@Override
public ListIterator<MenuItem> iterator() {
return getModel().iterator();
}
/**
* Adds a new menu item to this menu.
* <p/>
* The new item will be added to the end of the list.
*
* @param item the item to add.
* @return this menu for method chaining.
*/
@NotNull
public Menu addItem(@NotNull final MenuItem item) {
getModel().add(item);
return this;
}
/**
* Gets the menu item at the specified index.
*
* @param index the index of the item to retrieve.
* @return the menu item at the specified index or null if the index is not within the bounds of the model.
*/
@Nullable
public MenuItem getItem(final int index) {
if (index >= 0 && index < getModel().size()) {
return getModel().get(index);
}
return null;
}
/**
* Returns the number of menu items in this menu's model.
* If this model contains more than Integer.MAX_VALUE items, returns Integer.MAX_VALUE.
*
* @return the numbers of menu items in this menu's model.
*/
public int size() {
return getModel().size();
}
/**
* Performs the action defined by {@link MenuItem#getAction()} for the currently selected MenuItem for the given
* user.
* <p/>
* Does nothing if selected menu item has no action (null) or there is no valid selected menu item.
*
* @param user the player that activated this MenuItem.
*/
public void performSelectedAction(@NotNull final Player user) {
final MenuItem item = getSelectedItem(user);
if (item != null) {
item.performAction(user);
}
}
/** {@inheritDoc} */
@NotNull
@Override
public Menu setAction(@NotNull final Action action) {
return (Menu) super.setAction(action);
}
/** {@inheritDoc} */
@NotNull
@Override
public Menu setSelectable(final boolean selectable) {
return (Menu) super.setSelectable(selectable);
}
/** {@inheritDoc} */
@NotNull
@Override
public Menu setText(@NotNull final String text) {
return (Menu) super.setText(text);
}
/** {@inheritDoc} */
@Override
public Menu setImage(@Nullable final Image image) {
return (Menu) super.setImage(image);
}
/** {@inheritDoc} */
@Override
public Menu setItemStack(@Nullable final ItemStack itemStack) {
return (Menu) super.setItemStack(itemStack);
}
/** {@inheritDoc} */
@Override
public Menu setBlock(@Nullable final Block block) {
return (Menu) super.setBlock(block);
}
/** {@inheritDoc} */
@Override
public Menu setEffect(@Nullable final Effect effect) {
return (Menu) super.setEffect(effect);
}
}
|
package it.near.sdk.Communication;
import android.content.Context;
import android.os.Looper;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.auth.AuthenticationException;
import it.near.sdk.GlobalState;
import it.near.sdk.Utils.ULog;
/**
* Contains a static method to send trackings
* @author cattaneostefano
*/
public class NearNetworkUtil {
public static final String TAG = "NearNetworkUtil";
/**
* Send tracking information to the back-end.
* @param context the app context.
* @param url the tracking url.
* @param body the HTTP request body.
*/
public static void sendTrack(Context context, String url, String body){
// TODO not tested
NearAsyncHttpClient httpClient = new NearAsyncHttpClient();
try {
httpClient.nearPost(context, url, body, new JsonHttpResponseHandler(){
@Override
public void setUsePoolThread(boolean pool) {
super.setUsePoolThread(true);
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
ULog.d(TAG, "Tracking data sent.");
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
ULog.d(TAG, "Tracking data not sent. Error: " + statusCode);
}
});
} catch (AuthenticationException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/*
GlobalState.getInstance(context).getRequestQueue().add(
new CustomJsonRequest(context, Request.Method.POST, url, body, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
ULog.d(TAG, "Tracking data sent.");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
ULog.d(TAG, "Tracking data not sent. Error: " + error.toString());
}
})
);
*/
}
/**
* Send tracking information to the back-end. Since every component sends tracking data to different endpoints, the url is a parameter.
* @param context the application context.
* @param url the tracking url.
* @param body the HHTP request body.
* @param handler the response handler.
* @throws UnsupportedEncodingException
* @throws AuthenticationException
*/
public static void sendTrack (Context context, String url, String body, JsonHttpResponseHandler handler) throws UnsupportedEncodingException, AuthenticationException {
NearAsyncHttpClient httpClient = new NearAsyncHttpClient();
httpClient.nearPost(context, url, body, handler);
}
}
|
package com.elmakers.mine.bukkit.spell;
import com.elmakers.mine.bukkit.action.ActionHandler;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.utility.Target;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
public class ActionSpell extends BrushSpell
{
private Map<String, ActionHandler> actions = new HashMap<String, ActionHandler>();
private boolean undoable = false;
private boolean requiresBuildPermission = false;
private ActionHandler currentHandler = null;
private int workThreshold = 500;
@Override
protected void processResult(SpellResult result, ConfigurationSection castParameters) {
if (!result.isSuccess())
{
ActionHandler handler = actions.get(result.name().toLowerCase());
if (handler != null)
{
handler.start(currentCast, castParameters);
}
}
super.processResult(result, castParameters);
}
@Override
public SpellResult onCast(ConfigurationSection parameters)
{
currentCast.setWorkAllowed(workThreshold);
SpellResult result = SpellResult.CAST;
currentHandler = actions.get("cast");
ActionHandler downHandler = actions.get("alternate_down");
ActionHandler upHandler = actions.get("alternate_up");
ActionHandler sneakHandler = actions.get("alternate_sneak");
workThreshold = parameters.getInt("work_threshold", 500);
if (downHandler != null && isLookingDown())
{
result = SpellResult.ALTERNATE_DOWN;
currentHandler = downHandler;
}
else if (upHandler != null && isLookingUp())
{
result = SpellResult.ALTERNATE_UP;
currentHandler = upHandler;
}
else if (sneakHandler != null && mage.isSneaking())
{
result = SpellResult.ALTERNATE_SNEAK;
currentHandler = sneakHandler;
}
if (currentHandler != null)
{
try {
result = result.max(currentHandler.start(currentCast, parameters));
} catch (Exception ex) {
controller.getLogger().log(Level.WARNING, "Spell cast failed", ex);
result = SpellResult.FAIL;
try {
currentHandler.finish(currentCast);
} catch (Exception finishException) {
controller.getLogger().log(Level.WARNING, "Failed to clean up failed spell", finishException);
}
}
}
return result;
}
@Override
public void load(ConfigurationSection data)
{
super.load(data);
for (ActionHandler handler : actions.values())
{
handler.loadData(getMage(), data);
}
}
@Override
public void save(ConfigurationSection data)
{
super.save(data);
for (ActionHandler handler : actions.values())
{
handler.saveData(getMage(), data);
}
}
@Override
protected void loadTemplate(ConfigurationSection template)
{
usesBrush = false;
undoable = false;
requiresBuildPermission = false;
castOnNoTarget = true;
if (template.contains("actions"))
{
ConfigurationSection parameters = template.getConfigurationSection("parameters");
ConfigurationSection actionsNode = template.getConfigurationSection("actions");
Collection<String> actionKeys = actionsNode.getKeys(false);
for (String actionKey : actionKeys)
{
ActionHandler handler = new ActionHandler();
handler.load(actionsNode, actionKey);
handler.initialize(parameters);
usesBrush = usesBrush || handler.usesBrush();
undoable = undoable || handler.isUndoable();
requiresBuildPermission = requiresBuildPermission || handler.requiresBuildPermission();
actions.put(actionKey, handler);
}
}
undoable = template.getBoolean("undoable", undoable);
super.loadTemplate(template);
}
@Override
public boolean isUndoable()
{
return undoable;
}
@Override
public void getParameters(Collection<String> parameters) {
super.getParameters(parameters);
for (ActionHandler handler : actions.values()) {
handler.getParameterNames(parameters);
}
}
@Override
public void getParameterOptions(Collection<String> examples, String parameterKey) {
super.getParameterOptions(examples, parameterKey);
for (ActionHandler handler : actions.values()) {
handler.getParameterOptions(examples, parameterKey);
}
}
@Override
public String getMessage(String messageKey, String def) {
String message = super.getMessage(messageKey, def);
if (currentHandler != null) {
message = currentHandler.transformMessage(message);
}
return message;
}
@Override
public boolean requiresBuildPermission() {
return requiresBuildPermission;
}
}
|
package it.polimi.hegira.adapters.cassandra;
import it.polimi.hegira.models.CassandraColumn;
import it.polimi.hegira.models.CassandraModel;
import it.polimi.hegira.utils.CassandraTypesUtils;
import it.polimi.hegira.utils.Constants;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.hamcrest.Condition.Step;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.schemabuilder.Alter;
import com.datastax.driver.core.schemabuilder.CreateIndex;
import com.datastax.driver.core.schemabuilder.CreateIndex.CreateIndexOn;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.core.schemabuilder.SchemaStatement;
/**
* This class manages a single Table.
* Used to check columns, alter the table if necessary, and perform inserts into Cassandra.
* @author Andrea Celli
*
*/
public class Table {
private static Logger log = Logger.getLogger(Table.class);
private String tableName;
private List<String> columns;
//the current session
private Session session;
//flag that signals if the table has been altered
private boolean changed;
//the prepared statement for the actual table configuration (with all its columns)
private PreparedStatement defaultPrepared;
/**
* Initialize all the variables and creates the new table in cassandra.
* When created the table contains only the column for the id values.
* @param tableName
*/
public Table(String tableName){
this.tableName=tableName;
columns=new ArrayList<String>();
//retrieves the unique session from the session manager
session=SessionManager.getSessionManager().getSession();
setChanged(false);
createInitialTable(tableName);
}
/**
* This methods inserts a row in the table.
* This methods is synchronized in order to avoid conflicts due to different threads changing the same table.
*
* @param row - the row to be insterted
* @throws ClassNotFoundException, InvalidParameterException
*/
public synchronized void insert(CassandraModel row) throws ClassNotFoundException,InvalidParameterException{
List<CassandraColumn> colsToInsert=row.getColumns();
//number of column contained in the row
int rowSize=colsToInsert.size();
//the string used to build the prepared statement
//it contains columns names and gets progressively update
//the String will have the format: name1, name2, name3, name4....
String statementString;
//the array of objects to be inserted into the db
//the size of the array is rowSize+1 because we have to include the key
Object[] values=new Object[rowSize+1];
//set the primary key
statementString="id";
values[0]=row.getKeyValue();
//CHECK id the table contains the other columns
//at the same time build the names string and the object array
for(int i=1;i<rowSize+1;i++){
//update names string
String name=colsToInsert.get(i-1).getColumnName();
statementString=statementString + ", "+name;
//update objects array
values[i]=colsToInsert.get(i-1).getColumnValue();
//check if the table already contains the column
if(!columns.contains(name)){
//THE TABLE NEEDS TO BE UPDATED
alterTable(name,colsToInsert.get(i-1).getValueType(),colsToInsert.get(i-1).isIndexed());
setChanged(true);
}
}
//retrieve the statement to be executed
PreparedStatement execStatement=getPreparedStatement(statementString,rowSize);
//bing the statement with the array of objects that have to be inserted
BoundStatement bind=execStatement.bind(values);
//insert
session.execute(bind);
}
/**
* This method creates the table in the cassandra db.
* the initial table will contain only an id column
* @param tableName2
*/
private void createInitialTable(String tableName) {
session.execute(
"CREATE TABLE IF NOT EXISTS " + tableName + " ( " + Constants.DEFAULT_PRIMARY_KEY_NAME + " varchar PRIMARY KEY );");
//update the list of column names contained in the table
columns.add(Constants.DEFAULT_PRIMARY_KEY_NAME);
defaultPrepared=createPreparedStatement(Constants.DEFAULT_PRIMARY_KEY_NAME,0);
}
/**
* Returns a new prepared statement to insert a new row with the given columns.
* @param columnNames
* @param rowSize - number of columns contained in the row (without id)
* @return PreparedStatement
*/
private PreparedStatement createPreparedStatement(
String columnNames,int rowSize) {
String completeStatementString=packString(columnNames,rowSize);
return session.prepare(completeStatementString);
}
/**
* Takes as input the string containing column names in the format:
* name1, name2, name3...
* Pack the string with the remaining parts in order to use it to build a preparedStatement to perform an insert.
* The final string will be in the form:
* "INSERT INTO <tableName> (<name1>, <name2>, <name3>) VALUES (?,?,?)"
* @param columnNames
* @param rowSize - number of columns contained in the row (without id)
* @return the complete string for a prepared statement that performs an insert
*/
private String packString(String columnNames,int rowSize) {
String completeString="INSERT INTO "+tableName+" ( "+columnNames+" ) VALUES ( ";
//there's at least a ? for the id
String questionMarks="?";
//add other values question marks for remaining columns
for(int i=0;i<rowSize;i++){
questionMarks=questionMarks+",?";
}
completeString=completeString+questionMarks+" ) ";
return completeString;
}
/**
* Returns a prepared statement and eventually updates the default prepared statement.
* 1) table has been altered-->create and set a new default statement, return the default statement
* 2) table has not been altered
* 2.1)same number of columns-->return the default PreparedStatement (reuse to increase efficiency)
* 2.2)lower number of columns-->compute and return a new prepared statement (without setting it as default)
* @param columnNames
* @param rowSize
* @return PreparedStatement
*/
private PreparedStatement getPreparedStatement(String columnNames,
int rowSize) {
//table has been changed
if(isChanged()){
defaultPrepared=createPreparedStatement(columnNames, rowSize);
return defaultPrepared;
}else{
//not changed and same number of columns
//+1 takes into account the id
if(rowSize+1==columns.size()){
return defaultPrepared;
}else{
//lower number of columns but no table changes
return createPreparedStatement(columnNames, rowSize);
}
}
}
/**
* This method performs an alter on the table in order to introduce a new column.
*
* @param name - name of the new column
* @param valueType - the string representing the type of the new column
* @param indexed - true if the column has to be indexed
*/
private void alterTable(String name, String valueType, boolean indexed) throws ClassNotFoundException,InvalidParameterException{
SchemaStatement alter;
try{
//build the alter
alter=SchemaBuilder
.alterTable(tableName)
.addColumn(name)
.type(CassandraTypesUtils.getCQLDataType(valueType));
//execute the alter
session.execute(alter);
//create a new index if needed
if(indexed){
SchemaStatement createIndex=SchemaBuilder
.createIndex(name+"_index")
.onTable(tableName)
.andColumn(name);
session.execute(createIndex);
}
//TODO: altre catch
}catch(ClassNotFoundException | InvalidParameterException ex){
log.error("Error while altering table: "+tableName+"\nStackTrace:\n"+ex.getStackTrace());
throw ex;
}
}
private boolean isChanged() {
return changed;
}
private void setChanged(boolean changed) {
this.changed = changed;
}
}
|
package jaci.openrio.toast.lib.registry;
import edu.wpi.first.wpilibj.*;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* The Registrar is a simple class designed to get rid of Allocation exceptions in code, where if multiple
* instances of a Motor Controller, DIO, or Analog interface are created with the same port, WPILib throws
* a big fat error in your face. To solve this, the Registrar keeps one instance of each when you request it,
* allowing for multiple accesses, but not multiple constructions.
*
* @param <ID> The type to use for the Identifier. In most cases, this is an integer.
* @param <Type> The type to store in this registrar. This is the superclass
*/
public class Registrar<ID, Type> {
private volatile HashMap<ID, Type> registered = new HashMap<>();
/**
* Fetch an object from the Registrar, or create it if it doesn't exist yet.
*
* @param id The ID to store the object under
* @param clazz The Class (Type) of the object you are inserting (subclass of Type)
* @param creator The lambda function that will construct a new instance of the object if it doesn't
* already exist in the registrar
* @param <T> The type to insert / fetch from the registrar. This is a subclass of the Registrar's Type
* @return The object in the registrar / the new object created.
*/
public synchronized <T extends Type> T fetch(ID id, Class<T> clazz, Supplier<T> creator) {
Type in_register = registered.get(id);
if (in_register == null) {
T instance = creator.get();
registered.put(id, instance);
return instance;
} else {
if (clazz.isAssignableFrom(in_register.getClass()))
return (T) in_register;
else
throw new IllegalStateException("An object already exists in the Registrar with the given ID, " +
"but is of a different type! Expected: " + clazz.getName() + ", but got: " + in_register.getClass().getName());
}
}
/**
* Return the stream of the underlying Registrar hashmap. Use this to directly manipulate the registrar
*/
public synchronized Stream<Map.Entry<ID, Type>> stream() {
return registered.entrySet().stream();
}
// -- STATICS -- //
public static volatile Registrar<Integer, PWM> pwmRegistrar = new Registrar<>();
public static volatile Registrar<Integer, SpeedController> canRegistrar = new Registrar<>();
public static volatile Registrar<Integer, DigitalSource> dioRegistrar = new Registrar<>();
public static volatile Registrar<Integer, Relay> relayRegistrar = new Registrar<>();
public static volatile Registrar<Integer, AnalogInput> aiRegistrar = new Registrar<>();
public static volatile Registrar<Integer, AnalogOutput> aoRegistrar = new Registrar<>();
/**
* Get a DigitalOutput instance from the Registrar
* @param port the DIO port to use
*/
public static DigitalOutput digitalOutput(int port) {
return dioRegistrar.fetch(port, DigitalOutput.class, () -> { return new DigitalOutput(port); });
}
/**
* Get a DigitalInput instance from the Registrar
* @param port the DIO port to use
*/
public static DigitalInput digitalInput(int port) {
return dioRegistrar.fetch(port, DigitalInput.class, () -> { return new DigitalInput(port); });
}
/**
* Get an AnalogOutput instance from the Registrar
* @param port the AO port to use
*/
public static AnalogOutput analogOutput(int port) {
return aoRegistrar.fetch(port, AnalogOutput.class, () -> { return new AnalogOutput(port); });
}
/**
* Get an AnalogInput instance from the Registrar
* @param port the AI port to use
*/
public static AnalogInput analogInput(int port) {
return aiRegistrar.fetch(port, AnalogInput.class, () -> { return new AnalogInput(port); });
}
/**
* Get a Spike style Relay instance from the Registrar
* @param relayPort the Relay port to use
*/
public static Relay relay(int relayPort) {
return relayRegistrar.fetch(relayPort, Relay.class, () -> { return new Relay(relayPort); });
}
// -- Motor Controllers -- //
/**
* Get a Talon [SR] instance from the Registrar
* @param pwmPort the PWM Port to use
*/
public static Talon talon(int pwmPort) {
return pwmRegistrar.fetch(pwmPort, Talon.class, () -> { return new Talon(pwmPort); });
}
/**
* Get a Talon SRX [PWM] instance from the Registrar
* @param pwmPort the PWM Port to use
*/
public static TalonSRX talonSRX(int pwmPort) {
return pwmRegistrar.fetch(pwmPort, TalonSRX.class, () -> { return new TalonSRX(pwmPort); });
}
/**
* Get a Jaguar [PWM] instance from the Registrar
* @param pwmPort the PWM port to use
*/
public static Jaguar jaguar(int pwmPort) {
return pwmRegistrar.fetch(pwmPort, Jaguar.class, () -> { return new Jaguar(pwmPort); });
}
/**
* Get a Victor instance from the Registrar
* @param pwmPort the PWM port to use
*/
public static Victor victor(int pwmPort) {
return pwmRegistrar.fetch(pwmPort, Victor.class, () -> { return new Victor(pwmPort); });
}
/**
* Get a Victor SP instance from the Registrar
* @param pwmPort the PWM port to use
*/
public static VictorSP victorSP(int pwmPort) {
return pwmRegistrar.fetch(pwmPort, VictorSP.class, () -> { return new VictorSP(pwmPort); });
}
/**
* Get a Spark instance from the Registrar
* @param pwmPort the PWM port to use
*/
public static Spark spark(int pwmPort) {
return pwmRegistrar.fetch(pwmPort, Spark.class, () -> { return new Spark(pwmPort); });
}
/**
* Get an SD540 instance from the Registrar
* @param pwmPort the PWM port to use
*/
public static SD540 sd540(int pwmPort) {
return pwmRegistrar.fetch(pwmPort, SD540.class, () -> { return new SD540(pwmPort); });
}
/**
* Get a Talon SRX [CAN] instance from the Registrar
* @param canID the CAN Device ID to use
*/
public static CANTalon canTalon(int canID) {
return canRegistrar.fetch(canID, CANTalon.class, () -> { return new CANTalon(canID); });
}
/**
* Get a Jaguar [CAN] instance from the Registrar
* @param canID the CAN Device ID to use
*/
public static CANJaguar canJaguar(int canID) {
return canRegistrar.fetch(canID, CANJaguar.class, () -> { return new CANJaguar(canID); });
}
}
|
package com.facebook.litho;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaFlexDirection;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.support.annotation.StyleRes;
import android.support.v4.util.Pools;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.ExploreByTouchHelper;
import android.view.View;
import com.facebook.litho.annotations.OnCreateTreeProp;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaMeasureMode;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaNodeAPI;
import com.facebook.yoga.YogaMeasureOutput;
/**
* {@link ComponentLifecycle} is a stateless singleton object that defines how {@link Component}
* instances calculate their layout bounds and mount elements, among other things. This is the
* base class from which all new component types inherit.
*
* In most cases, the {@link ComponentLifecycle} class will be automatically generated by the
* annotation processor at build-time based on your spec class and you won't have to deal with
* it directly when implementing new component types.
*/
public abstract class ComponentLifecycle implements EventDispatcher {
private static final AtomicInteger sComponentId = new AtomicInteger();
private static final int DEFAULT_MAX_PREALLOCATION = 15;
private boolean mPreallocationDone;
public enum MountType {
NONE,
DRAWABLE,
VIEW,
}
public interface StateContainer {}
private static final YogaBaselineFunction sBaselineFunction = new YogaBaselineFunction() {
public float baseline(YogaNodeAPI cssNode, float width, float height) {
final InternalNode node = (InternalNode) cssNode.getData();
return node.getComponent()
.getLifecycle()
.onMeasureBaseline(node.getContext(), (int) width, (int) height);
}
};
private static final YogaMeasureFunction sMeasureFunction = new YogaMeasureFunction() {
private final Pools.SynchronizedPool<Size> mSizePool =
new Pools.SynchronizedPool<>(2);
private Size acquireSize(int initialValue) {
Size size = mSizePool.acquire();
if (size == null) {
size = new Size();
}
size.width = initialValue;
size.height = initialValue;
return size;
}
private void releaseSize(Size size) {
mSizePool.release(size);
}
@Override
@SuppressLint("WrongCall")
@SuppressWarnings("unchecked")
public long measure(
YogaNodeAPI cssNode,
float width,
YogaMeasureMode widthMode,
float height,
YogaMeasureMode heightMode) {
final InternalNode node = (InternalNode) cssNode.getData();
final DiffNode diffNode = node.areCachedMeasuresValid() ? node.getDiffNode() : null;
final Component<?> component = node.getComponent();
final int widthSpec;
final int heightSpec;
ComponentsSystrace.beginSection("measure:" + component.getSimpleName());
widthSpec = SizeSpec.makeSizeSpecFromCssSpec(width, widthMode);
heightSpec = SizeSpec.makeSizeSpecFromCssSpec(height, heightMode);
node.setLastWidthSpec(widthSpec);
node.setLastHeightSpec(heightSpec);
int outputWidth = 0;
int outputHeight = 0;
if (Component.isNestedTree(component)) {
final InternalNode nestedTree = LayoutState.resolveNestedTree(node, widthSpec, heightSpec);
outputWidth = nestedTree.getWidth();
outputHeight = nestedTree.getHeight();
} else if (diffNode != null
&& diffNode.getLastWidthSpec() == widthSpec
&& diffNode.getLastHeightSpec() == heightSpec) {
outputWidth = (int) diffNode.getLastMeasuredWidth();
outputHeight = (int) diffNode.getLastMeasuredHeight();
} else {
final Size size = acquireSize(Integer.MIN_VALUE /* initialValue */);
try {
component.getLifecycle().onMeasure(
node.getContext(),
node,
widthSpec,
heightSpec,
size,
component);
if (size.width < 0 || size.height < 0) {
throw new IllegalStateException(
"MeasureOutput not set, ComponentLifecycle is: " + component.getLifecycle());
}
outputWidth = size.width;
outputHeight = size.height;
if (node.getDiffNode() != null) {
node.getDiffNode().setLastWidthSpec(widthSpec);
node.getDiffNode().setLastHeightSpec(heightSpec);
node.getDiffNode().setLastMeasuredWidth(outputWidth);
node.getDiffNode().setLastMeasuredHeight(outputHeight);
}
} finally {
releaseSize(size);
}
}
node.setLastMeasuredWidth(outputWidth);
node.setLastMeasuredHeight(outputHeight);
ComponentsSystrace.endSection();
return YogaMeasureOutput.make(outputWidth, outputHeight);
}
};
private final int mId;
protected ComponentLifecycle() {
mId = sComponentId.incrementAndGet();
}
int getId() {
return mId;
}
Object createMountContent(ComponentContext c) {
return onCreateMountContent(c);
}
|
package com.github.egonw.ops4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AbstractOPS4JClient {
private HttpClient httpClient = null;
private String appID;
private String appKey;
protected String server;
public AbstractOPS4JClient(String server, String appID, String appKey, HttpClient httpclient)
throws MalformedURLException {
this.server = server;
if (!this.server.endsWith("/")) this.server += "/";
new URL(this.server); // validate the server URL
this.appID = appID;
this.appKey = appKey;
this.httpClient = httpclient;
if (httpclient == null) this.httpClient = new DefaultHttpClient();
}
protected String runRequest(String call, Map<String, String> params, Object... objects)
throws ClientProtocolException, IOException, HttpException {
params.put("app_id", appID);
params.put("app_key", appKey);
params.put("_format", "ttl"); // the default
String requestUrl = createRequest(call, params, objects);
System.out.println("Call: " + requestUrl);
HttpGet httppost = new HttpGet(requestUrl);
httppost.addHeader("User-Agent", "ops4j (https://github.com/egonw/ops4j)");
HttpResponse response = httpClient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) throw new HttpException(
"Expected HTTP 200, but got a " + statusCode + ": " + statusLine.getReasonPhrase()
);
HttpEntity responseEntity = response.getEntity();
InputStream in = responseEntity.getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(in, writer, "UTF-8");
in.close();
return writer.toString();
}
private String createRequest(String server, Map<String, String> params, Object... objects)
throws UnsupportedEncodingException {
StringBuffer requestURI = new StringBuffer();
for (int i=0; i<objects.length; i++) {
Object obj = objects[i];
if (obj instanceof ResponseFormat) {
params.put("_format", ((ResponseFormat)obj).getOPSCode());
} else if (obj instanceof ParameterValue) {
ParameterValue value = (ParameterValue)obj;
params.put(value.getParameter().getName(), value.getValue());
}
}
if (!params.isEmpty()) {
requestURI.append(server).append('?');
boolean beyondFirst = false;
for (String key : params.keySet()) {
if (beyondFirst) requestURI.append('&');
requestURI.append(key).append('=').append(URLEncoder.encode(params.get(key), "UTF-8"));
beyondFirst = true;
}
}
return requestURI.toString();
}
}
|
package mimickal.mc.floodgate;
import com.enderio.core.common.fluid.IFluidWrapper;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class TileEntityFloodgate extends TileEntity implements IFluidWrapper {
public static final int MAX_CAPACITY = Fluid.BUCKET_VOLUME;
private FluidStack heldFluid;
/**
* This is called prior to moving any fluid. I assume this is used to
* determine how much of a fluid the floodgate should be allowed to
* accept (if any).
*
* @param resource The fluid being offered to the floodgate
* @return How much of the fluid the floodgate can accept (maybe?)
*/
@Override
public int offer(FluidStack resource) {
// TODO eventually make sure this fluid is usable (i.e. does it have source blocks we can place?)
return MAX_CAPACITY;
}
/**
* This is what the floodgate does when the offered fluid is actually
* consumed.
*
* @param fluid The fluid filling the floodgate
* @return The amount of fluid the floodgate accepted
*/
@Override
public int fill(FluidStack fluid) {
int amountFilled = Math.min(fluid.amount, MAX_CAPACITY);
// TODO check that we have enough fluid to place a source block
heldFluid = new FluidStack(fluid, amountFilled);
BlockPos placeAt = findNearestFreeSpot();
if (placeAt == null) {
return 0; // Don't actually consume fluid if we can't find a place to put it
} else {
placeFluid(fluid, placeAt);
return amountFilled;
}
}
/**
* The draining version of "offer". Pipes use this function to figure out
* if they can extract any fluid from the floodgate.
*
* The floodgate drains itself by placing fluid into the world,
* therefore it never has any fluid available for draining.
*
* @return null
*/
@Nullable
@Override
public FluidStack getAvailableFluid() {
return null;
}
/**
* This function contains the logic for how a floodgate responds to having
* fluid extracted from it.
* The floodgate should never have fluid extracted from it.
*
* @param resource Unused. Not sure what this is for.
* @return null
*/
@Nullable
@Override
public FluidStack drain(FluidStack resource) {
return null;
}
/**
* FIXME figure out what this actually does
* Seriously I have no idea.
* @return
*/
@Nonnull
@Override
public List<ITankInfoWrapper> getTankInfoWrappers() {
return new ArrayList<>();
}
private void placeFluid(FluidStack fluid, BlockPos placeAt) {
Block fluidSourceBlock = fluid.getFluid().getBlock();
this.worldObj.setBlockState(placeAt, fluidSourceBlock.getDefaultState());
}
@Nullable
private BlockPos findNearestFreeSpot() {
BlockPos testPos = this.pos.down();
if (this.worldObj.isAirBlock(testPos)) {
return testPos;
} else {
return null;
}
//this.worldObj.getBlockState(testPos).getBlock().
}
}
|
package mooklabs.laputamod.items;
import java.util.List;
import mooklabs.laputamod.LapMain;
import mooklabs.mookcore.MLib;
import net.minecraft.block.Block;
import net.minecraft.block.IGrowable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraftforge.event.entity.player.BonemealEvent;
import cpw.mods.fml.common.eventhandler.Event.Result;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/**
* DONT PLAY WITH THIS FOR AWHILE
*
* @author moolabs
*/
public class VoluciteNecklace extends Item {
public VoluciteNecklace() {
super();
setUnlocalizedName("voluciteNecklace");
setTextureName(LapMain.itemfold + ":voluciteNecklace");
this.setMaxStackSize(1);
}
/**
* i think this is like onCrafted, not creative spawned
*/
@Override
public void onCreated(ItemStack itemStack, World world, EntityPlayer player) {
register(itemStack, player, true);
}
@SideOnly(Side.CLIENT)
@Override
public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean par4) {
if (itemStack.stackTagCompound != null) {
String owner = itemStack.stackTagCompound.getString("owner");
if (itemStack.stackTagCompound.getBoolean("creativeSpawned")) list.add("Sole Owner: " + owner);
else list.add("Owner: " + owner);
if (owner.equals(player.getCommandSenderName())) {// if belongs to player
list.add(EnumChatFormatting.GREEN + "Grinder: " + "Researched");
} else {// if doesent belong to player
list.add(EnumChatFormatting.RED + "This Necklace belongs to someone with power," + " return it to any admin since you can't use it");
}
} else {// if has no tags
list.add(EnumChatFormatting.BLUE + "NO INFO!");
list.add(EnumChatFormatting.RED + "Right click to register");
}
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*
* @Override public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { if (!world.isRemote) { if (itemStack.stackTagCompound == null)
* register(itemStack, player, false); if (player.capabilities.isCreativeMode) { itemStack.stackTagCompound.setBoolean("creativeSpawned", true); } } return
* itemStack; }
*/
public void register(ItemStack itemStack, EntityPlayer player, boolean wasCrafted) {
if (itemStack.stackTagCompound == null) {
itemStack.stackTagCompound = new NBTTagCompound();// create tag
itemStack.stackTagCompound.setBoolean("creativeSpawned", wasCrafted);
itemStack.stackTagCompound.setBoolean("launch", true);
itemStack.stackTagCompound.setBoolean("launchMob", true);
itemStack.stackTagCompound.setBoolean("hover", true);
itemStack.stackTagCompound.setBoolean("dig", true);
itemStack.stackTagCompound.setInteger("power", 50);
itemStack.stackTagCompound.setInteger("maxPower", 50);
itemStack.stackTagCompound.setInteger("cooldown", 0);
itemStack.stackTagCompound.setInteger("maxCooldown", 50);
itemStack.stackTagCompound.setString("owner", player.getCommandSenderName());
} else {// has allready been registed
if (itemStack.stackTagCompound.getBoolean("creativeSpawned")) {
MLib.printToPlayer("Sorry this has restricted access by " + itemStack.stackTagCompound.getString("owner"));
return;// if it cannot be claimed by another player(ie for admins)
} else {
// switch owner?
itemStack.stackTagCompound.setString("owner", player.getCommandSenderName());// register to name
}
}
}
// when player types in chat stuff happens!
@Override
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {
if (itemStack.stackTagCompound == null) register(itemStack, player, false);
// NOT YET BECUAE ITS ITEM BASEDelse if (itemStack.stackTagCompound.getString("owner").equals(player.getCommandSenderName())) register(itemStack, player, false);
NBTTagCompound tagC = itemStack.stackTagCompound;
if (tagC.getInteger("power") <= 0) return itemStack;
tagC.setInteger("power", tagC.getInteger("power") - tagC.getInteger("cooldown"));
tagC.setInteger("cooldown", tagC.getInteger("cooldown") + 1);
if (player.isSneaking()) {
String str = "";
/*
if (tagC.getString"mode".equals("launch")) {
str = "hover";
if (tagC.getBoolean("hover")) break;
}
}
else if ()
*/
switch (tagC.getString("mode")) {
case "launch":
str = "hover";
if (tagC.getBoolean("hover")) break;// bit iffy but will work later
case "hover":
str = "dig";
if (tagC.getBoolean("dig")) break;
case "dig":
str = "launchMob";
if (tagC.getBoolean("launchMob")) break;
case "launchMob":
str = "launch";
if (tagC.getBoolean("launch")) break;
default:
str = "launch";
}
MLib.printToPlayer("Effect set to" + str);
itemStack.stackTagCompound.setString("mode", str);
} else {
switch (tagC.getString("mode")) {
case "launch":
launchPlayer(player, 1.3);
break;
case "hover":
player.motionY = 0;
break;
case "dig":
dig(world, player);
break;
case "launchMob":// will change launch velocity
MLib.printToPlayer("You just need to left click on a mob to use this.");
break;
default:
MLib.printToPlayer("Shift-right click to start using");
}
}
return itemStack;
}
public void launchPlayer(EntityPlayer entityPlayer, double amt) {
Vec3 desiredDirection = entityPlayer.getLookVec();
entityPlayer.motionX = amt * desiredDirection.xCoord;
entityPlayer.motionY = amt * desiredDirection.yCoord;
entityPlayer.motionZ = amt * desiredDirection.zCoord;
}
public void dig(World w, EntityPlayer player) {
int yaw = (int) player.rotationYaw;
if (yaw < 0) // due to the yaw running a -360 to positive 360
yaw += 360; // not sure why it's that way
yaw += 22; // centers coordinates you may want to drop this line
yaw %= 360; // and this one if you want a strict interpretation of the zones
byte facing = (byte) (yaw / 90); // 360degrees divided by 45 == 8 zones
int st = 0, end = 0;
boolean nS = false;
switch (facing) {
case 0:
st = 0;
end = 10;
nS = false;
break;// south
case 1:
st = -10;
end = 0;
nS = true;
break;// west
case 2:
st = -10;
end = 0;
nS = false;
break;// north
case 3:
st = 0;
end = 10;
nS = true;
break;// east
}
int x = (int) Math.floor(player.posX);
int z = (int) Math.floor(player.posZ);
int y = (int) Math.floor(player.posY);
if (nS) for (int j = 0; j < 3; j++)
for (int i = st; i < end; i++)
breakBlock(w, x + i, y + j, z);
else for (int j = 0; j < 3; j++)
for (int i = st; i < end; i++)
breakBlock(w, x, y + j, z + i);
}
private void breakBlock(World world, int x, int y, int z) {
if (world.getBlock(x, y, z) != Blocks.bedrock) {// duh
world.getBlock(x, y, z).dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
world.setBlockToAir(x, y, z);
}
}
@Override
public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity) {
if (stack.stackTagCompound == null) return false;
if (stack.stackTagCompound.getBoolean("launchMob")) {
entity.motionY = 4;
return true;
}
return false;
}
@Override
public boolean onItemUse(ItemStack itemStack, EntityPlayer entityPlayer, World world, int par4, int par5, int par6, int par7, float par8, float par9, float par10) {
if (itemStack.stackTagCompound == null) return false;
NBTTagCompound tagC = itemStack.stackTagCompound;
if (world.getBlock(par4, par5, par6) == LapMain.solidVoluciteBlock) {
itemStack.stackTagCompound.setInteger("power", itemStack.stackTagCompound.getInteger("maxPower"));
itemStack.stackTagCompound.setInteger("cooldown", 0);
return true;
}
else if (tagC.getInteger("power") <= 0)
return false;
else if (entityPlayer.canPlayerEdit(par4, par5, par6, par7, itemStack) && applyBonemeal(itemStack, world, par4, par5, par6, entityPlayer)) {
tagC.setInteger("power", tagC.getInteger("power") - tagC.getInteger("cooldown"));
tagC.setInteger("cooldown", tagC.getInteger("cooldown") + 1);
if (!world.isRemote)
world.playAuxSFX(2005, par4, par5, par6, 0);
return true;
}
return false;
}
@Override
/**
* Called each tick as long the item is on a player inventory. Uses by maps to check if is on a player hand and update it's contents.
*/
public void onUpdate(ItemStack itemStack, World world, Entity entity, int slotNumber, boolean isHeld) {
if (itemStack.stackTagCompound == null) return;
NBTTagCompound tagC = itemStack.stackTagCompound;
if (tagC.getByte("counter") == 0) {
addPower(itemStack, 1);
addCooldown(itemStack, -1);
tagC.setByte("counter", (byte) 20);
}
tagC.setByte("counter", (byte) (tagC.getByte("counter") - 1));
}
// {{for gui mostly
public int getPower(ItemStack item) {
return item.stackTagCompound.getInteger("power");
}
public int getCooldown(ItemStack item) {
return item.stackTagCompound.getInteger("cooldown");
}
public void setPower(ItemStack item, int x) {
item.stackTagCompound.setInteger("power", x);
}
public void addPower(ItemStack item, int x) {
item.stackTagCompound.setInteger("power", item.stackTagCompound.getInteger("power") + x);
}
public void setCooldown(ItemStack item, int x) {
item.stackTagCompound.setInteger("cooldown", x);
}
public void addCooldown(ItemStack item, int x) {
item.stackTagCompound.setInteger("cooldown", item.stackTagCompound.getInteger("cooldown") + x);
}
public int getMaxPower(ItemStack item) {
return item.stackTagCompound.getInteger("maxPower");
}
public int getMaxCooldown(ItemStack item) {
return item.stackTagCompound.getInteger("maxCooldown");
}
@Override
public int getEntityLifespan(ItemStack itemStack, World world) {
return 20;
}
/**
* The bonemeal method!! :D
* @param itemstack
* @param world
* @param p_150919_2_
* @param p_150919_3_
* @param p_150919_4_
* @param player
* @return
*/
public static boolean applyBonemeal(ItemStack itemstack, World world, int p_150919_2_, int p_150919_3_, int p_150919_4_, EntityPlayer player) {
Block block = world.getBlock(p_150919_2_, p_150919_3_, p_150919_4_);
BonemealEvent event = new BonemealEvent(player, world, block, p_150919_2_, p_150919_3_, p_150919_4_);
if (MinecraftForge.EVENT_BUS.post(event)) {
return false;
}
if (event.getResult() == Result.ALLOW) {
if (!world.isRemote) {
itemstack.stackSize
}
return true;
}
if (block instanceof IGrowable) {
IGrowable igrowable = (IGrowable) block;
if (igrowable.func_149851_a(world, p_150919_2_, p_150919_3_, p_150919_4_, world.isRemote)) {
if (!world.isRemote) {
if (igrowable.func_149852_a(world, world.rand, p_150919_2_, p_150919_3_, p_150919_4_)) {
igrowable.func_149853_b(world, world.rand, p_150919_2_, p_150919_3_, p_150919_4_);
}
--itemstack.stackSize;
}
return true;
}
}
return false;
}
/**
* I might use this later to make is affect wider area<br>
* Im pretty sure this is for a block/item to use if it is not being held by a player(it has fakeplayer)
*
* @return
*/
public static boolean func_150919_a(ItemStack itemstack, World p_150919_1_, int p_150919_2_, int p_150919_3_, int p_150919_4_) {
if (p_150919_1_ instanceof WorldServer) return applyBonemeal(itemstack, p_150919_1_, p_150919_2_, p_150919_3_, p_150919_4_, FakePlayerFactory.getMinecraft((WorldServer) p_150919_1_));
return false;
}
}
|
package com.j256.ormlite.android;
import com.j256.ormlite.logger.Level;
import com.j256.ormlite.logger.LogBackend;
import com.j256.ormlite.logger.LogBackendFactory;
import com.j256.ormlite.logger.LoggerFactory;
import android.util.Log;
/**
* Log backend that delegates to the internal Android logger.
*
* <p>
* To see log messages you will do something like:
* </p>
*
* <pre>
* adb shell setprop log.tag.YourActivity VERBOSE
* </pre>
*
* <p>
* <b>NOTE:</b> Unfortunately, Android variables are limited in size so this class takes that last 23 (sic) characters
* of the class name if it is larger than 23 characters. For example, if the class is AndroidDatabaseConnection you
* would do:
* </p>
*
* <pre>
* adb shell setprop log.tag.droidDatabaseConnection VERBOSE
* </pre>
*
* <p>
* To see all log messages use:
* </p>
*
* <pre>
* adb shell setprop log.tag.simplelogging DEBUG
* </pre>
*
* @author graywatson
*/
public class AndroidLogBackend implements LogBackend {
private final static String ALL_LOGS_NAME = "ORMLite";
// check to see if the android level has changed every so often
private final static int REFRESH_LEVEL_CACHE_EVERY = 200;
private final static int MAX_TAG_LENGTH = 23;
private final String className;
// we do this because supposedly Log.isLoggable() always does IO
private volatile int levelCacheC = 0;
private final boolean levelCache[];
public AndroidLogBackend(String className) {
// get the last part of the class name
String simpleName = LoggerFactory.getSimpleClassName(className);
// make sure that our tag length is not too long
int length = simpleName.length();
if (length > MAX_TAG_LENGTH) {
simpleName = className.substring(length - MAX_TAG_LENGTH, length);
}
this.className = simpleName;
// find the maximum level value
int maxLevel = 0;
for (Level level : Level.values()) {
int androidLevel = levelToAndroidLevel(level);
if (androidLevel > maxLevel) {
maxLevel = androidLevel;
}
}
levelCache = new boolean[maxLevel + 1];
refreshLevelCache();
}
@Override
public boolean isLevelEnabled(Level level) {
// we don't care if this is not synchronized, it will be updated sooner or later and multiple updates are fine.
if (++levelCacheC >= REFRESH_LEVEL_CACHE_EVERY) {
refreshLevelCache();
levelCacheC = 0;
}
int androidLevel = levelToAndroidLevel(level);
if (androidLevel < levelCache.length) {
return levelCache[androidLevel];
} else {
return isLevelEnabledInternal(androidLevel);
}
}
@Override
public void log(Level level, String msg) {
switch (level) {
case TRACE:
Log.v(className, msg);
break;
case DEBUG:
Log.d(className, msg);
break;
/* INFO below */
case WARNING:
Log.w(className, msg);
break;
case ERROR:
Log.e(className, msg);
break;
case FATAL:
// no fatal level
Log.e(className, msg);
break;
case INFO:
default:
Log.i(className, msg);
break;
}
}
@Override
public void log(Level level, String msg, Throwable t) {
switch (level) {
case TRACE:
Log.v(className, msg, t);
break;
case DEBUG:
Log.d(className, msg, t);
break;
/* INFO below */
case WARNING:
Log.w(className, msg, t);
break;
case ERROR:
Log.e(className, msg, t);
break;
case FATAL:
// no level higher than e
Log.e(className, msg, t);
break;
case INFO:
default:
Log.i(className, msg, t);
break;
}
}
private void refreshLevelCache() {
for (Level level : Level.values()) {
int androidLevel = levelToAndroidLevel(level);
if (androidLevel < levelCache.length) {
levelCache[androidLevel] = isLevelEnabledInternal(androidLevel);
}
}
}
private boolean isLevelEnabledInternal(int androidLevel) {
// this is supposedly expensive with an IO operation for each call so we cache them into levelCache[]
return Log.isLoggable(className, androidLevel) || Log.isLoggable(ALL_LOGS_NAME, androidLevel);
}
private int levelToAndroidLevel(Level level) {
switch (level) {
case TRACE:
return Log.VERBOSE;
case DEBUG:
return Log.DEBUG;
/* INFO below */
case WARNING:
return Log.WARN;
case ERROR:
return Log.ERROR;
case FATAL:
return Log.ERROR;
case INFO:
default:
return Log.INFO;
}
}
/**
* Factory for generating AndroidLogBackend instances.
*/
public static class AndroidLogBackendFactory implements LogBackendFactory {
@Override
public LogBackend createLogBackend(String classLabel) {
return new AndroidLogBackend(classLabel);
}
}
}
|
package net.adrouet.broceliande.algo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.lang3.tuple.ImmutablePair;
import net.adrouet.broceliande.struct.DataSet;
import net.adrouet.broceliande.struct.IData;
public class RandomForest<D extends IData<R>, R extends Comparable<R>> {
private List<DecisionTree<D, R>> decisionTrees;
private Splitter<D, R> splitter;
private Bagging bagging;
private Parameter p;
/**
* Init RF with all parameter
*
* @param p
* params
*/
public RandomForest(Parameter p) {
this.decisionTrees = new ArrayList<>();
this.splitter = new Splitter(p.getK());
this.bagging = new Bagging(p.getSeed());
this.p = p;
}
/**
* Create the model whit the learning set
*
* @param learningSet
*/
public void fit(List<D> learningSet) {
// #1 Bagging
this.bagging.getStream(learningSet).limit(p.getNbTrees()).forEach(sample -> {
// #2 Build all decision tree
DecisionTree decisionTree = new DecisionTree(splitter, this.p);
// XXX
DataSet ds = new DataSet<>(sample.get(0).getClass());
ds.setData(sample);
decisionTree.compute(ds);
decisionTrees.add(decisionTree);
});
}
/**
* Set the predicted result on data
*
* @param data
* @return
*/
public R predict(D data) {
HashMap<R, Integer> votes = new HashMap<>();
// #1 voting
for (DecisionTree<D, R> tree : this.decisionTrees) {
R vote = tree.predict(data);
if (!votes.containsKey(vote)) {
votes.put(vote, new Integer(0));
}
votes.put(vote, votes.get(vote) + 1);
}
// #2 get the dominant vote
Entry<R, Integer> dominant = null;
for (Entry<R, Integer> vote : votes.entrySet()) {
if (dominant == null || dominant.getValue() < vote.getValue()) {
dominant = vote;
}
}
return dominant.getKey();
}
public List<ImmutablePair<Method, Double>> importance() {
for (DecisionTree<D, R> tree : this.decisionTrees) {
// (TODO)
}
return null;
}
}
|
package com.jmss.application.windows;
import com.jmss.domain.Member;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Optional;
// TODO disable Delete button if table is empty
// TODO disable make whole window smaller (or even remove resize ability at all)
// TODO allows correct member field changes
public class MembersWindow extends BorderPane {
private static final Logger LOGGER = LoggerFactory.getLogger(MembersWindow.class);
private final ObservableList<Member> data;
private final TabPane tabPane = new TabPane();
private final TextField firstNameField = new TextField();
private final TextField lastNameField = new TextField();
private final TableView<Member> table = new TableView<>();
public MembersWindow(List<Member> members) {
data = FXCollections.observableList(members);
setCenter(createTabPane());
setRight(createButtonPane());
}
private TabPane createTabPane() {
Tab memberTab = new Tab("Member");
memberTab.setContent(createMemberTab());
Tab memberListTab = new Tab("Member List");
memberListTab.setContent(createMemberListTab());
tabPane.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> {
LOGGER.debug("Changing tab to '{}'...", newValue.getText());
TableView.TableViewSelectionModel<Member> tableSelectionModel = table.getSelectionModel();
int index = tableSelectionModel.getSelectedIndex();
if (index >= 0) {
if (memberListTab.equals(newValue)) {
LOGGER.trace("Updating member in table...");
Member member = new Member(firstNameField.getText(), lastNameField.getText());
data.set(index, member);
} else if (memberTab.equals(newValue)) {
LOGGER.trace("Updating member's fields...");
Member member = data.get(index);
firstNameField.setText(member.getFirstName());
lastNameField.setText(member.getLastName());
}
}
}
);
tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
tabPane.getTabs().add(memberTab);
tabPane.getTabs().add(memberListTab);
return tabPane;
}
private Pane createMemberTab() {
GridPane pane = new GridPane();
pane.setPadding(new Insets(10, 10, 10, 10));
pane.setVgap(5);
pane.setHgap(5);
Label label1 = new Label("First Name:");
GridPane.setConstraints(label1, 0, 0);
pane.getChildren().add(label1);
GridPane.setConstraints(firstNameField, 1, 0);
pane.getChildren().add(firstNameField);
Label label2 = new Label("Last Name:");
GridPane.setConstraints(label2, 0, 1);
pane.getChildren().add(label2);
GridPane.setConstraints(lastNameField, 1, 1);
pane.getChildren().add(lastNameField);
return pane;
}
private Pane createMemberListTab() {
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setCellValueFactory(new PropertyValueFactory<Member, String>("firstName"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setCellValueFactory(new PropertyValueFactory<Member, String>("lastName"));
table.setEditable(true);
table.setOnMouseClicked(event -> {
LOGGER.trace("Updating member's fields via mouse...");
if (event.getClickCount() > 1) {
TableView.TableViewSelectionModel<Member> tableSelectionModel = table.getSelectionModel();
Optional.ofNullable(tableSelectionModel.getSelectedItem())
.ifPresent(member -> {
firstNameField.setText(member.getFirstName());
lastNameField.setText(member.getLastName());
SingleSelectionModel<Tab> selectionModel = tabPane.getSelectionModel();
selectionModel.select(0);
});
}
});
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol);
GridPane pane = new GridPane();
pane.setPadding(new Insets(10, 0, 10, 10));
GridPane.setHgrow(table, Priority.ALWAYS);
GridPane.setVgrow(table, Priority.ALWAYS);
pane.getChildren().addAll(table);
return pane;
}
private Node createButtonPane() {
final VBox pane = new VBox();
pane.setSpacing(5);
pane.setPadding(new Insets(40, 10, 10, 10));
Button aNew = new Button("New");
aNew.setMaxWidth(Double.MAX_VALUE);
aNew.setOnAction(e -> {
LOGGER.debug("Adding new member...");
Member match = new Member(firstNameField.getText(), lastNameField.getText());
data.add(match);
firstNameField.clear();
lastNameField.clear();
});
Button delete = new Button("Delete");
delete.setMaxWidth(Double.MAX_VALUE);
delete.setOnAction(e -> {
LOGGER.debug("Deleting member...");
int focusedIndex = table.getSelectionModel().getFocusedIndex();
if (focusedIndex >= 0)
data.remove(focusedIndex);
});
pane.getChildren().addAll(aNew, delete);
return pane;
}
}
|
package net.etalia.client.json;
import java.util.HashMap;
import java.util.Map;
import net.etalia.client.domain.AdvertisedPaginationList;
import net.etalia.client.domain.Article;
import net.etalia.client.domain.Banner;
import net.etalia.client.domain.Entity;
import net.etalia.client.domain.Journalia;
import net.etalia.client.domain.JournaliaStampAggregation;
import net.etalia.client.domain.JournaliaSuggestedAggregation;
import net.etalia.client.domain.JournaliaSystemAggregation;
import net.etalia.client.domain.Media;
import net.etalia.client.domain.PageAssignedDrafts;
import net.etalia.client.domain.PageAssignedPublished;
import net.etalia.client.domain.PageExample;
import net.etalia.client.domain.PageExampleSection;
import net.etalia.client.domain.PageLink;
import net.etalia.client.domain.PageMyContents;
import net.etalia.client.domain.PageMyDrafts;
import net.etalia.client.domain.PageQuery;
import net.etalia.client.domain.PageStamp;
import net.etalia.client.domain.PaginationList;
import net.etalia.client.domain.PublicationOwner;
import net.etalia.client.domain.PublicationSection;
import net.etalia.client.domain.PublicationStamps;
import net.etalia.client.domain.PublicationStandard;
import net.etalia.client.domain.SearchCriteria;
import net.etalia.client.domain.StampArticle;
import net.etalia.client.domain.StampPublication;
import net.etalia.client.domain.Tag;
import net.etalia.client.domain.User;
import net.etalia.client.domain.UserProfile;
import net.etalia.jalia.EntityFactory;
import net.etalia.jalia.EntityNameProvider;
import net.etalia.jalia.JsonClassData;
import net.etalia.jalia.JsonClassDataFactory;
import net.etalia.jalia.JsonClassDataFactoryImpl;
import net.etalia.jalia.JsonContext;
import net.etalia.jalia.TypeUtil;
/**
* Implements Etalia names, entity factory and class data factory.
*
*
* @author Simone Gianni <simoneg@apache.org>
*/
public class JaliaDomainFactory implements EntityNameProvider, EntityFactory, JsonClassDataFactory {
private JsonClassDataFactoryImpl classDataFactory = new JsonClassDataFactoryImpl();
private Map<Class<?>, String> nameMappingsByClass = new HashMap<Class<?>, String>();
private Map<String, Class<?>> nameMappingsByName = new HashMap<String, Class<?>>();
{
map(AdvertisedPaginationList.class, "AdvertisedPaginationList");
map(Article.class, "Article");
map(Banner.class, "Banner");
map(Journalia.class, "Journalia");
map(JournaliaSystemAggregation.class, "SystemAggregation");
map(JournaliaStampAggregation.class, "StampAggregation");
map(JournaliaSuggestedAggregation.class, "SuggestedAggregation");
map(Media.class, "Media");
map(PageAssignedDrafts.class, "PageAssignedDrafts");
map(PageAssignedPublished.class, "PageAssignedPublished");
map(PageExample.class, "PageExample");
map(PageExampleSection.class, "PageExampleSection");
map(PageLink.class, "PageLink");
map(PageMyContents.class, "PageMyContents");
map(PageMyDrafts.class, "PageMyDrafts");
map(PageQuery.class, "PageQuery");
map(PageStamp.class, "PageStamp");
map(PaginationList.class, "PaginationList");
map(PublicationOwner.class, "PublicationOwner");
map(PublicationSection.class, "PublicationSection");
map(PublicationStamps.class, "PublicationStamps");
map(PublicationStandard.class, "PublicationStandard");
map(SearchCriteria.class, "SearchCriteria");
map(StampArticle.class, "StampArticle");
map(StampPublication.class, "StampPublication");
map(Tag.class, "Tag");
map(User.class, "User");
map(UserProfile.class, "UserProfile");
}
private void map(Class<?> clazz, String name) {
nameMappingsByClass.put(clazz, name);
nameMappingsByName.put(name, clazz);
}
/**
* Uses default domain mappings for Etalia
*/
public String getEntityName(Class<?> clazz) {
String ret = nameMappingsByClass.get(clazz);
if (ret == null) {
// TODO parse an annotation?
}
return ret;
}
/**
* Uses default domain mappings for Etalia
*/
public Class<?> getEntityClass(String name) {
return nameMappingsByName.get(name);
}
public JsonClassData getClassData(Class<?> clazz, JsonContext context) {
JsonClassData ret = classDataFactory.getClassData(clazz, context);
if (!ret.isNew()) return ret;
classDataFactory.cache(clazz, ret);
return ret;
}
/**
* Uses {@link Persistent#getId()} to fetch the id.
*/
public String getId(Object entity, JsonContext context) {
if (entity instanceof Entity) {
return ((Entity) entity).getId();
} else if (entity instanceof Media) {
return ((Media) entity).getId();
}
return null;
}
public Object buildEntity(Class<?> clazz, String id, JsonContext context) {
try {
return TypeUtil.get(clazz).newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public Object prepare(Object obj, boolean serializing, JsonContext context) {
return obj;
}
public Object finish(Object obj, boolean serializing, JsonContext context) {
return obj;
}
}
|
package com.meiziaccess.AssociationTool;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Associator {
//orginalDir xml
//xmlDir xml
public List<Addresses> getAddresses(String orginalDir,String lowVideoDir,String highVideoDir,String frameDir,String xmlDir, int type) {
List<Addresses> rs=new ArrayList<>();
File root = new File(orginalDir);
File[] files = root.listFiles();
for (File file : files) {
if (file.isDirectory()) {
rs.addAll(getAddresses(file.getAbsolutePath(),lowVideoDir,highVideoDir,frameDir,xmlDir, type));
} else if (isXml(file)) {
Addresses curAddress=new Addresses();
String name="";
String keyFramePath="";
//xml,
try {
switch (type) {
case 1:
name = getName(file);
StringBuilder sb = new StringBuilder();
associatetKeyFrames(name, frameDir, sb);
keyFramePath = sb.toString();
break;
case 2:
name = getName2(file); //BTV
keyFramePath = getKeyFrameBTVorNanfang(file, frameDir);
break;
case 3:
name = getName2(file);
keyFramePath = getKeyFrameBTVorNanfang(file, frameDir);
break;
case 4:
name = getName3(file);
keyFramePath = getKeyFrameHaiWai(file, frameDir);
break;
case 5:
name = getName4(file);
System.out.println(name);
keyFramePath = getKeyFrameDianshiju(file, frameDir);
break;
default:
}
}catch (Exception e){
continue;
}
curAddress.setLowCodeVideoPath(associateVideo(name,lowVideoDir));
curAddress.setHighCodeVideoPath(associateVideo(name,highVideoDir));
curAddress.setUnCatalgedXmlPath(file.getAbsolutePath());
curAddress.setCatalgedXmlPath("");
curAddress.setName(name);
curAddress.setKeyFramePath(keyFramePath);
rs.add(curAddress);
}
}
return rs;
}
private boolean isXml(File file) {
boolean flag = false;
String str = file.getName();
String type = str.substring(str.lastIndexOf('.') + 1, str.length());
if (type.toLowerCase().equals("xml"))
flag = true;
return flag;
}
private String associateVideo(String name,String videoDir){
while(name.contains(" ")) name=name.replaceAll(" ","");
name=name.toLowerCase();
String rs=new String();
File root = new File(videoDir);
File[] files = root.listFiles();
for (File file : files) {
if(!rs.equals("")) return rs;
if (file.isDirectory()) {
rs=associateVideo(name,file.getAbsolutePath());
} else {
String filename = file.getName().replace("", "1/2").replace("", "2/2").toLowerCase();
while (filename.contains(" ")) filename=filename.replaceAll(" ","");
if (filename.contains(name)) {
return file.getAbsolutePath();
}
}
}
return "";
}
// Name
private void associatetKeyFrames(String name,String xmlDir,StringBuilder stringBuilder){
File root = new File(xmlDir);
File[] files = root.listFiles();
for (File file : files) {
if (file.isDirectory()) {
associatetKeyFrames(name,file.getAbsolutePath(),stringBuilder);
} else {
String filename = file.getName().toLowerCase();
if (filename.contains(name)) {
stringBuilder.append(file.getAbsoluteFile());
stringBuilder.append(";");
}
}
}
}
private String getName(File file) {
String name = new String();
SAXBuilder builder = new SAXBuilder();
Document doc;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
name=root.getChildText("Name");
} catch (JDOMException | IOException e) {
// TODO Auto-generated catch block
System.out.println("file: " + file.getAbsolutePath());
e.printStackTrace();
}
return name;
}
//BTV
public String getName2(File file){
String name=new String();
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
Namespace ns = root.getNamespace();
Element nameElemnet=root.getChild("List",ns).getChild("CatalogueMetaData",ns).getChild("TopUnit",ns).getChild("Name",ns);
name=nameElemnet.getText();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return name;
}
public String getName3(File file){
String name=new String();
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
Namespace ns = root.getNamespace();
Element nameElemnet=root.getChild("ImportContents",ns).getChild("CatalogueMetaData",ns).getChild("TopUnit",ns).getChild("Name",ns);
name=nameElemnet.getText();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return name;
}
public String getName4(File file){
String name=new String();
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
//Namespace ns = root.getNamespace();
Element nameElemnet=root.getChild("MetaData").getChild("Clip").getChild("ClipFiles").getChild("ClipFile");
name=nameElemnet.getAttributeValue("filename");
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return name;
}
//XML
private String getName5(File file) {
String result = new String();
SAXBuilder builder = new SAXBuilder();
Document doc;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
if(root.getAttributeValue("VideoPath").equals("")){
result = root.getChild("Program").getChild("Title").getChild("ProperTitle").getText();
}
else
result=root.getAttributeValue("VideoPath");
} catch (JDOMException | IOException e) {
// TODO Auto-generated catch block
System.out.println("file: " + file.getAbsolutePath());
e.printStackTrace();
}
return result;
}
// /temp/keyframe/a.jpg "a.jpg;"
// BTV ,';'
public String getKeyFrameBTVorNanfang(File file,String frameDir){
String name=new String();
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
Namespace ns = root.getNamespace();
List<Element> le=root.getChild("List",ns).getChild("MetaData",ns).getChildren("Attributes",ns);
for (Element e:le) {
List<Element> attrElementList=e.getChildren("AttributeItem",ns);
for (Element ae : attrElementList){
if(ae.getChildText("ItemCode",ns).equals("STRKEYFRAMEFILE")){
String[] ss=ae.getChildText("Value",ns).split("/");
if(ss.length>0){
String desPath=findFilePath(ss[ss.length-1],frameDir);
if(desPath.length()>0) {
name += desPath;
name += ";";
}
}
}
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return name;
}
public String getKeyFrameHaiWai(File file,String frameDir){
String name=new String();
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
Namespace ns = root.getNamespace();
List<Element> le=root.getChild("ImportContents",ns).getChild("MetaData",ns).getChildren("Attributes",ns);
for (Element e:le) {
List<Element> attrElementList=e.getChildren("AttributeItem",ns);
for (Element ae : attrElementList){
if(ae.getChildText("ItemCode",ns).equals("")){
String[] ss=ae.getChildText("Value",ns).split("/");
if(ss.length>0){
String desPath=findFilePath(ss[ss.length-1],frameDir);
if(desPath.length()>0) {
name += desPath;
name += ";";
}
}
}
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return name;
}
public String getKeyFrameDianshiju(File file,String frameDir){
String name=new String();
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(file);
Element root = doc.getRootElement();
//Namespace ns = root.getNamespace();
List<Element> keyframeEl = root.getChild("MetaData").getChild("KeyFrames").getChildren("KeyFrame");
for (Element e:keyframeEl) {
String desPath=findFilePath( e.getChildText("FileName"),frameDir);
if(desPath.length()>0) {
name += desPath;
name += ";";
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return name;
}
public String findFilePath(String name,String Dir){
String rs=new String();
File root = new File(Dir);
File[] files = root.listFiles();
for (File file : files) {
if(!rs.equals("")) return rs;
if (file.isDirectory()) {
rs=findFilePath(name,file.getAbsolutePath());
} else {
String filename = file.getName().toLowerCase().replaceAll(" ","");
if (filename.equals(name.toLowerCase().replaceAll(" ",""))) {
rs= file.getAbsolutePath();
}
}
}
return rs;
}
}
|
package com.minespaceships.mod.spaceship;
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.Vector;
import javax.vecmath.Vector3d;
import com.google.common.collect.ImmutableList;
import com.minespaceships.mod.blocks.EnergyBlock;
import com.minespaceships.mod.blocks.EngineBlock;
import com.minespaceships.mod.blocks.NavigatorBlock;
import com.minespaceships.mod.blocks.PhaserBlock;
import com.minespaceships.mod.blocks.ShieldBlock;
import com.minespaceships.mod.overhead.ChatRegisterEntity;
import com.minespaceships.mod.target.Target;
import com.minespaceships.mod.worldanalysation.WorldMock;
import com.minespaceships.util.BlockCopier;
import com.minespaceships.util.PhaserUtils;
import com.minespaceships.util.Vec3Op;
import energyStrategySystem.EnergyStrategySystem;
import energyStrategySystem.IEnergyC;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.BlockDoor.EnumDoorHalf;
import net.minecraft.block.BlockWallSign;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.util.Vec3i;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
public class Spaceship implements Serializable{
private World world;
private BlockMap blockMap;
private SpaceshipAssembler assembler;
private EnergyStrategySystem energySystem;
private MovementTarget target;
private Vec3 position;
private boolean isResolved = true;
private static final String positionsKey = "Positions";
private static final String containsTargetKey = "containsTarget";
private static final String targetPositionKey = "TargetPos";
private static final String targetTurnKey = "TargetTurn";
private static final String actualPositionKey = "APK";
private boolean canBeRemoved = true;
public static final int maxShipSize = 27000;
public Spaceship(BlockPos initial, World world) throws Exception{
blockMap = new BlockMap(initial);
blockMap = SpaceshipMath.getConnectedPositions(initial, world, maxShipSize);
if(blockMap == null){
throw new Exception("Ship is too huge or connected to the Ground");
}
this.world = world;
initializeBase();
}
public Spaceship(BlockMap blocks, World world){
blockMap = blocks;
this.world = world;
initializeBase();
}
public Spaceship(NBTTagCompound s, String firstKey, World world)throws Exception {
this.world = world;
//world needs to be loaded first to prevent null pointer
this.readFromNBT(s, firstKey);
initializeBase();
}
private void initializeBase(){
if(assembler == null){
assembler = new SpaceshipAssembler(blockMap.getOrigin());
refreshParts();
}
energySystem = new EnergyStrategySystem(assembler, world);
if(position == null){
position = blockMap.getMiddleVec();
}
//Shipyard.getShipyard(world).addShip(this);
}
public BlockPos getOrigin(){
return blockMap.getMiddle();
}
public Vec3 getOriginVec(){
return blockMap.getMiddleVec();
}
public BlockPos getBlockMapOrigin(){
return blockMap.getOrigin();
}
public BlockPos getRandomPos(Random rand){
ArrayList<BlockPos> positions = getPositions();
float index = (float)(positions.size()-1)*rand.nextFloat();
return positions.get((int)(index));
}
public BlockPos getMaxPos(){
return blockMap.getMaxPos();
}
public BlockPos getMinPos(){
return blockMap.getMinPos();
}
public boolean canBeRemoved(){
return canBeRemoved;
}
public ArrayList<BlockPos> getPositions(){
return blockMap.getPositions();
}
public BlockMap getBlockMap(){
return blockMap;
}
public int getSize(){
return blockMap.getSize();
}
public float getHardness(){
return blockMap.getHardnessSum(world);
}
public int getNavigatorCount(){
return assembler.getParts(NavigatorBlock.class).size();
}
public int getPhaserCount(){
return assembler.getParts(PhaserBlock.class).size();
}
public int getShieldsCount(){
return assembler.getParts(ShieldBlock.class).size();
}
public int getEnginesCount(){
return assembler.getParts(EngineBlock.class).size();
}
public int getActiveGeneratorsCount(){
return energySystem.getActive(EnergyBlock.class, true).size();
}
public int getActivePhaserCount(){
return energySystem.getActive(PhaserBlock.class, true).size();
}
public int getActiveShieldsCount(){
return energySystem.getActive(ShieldBlock.class, true).size();
}
public int getActiveEnginesCount(){
return energySystem.getActive(EngineBlock.class, true).size();
}
public float getCapacity(){
return energySystem.getEnergy(false);
}
public float getEnergy(){
return energySystem.getEnergy();
}
public void activatePhasers(){
energySystem.changeAll(PhaserBlock.class, true);
}
public void deactivatePhasers(){
energySystem.changeAll(PhaserBlock.class, false);
}
public void activateShields(){
energySystem.changeAll(ShieldBlock.class, true);
}
public void deactivateShields(){
energySystem.changeAll(ShieldBlock.class, false);
}
public void activateEngines(){
energySystem.changeAll(EngineBlock.class, true);
}
public void deactivateEngines(){
energySystem.changeAll(EngineBlock.class, false);
}
public void balanceEnergy(){
energySystem.refresh(true);
}
public void deactivateEverything(){
energySystem.changeAll(IEnergyC.class, false);
}
public int getDistanceToGround(){
ArrayList<BlockPos> positions = getPositions();
int minHeight = Integer.MAX_VALUE;
for(BlockPos pos : positions){
BlockPos current = pos.add(0,-1,0);
int height = 1;
while(current.getY() > 0 && world.isAirBlock(current)){
current = current.add(0,-1,0);
height++;
}
if(!containsBlock(current)){
if(height < minHeight){
minHeight = height;
}
}
}
if(minHeight != Integer.MAX_VALUE){
return minHeight-1;
} else {
return 0;
}
}
public void shootPhaserAt(Target target){
ArrayList<BlockPos> phasers = energySystem.getActive(PhaserBlock.class, true);
Random rand = new Random();
boolean hasShot = false;
target.getNewTarget(world);
while(!phasers.isEmpty()){
int index = (int)((float)phasers.size()*rand.nextFloat());
BlockPos pos = phasers.get(index);
phasers.remove(index);
Block block = world.getBlockState(pos).getBlock();
if(block instanceof PhaserBlock){
((PhaserBlock)block).stopShooting(pos, world);
if(!hasShot){
hasShot = ((PhaserBlock)block).shoot(pos, world, ShipInformation.getShipStrength(this), target);
}
}
}
}
public void setTarget(BlockPos position){
//moveTo(Vec3Op.subtract(position, origin), 0, world);
this.position = getOriginVec();
target = new MovementTarget(position, 0, world);
}
public void setTarget(BlockPos position, int turn){
//moveTo(Vec3Op.subtract(position, origin), world);
this.position = getOriginVec();
target = new MovementTarget(position, turn, world);
}
public void moveTo(BlockPos addDirection) {
moveTo(addDirection, world, 0);
}
public void moveTo(BlockPos addDirection, World world) {
moveTo(addDirection, world, 0);
}
public void moveTo(BlockPos addDirection, int turn, World world) {
moveTo(addDirection, world, turn);
}
public void moveToTarget(){
moveTo(target.getTarget(), target.getWorld(), target.getTurn());
target = null;
}
public BlockPos getShipLengthToAdd(EntityPlayer player){
int length = 0;
if(getMaxPos().getZ()-getMinPos().getZ() > getMaxPos().getX()-getMinPos().getX())
{
length = getMaxPos().getZ()-getMinPos().getZ() + 1;
}
else
{
length = getMaxPos().getX()-getMinPos().getX() + 1;
}
System.out.println("DIIIIIEEE LNGEEE IST : " + length);
if (getFacing()==EnumFacing.EAST){
return new BlockPos (length,0,0);
} else if (getFacing()==EnumFacing.WEST){
return new BlockPos (-(length),0,0);
} else if (getFacing()==EnumFacing.NORTH){
return new BlockPos (0,0,-(length));
} else if (getFacing()==EnumFacing.SOUTH){
return new BlockPos (0,0,length);
}
else {
int playerRotation = MathHelper.floor_double((double)(player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
if (playerRotation==EnumFacing.EAST.getHorizontalIndex()){
return new BlockPos (length,0,0);
} else if (playerRotation==EnumFacing.WEST.getHorizontalIndex()){
return new BlockPos (-(length),0,0);
} else if (playerRotation==EnumFacing.NORTH.getHorizontalIndex()){
return new BlockPos (0,0,-(length));
} else{
return new BlockPos (0,0,length);
}
}
}
public EnumFacing getFacing(){
int north=0;
int south=0;
int east=0;
int west=0;
ArrayList<BlockPos> facingListActive= energySystem.getActive(EngineBlock.class, true);
ArrayList<BlockPos> facingListDeactive= energySystem.getActive(EngineBlock.class, false);
for (BlockPos p: facingListActive){
EnumFacing e=Turn.getEnumFacing(world.getBlockState(p));
if(e==EnumFacing.NORTH){
north+=1;
} else if (e==EnumFacing.SOUTH){
south+=1;
} else if( e==EnumFacing.EAST){
east+=1;
}
else if( e==EnumFacing.WEST){
west+=1;
}
}
for (BlockPos p: facingListDeactive){
EnumFacing e=Turn.getEnumFacing(world.getBlockState(p));
if(e==EnumFacing.NORTH){
north+=1;
} else if (e==EnumFacing.SOUTH){
south+=1;
} else if( e==EnumFacing.EAST){
east+=1;
}
else if( e==EnumFacing.WEST){
west+=1;
}
}
if(north>south&& north>west&& north> east){
return EnumFacing.NORTH.getOpposite();
} else if(south>north&&south>west&&south>east){
return EnumFacing.SOUTH.getOpposite();
} else if (east>north&&east>south&&east>west){
return EnumFacing.EAST.getOpposite();
} else if (west>north&&west>south&&west>east){
return EnumFacing.WEST.getOpposite();
}
return EnumFacing.UP;
}
private void moveTo(BlockPos addDirection, World world, final int turn){
if(!canMove(addDirection, world, turn)){
return;
}
/**
* Moves the spaceship to a target position.
* These method check also if the target position is a valid position.
* @param position
*/
public void move(BlockPos position){
if(position == null){
throw new IllegalArgumentException("The target position can not be null");
}
double x = position.getX();
double y = position.getY();
double z = position.getZ();
double maxWorldHeight = this.world.getHeight();
BlockPos maxShipHeight = getMaxPos();
BlockPos minShipHeight = getMinPos();
double shipHeight = maxShipHeight.getY()-minShipHeight.getY();
//Troubleshooting for the world height out of bounds.
if(position.getY() >= maxWorldHeight){
this.setTarget(new BlockPos(x,(maxWorldHeight-shipHeight),z));
}
if(position.getY() <= 0){
this.setTarget(new BlockPos(x,(0+shipHeight),z));
}
//Valid position
this.setTarget(new BlockPos(x,y,z));
}
public boolean canMove(BlockPos addDirection, World targetWorld, int turn){
if(world != targetWorld){
return true;
}
double maxWorldHeight = this.world.getHeight();
BlockPos maxPos = getMaxPos();
BlockPos minPos = getMinPos();
BlockPos nextMaxPos = Turn.getRotatedPos(maxPos, getOrigin(), addDirection, turn);
BlockPos nextMinPos = Turn.getRotatedPos(minPos, getOrigin(), addDirection, turn);
if(nextMaxPos.getY() > maxWorldHeight || nextMinPos.getY() < 0){
return false;
}
return !isInsideShipRectangle(nextMaxPos) && !isInsideShipRectangle(nextMinPos);
}
public boolean isInsideShipRectangle(BlockPos pos){
BlockPos max = getMaxPos();
BlockPos min = getMinPos();
return pos.getX() >= min.getX() &&
pos.getY() >= min.getY() &&
pos.getZ() >= min.getZ() &&
pos.getX() <= max.getX() &&
pos.getY() <= max.getY() &&
pos.getZ() <= max.getZ();
}
public void update(){
Side side = FMLCommonHandler.instance().getEffectiveSide();
Vector<BlockPos> movedPositions = move();
if(side == Side.CLIENT){
if(movedPositions != null){
Random rand = new Random();
for(BlockPos pos : movedPositions){
world.spawnParticle(EnumParticleTypes.PORTAL, pos.getX()+rand.nextFloat(), pos.getY()+rand.nextFloat(), pos.getZ()+rand.nextFloat(), 0, 0, 0, new int[0]);
world.playSound(pos.getX(), pos.getY(), pos.getZ(), EngineBlock.engineSound, EngineBlock.engineSoundVolume, EngineBlock.engineSoundPitch, true);
}
}
}
}
private Vector<BlockPos> move(){
if(target != null){
if(world != target.getWorld()){
moveToTarget();
return null;
}
Vec3 targetVec = new Vec3(target.getTarget().getX(), target.getTarget().getY(), target.getTarget().getZ());
Vec3 direction = targetVec.subtract(position);
float distance = (float) direction.lengthVector();
float traveledDistance = 0;
float speed = ShipInformation.getShipSpeed(this);
if(speed <= 0){
stop();
return null;
}
float directionAbs = 1;
if(speed <= 1){
direction = Vec3Op.scale(direction.normalize(), speed);
directionAbs = speed;
} else {
direction = direction.normalize();
}
Vector<BlockPos> movedPositions = new Vector<BlockPos>();
while(traveledDistance < speed && distance > 0) {
position = position.add(direction);
traveledDistance += directionAbs;
distance -= directionAbs;
movedPositions.add(new BlockPos(Math.round(position.xCoord), Math.round(position.yCoord), Math.round(position.zCoord)));
BlockPos worldPos = new BlockPos(new BlockPos(Math.round(position.xCoord), Math.round(position.yCoord), Math.round(position.zCoord)));
Block block = world.getBlockState(worldPos).getBlock();
if(!containsBlock(worldPos) &&
block.getMaterial() != Material.air &&
!block.getMaterial().isLiquid()){
stop();
return movedPositions;
}
}
if(distance <= 0){
stop();
}
return movedPositions;
} else {
return null;
}
}
public void stop(){
BlockPos positionPos = new BlockPos(new BlockPos(Math.round(position.xCoord), Math.round(position.yCoord), Math.round(position.zCoord)));
BlockPos addDirection = Vec3Op.subtract(positionPos, getOrigin());
moveTo(addDirection, world, target.getTurn());
target = null;
}
public void readFromNBT(NBTTagCompound c, String firstKey){
String data = c.getString(firstKey+positionsKey);
BlockPos pos = BlockPos.fromLong(c.getLong(firstKey+actualPositionKey));
position = new Vec3(pos.getX(), pos.getY(), pos.getZ());
if(c.getBoolean(firstKey+containsTargetKey)){
BlockPos targetPos = BlockPos.fromLong(c.getLong(firstKey+targetPositionKey));
int targetTurn = c.getInteger(firstKey+targetTurnKey);
target = new MovementTarget(targetPos, targetTurn, world);
}
try {
positionsFromString(data);
} catch (Exception e) {
e.printStackTrace();
}
}
public void writeToNBT(NBTTagCompound c, String firstKey){
c.setString(firstKey+positionsKey, positionsToString());
BlockPos pos = new BlockPos(position);
c.setLong(firstKey+actualPositionKey, pos.toLong());
if(target != null){
c.setBoolean(firstKey+containsTargetKey, true);
c.setLong(firstKey+targetPositionKey, target.getTarget().toLong());
c.setInteger(firstKey+targetTurnKey, target.getTurn());
} else {
c.setBoolean(firstKey+containsTargetKey, false);
}
}
}
|
package net.sf.jabref.gui;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefExecutorService;
import net.sf.jabref.JabRefGUI;
import net.sf.jabref.gui.desktop.JabRefDesktop;
import net.sf.jabref.gui.importer.EntryFromFileCreator;
import net.sf.jabref.gui.importer.EntryFromFileCreatorManager;
import net.sf.jabref.gui.importer.UnlinkedFilesCrawler;
import net.sf.jabref.gui.importer.UnlinkedPDFFileFilter;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.EntryTypes;
import net.sf.jabref.model.database.BibDatabaseContext;
import net.sf.jabref.model.entry.BibtexEntryType;
import net.sf.jabref.model.entry.EntryType;
import net.sf.jabref.model.entry.FieldName;
import net.sf.jabref.preferences.JabRefPreferences;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* GUI Dialog for the feature "Find unlinked files".
*
* @author Nosh&Dan
* @version 25.11.2008 | 23:13:29
*
*/
public class FindUnlinkedFilesDialog extends JDialog {
private static final Log LOGGER = LogFactory.getLog(FindUnlinkedFilesDialog.class);
/**
* Keys to be used for referencing this Action.
*/
public static final String ACTION_COMMAND = "findUnlinkedFiles";
public static final String ACTION_MENU_TITLE = Localization.menuTitle("Find unlinked files...");
public static final String ACTION_SHORT_DESCRIPTION = Localization
.lang("Searches for unlinked PDF files on the file system");
private static final String GLOBAL_PREFS_WORKING_DIRECTORY_KEY = "findUnlinkedFilesWD";
private static final String GLOBAL_PREFS_DIALOG_SIZE_KEY = "findUnlinkedFilesDialogSize";
private JabRefFrame frame;
private BibDatabaseContext databaseContext;
private EntryFromFileCreatorManager creatorManager;
private UnlinkedFilesCrawler crawler;
private Path lastSelectedDirectory;
private TreeModel treeModel;
/* PANELS */
private JPanel panelDirectory;
private JPanel panelSearchArea;
private JPanel panelFiles;
private JPanel panelOptions;
private JPanel panelButtons;
private JPanel panelEntryTypesSelection;
private JPanel panelImportArea;
private JButton buttonBrowse;
private JButton buttonScan;
private JButton buttonApply;
private JButton buttonClose;
/* Options for the TreeView */
private JButton buttonOptionSelectAll;
private JButton buttonOptionUnselectAll;
private JButton buttonOptionExpandAll;
private JButton buttonOptionCollapseAll;
private JCheckBox checkboxCreateKeywords;
private JTextField textfieldDirectoryPath;
private JLabel labelDirectoryDescription;
private JLabel labelFileTypesDescription;
private JLabel labelFilesDescription;
private JLabel labelEntryTypeDescription;
private JLabel labelSearchingDirectoryInfo;
private JLabel labelImportingInfo;
private JTree tree;
private JScrollPane scrollpaneTree;
private JComboBox<FileFilter> comboBoxFileTypeSelection;
private JComboBox<BibtexEntryTypeWrapper> comboBoxEntryTypeSelection;
private JProgressBar progressBarSearching;
private JProgressBar progressBarImporting;
private MouseListener treeMouseListener;
private Action actionSelectAll;
private Action actionUnselectAll;
private Action actionExpandTree;
private Action actionCollapseTree;
private ComponentListener dialogPositionListener;
private final AtomicBoolean threadState = new AtomicBoolean();
private boolean checkBoxWhyIsThereNoGetSelectedStupidSwing;
/**
* For Unit-testing only. <i>Don't remove!</i> <br>
* Used via reflection in {@link net.sf.jabref.importer.DatabaseFileLookup} to construct this
* class.
*/
@SuppressWarnings("unused")
private FindUnlinkedFilesDialog() {
//intended
}
public FindUnlinkedFilesDialog(Frame owner, JabRefFrame frame, BasePanel panel) {
super(owner, Localization.lang("Find unlinked files"), true);
this.frame = frame;
restoreSizeOfDialog();
databaseContext = panel.getDatabaseContext();
creatorManager = new EntryFromFileCreatorManager();
crawler = new UnlinkedFilesCrawler(databaseContext);
lastSelectedDirectory = loadLastSelectedDirectory();
initialize();
buttonApply.setEnabled(false);
}
/**
* Close dialog when pressing escape
*/
@Override
protected JRootPane createRootPane() {
ActionListener actionListener = actionEvent -> setVisible(false);
JRootPane rPane = new JRootPane();
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
rPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
return rPane;
}
/**
* Stores the current size of this dialog persistently.
*/
private void storeSizeOfDialog() {
Dimension dim = getSize();
String store = dim.width + ";" + dim.height;
Globals.prefs.put(FindUnlinkedFilesDialog.GLOBAL_PREFS_DIALOG_SIZE_KEY, store);
}
/**
* Restores the location and size of this dialog from the persistent storage.
*/
private void restoreSizeOfDialog() {
String store = Globals.prefs.get(FindUnlinkedFilesDialog.GLOBAL_PREFS_DIALOG_SIZE_KEY);
Dimension dimension = null;
if (store != null) {
try {
String[] dim = store.split(";");
dimension = new Dimension(Integer.valueOf(dim[0]), Integer.valueOf(dim[1]));
} catch (NumberFormatException ignoredEx) {
LOGGER.debug("RestoreSizeDialog Exception ", ignoredEx);
}
}
if (dimension != null) {
setPreferredSize(dimension);
}
}
/**
* Initializes the components, the layout, the data structure and the
* actions in this dialog.
*/
private void initialize() {
initializeActions();
initComponents();
createTree();
createFileTypesCombobox();
createEntryTypesCombobox();
initLayout();
setupActions();
pack();
}
/**
* Initializes action objects. <br>
* Does not assign actions to components yet!
*/
private void initializeActions() {
actionSelectAll = new AbstractAction(Localization.lang("Select all")) {
@Override
public void actionPerformed(ActionEvent e) {
CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
rootNode.setSelected(true);
tree.invalidate();
tree.repaint();
}
};
actionUnselectAll = new AbstractAction(Localization.lang("Unselect all")) {
@Override
public void actionPerformed(ActionEvent e) {
CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
rootNode.setSelected(false);
tree.invalidate();
tree.repaint();
}
};
actionExpandTree = new AbstractAction(Localization.lang("Expand all")) {
@Override
public void actionPerformed(ActionEvent e) {
CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
expandTree(tree, new TreePath(rootNode), true);
}
};
actionCollapseTree = new AbstractAction(Localization.lang("Collapse all")) {
@Override
public void actionPerformed(ActionEvent e) {
CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
expandTree(tree, new TreePath(rootNode), false);
}
};
dialogPositionListener = new ComponentAdapter() {
/* (non-Javadoc)
* @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent)
*/
@Override
public void componentResized(ComponentEvent e) {
storeSizeOfDialog();
}
/* (non-Javadoc)
* @see java.awt.event.ComponentAdapter#componentMoved(java.awt.event.ComponentEvent)
*/
@Override
public void componentMoved(ComponentEvent e) {
storeSizeOfDialog();
}
};
}
/**
* Stores the working directory path for this view in the global
* preferences.
*
* @param lastSelectedDir
* directory that is used as the working directory in this view.
*/
private void storeLastSelectedDirectory(Path lastSelectedDir) {
lastSelectedDirectory = lastSelectedDir;
if (lastSelectedDirectory != null) {
Globals.prefs.put(FindUnlinkedFilesDialog.GLOBAL_PREFS_WORKING_DIRECTORY_KEY,
lastSelectedDirectory.toAbsolutePath().toString());
}
}
/**
* Loads the working directory path which is persistantly stored for this
* view and returns it as a {@link File}-Object. <br>
* <br>
* If there is no working directory path stored, the general working
* directory will be consulted.
*
* @return The persistently stored working directory path for this view.
*/
private Path loadLastSelectedDirectory() {
String workingDirectory = Globals.prefs.get(FindUnlinkedFilesDialog.GLOBAL_PREFS_WORKING_DIRECTORY_KEY);
if (workingDirectory == null) {
workingDirectory = Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY);
}
lastSelectedDirectory = Paths.get(workingDirectory);
return lastSelectedDirectory;
}
/**
* Disables or enables all visible Elements in this Dialog. <br>
* <br>
* This also removes the {@link MouseListener} from the Tree-View to prevent
* it from receiving mouse events when in disabled-state.
*
* @param enable
* <code>true</code> when the elements shall get enabled,
* <code>false</code> when they shall get disabled.
*/
private void disOrEnableDialog(boolean enable) {
if (enable) {
tree.addMouseListener(treeMouseListener);
} else {
tree.removeMouseListener(treeMouseListener);
}
disOrEnableAllElements(FindUnlinkedFilesDialog.this, enable);
}
/**
* Recursively disables or enables all swing and awt components in this
* dialog, starting with but not including the container
* <code>startContainer</code>.
*
* @param startContainer
* The GUI Element to start with.
* @param enable
* <code>true</code>, if all elements will get enabled,
* <code>false</code> if all elements will get disabled.
*/
private void disOrEnableAllElements(Container startContainer, boolean enable) {
Component[] children = startContainer.getComponents();
for (Component child : children) {
if (child instanceof Container) {
disOrEnableAllElements((Container) child, enable);
}
child.setEnabled(enable);
}
}
/**
* Expands or collapses the specified tree according to the
* <code>expand</code>-parameter.
*/
private void expandTree(JTree currentTree, TreePath parent, boolean expand) {
TreeNode node = (TreeNode) parent.getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration<TreeNode> e = node.children(); e.hasMoreElements();) {
TreePath path = parent.pathByAddingChild(e.nextElement());
expandTree(currentTree, path, expand);
}
}
if (expand) {
currentTree.expandPath(parent);
} else {
currentTree.collapsePath(parent);
}
}
/**
* Starts the search of unlinked files according to the current dialog
* state. <br>
* <br>
* This state is made of: <br>
* <li>The value of the "directory"-input-textfield and <li>The file type
* selection. <br>
* The search will process in a seperate thread and the progress bar behind
* the "search" button will be displayed. <br>
* <br>
* When the search has completed, the
* {@link #searchFinishedHandler(CheckableTreeNode)} handler method is
* invoked.
*/
private void startSearch() {
Path directory = Paths.get(textfieldDirectoryPath.getText());
if (Files.notExists(directory)) {
directory = Paths.get(System.getProperty("user.dir"));
}
if (!Files.isDirectory(directory)) {
directory = directory.getParent();
}
//this addtional statement is needed because for the lamdba the variable must be effetively final
Path dir = directory;
storeLastSelectedDirectory(directory);
progressBarSearching.setMinimumSize(
new Dimension(buttonScan.getSize().width, progressBarSearching.getMinimumSize().height));
progressBarSearching.setVisible(true);
progressBarSearching.setString("");
labelSearchingDirectoryInfo.setVisible(true);
buttonScan.setVisible(false);
disOrEnableDialog(false);
labelSearchingDirectoryInfo.setEnabled(true);
final FileFilter selectedFileFilter = (FileFilter) comboBoxFileTypeSelection.getSelectedItem();
threadState.set(true);
JabRefExecutorService.INSTANCE.execute(() -> {
UnlinkedPDFFileFilter unlinkedPDFFileFilter = new UnlinkedPDFFileFilter(selectedFileFilter,
databaseContext);
CheckableTreeNode rootNode = crawler.searchDirectory(dir.toFile(), unlinkedPDFFileFilter, threadState,
new ChangeListener() {
int counter;
@Override
public void stateChanged(ChangeEvent e) {
counter++;
String message;
if (counter == 1) {
message = Localization.lang("One file found");
} else {
message = Localization.lang("%0 files found", Integer.toString(counter));
}
progressBarSearching.setString(message);
}
});
searchFinishedHandler(rootNode);
});
}
/**
* This will start the import of all file of all selected nodes in this
* dialogs tree view. <br>
* <br>
* The import itself will run in a seperate thread, whilst this dialog will
* be showing a progress bar, until the thread has finished its work. <br>
* <br>
* When the import has finished, the {@link #importFinishedHandler(java.util.List)} is
* invoked.
*/
private void startImport() {
if (treeModel == null) {
return;
}
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
CheckableTreeNode root = (CheckableTreeNode) treeModel.getRoot();
final List<File> fileList = getFileListFromNode(root);
if ((fileList == null) || fileList.isEmpty()) {
return;
}
progressBarImporting.setVisible(true);
labelImportingInfo.setVisible(true);
buttonApply.setVisible(false);
buttonClose.setVisible(false);
disOrEnableDialog(false);
labelImportingInfo.setEnabled(true);
progressBarImporting.setMinimum(0);
progressBarImporting.setMaximum(fileList.size());
progressBarImporting.setValue(0);
progressBarImporting.setString("");
final EntryType entryType = ((BibtexEntryTypeWrapper) comboBoxEntryTypeSelection.getSelectedItem())
.getEntryType();
threadState.set(true);
JabRefExecutorService.INSTANCE.execute(() -> {
List<String> errors = new LinkedList<>();
creatorManager.addEntriesFromFiles(fileList, databaseContext.getDatabase(), frame.getCurrentBasePanel(),
entryType, checkBoxWhyIsThereNoGetSelectedStupidSwing, new ChangeListener() {
int counter;
@Override
public void stateChanged(ChangeEvent e) {
counter++;
progressBarImporting.setValue(counter);
progressBarImporting.setString(Localization.lang("%0 of %1", Integer.toString(counter),
Integer.toString(progressBarImporting.getMaximum())));
}
}, errors);
importFinishedHandler(errors);
});
}
/**
*
* @param errors
*/
private void importFinishedHandler(List<String> errors) {
if ((errors != null) && !errors.isEmpty()) {
String message;
if (errors.size() == 1) {
message = Localization.lang("There was one file that could not be imported.");
} else {
message = Localization.lang("There were %0 files which could not be imported.",
Integer.toString(errors.size()));
}
JOptionPane.showMessageDialog(this,
Localization.lang("The import finished with warnings:") + "\n" + message,
Localization.lang("Warning"), JOptionPane.WARNING_MESSAGE);
}
progressBarImporting.setVisible(false);
labelImportingInfo.setVisible(false);
buttonApply.setVisible(true);
buttonClose.setVisible(true);
disOrEnableDialog(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getCurrentBasePanel().markBaseChanged();
}
/**
* Will be called from the Thread in which the "unlinked files search" is
* processed. As the result of the search, the root node of the determined
* file structure is passed.
*
* @param rootNode
* The root of the file structure as the result of the search.
*/
private void searchFinishedHandler(CheckableTreeNode rootNode) {
treeModel = new DefaultTreeModel(rootNode);
tree.setModel(treeModel);
tree.setRootVisible(rootNode.getChildCount() > 0);
tree.invalidate();
tree.repaint();
progressBarSearching.setVisible(false);
labelSearchingDirectoryInfo.setVisible(false);
buttonScan.setVisible(true);
actionSelectAll.actionPerformed(null);
disOrEnableDialog(true);
buttonApply.setEnabled(true);
}
/**
* Sets up the actions for the components.
*/
private void setupActions() {
/**
* Stores the selected directory.
*/
buttonBrowse.addActionListener(e -> {
Optional<Path> selectedDirectory = new FileDialog(frame).showDialogAndGetSelectedDirectory();
selectedDirectory.ifPresent(d -> {
textfieldDirectoryPath.setText(d.toAbsolutePath().toString());
storeLastSelectedDirectory(d);
});
});
buttonScan.addActionListener(e -> startSearch());
/**
* Action for the button "Import...". <br>
* <br>
* Actions on this button will start the import of all file of all
* selected nodes in this dialogs tree view. <br>
*/
ActionListener actionListenerImportEntrys = e -> startImport();
buttonApply.addActionListener(actionListenerImportEntrys);
buttonClose.addActionListener(e -> dispose());
}
/**
* Creates a list of {@link File}s for all leaf nodes in the tree structure
* <code>node</code>, which have been marked as <i>selected</i>. <br>
* <br>
* <code>Selected</code> nodes correspond to those entries in the tree,
* whose checkbox is <code>checked</code>.
*
* SIDE EFFECT: The checked nodes are removed from the tree.
*
* @param node
* The root node representing a tree structure.
* @return A list of files of all checked leaf nodes.
*/
private List<File> getFileListFromNode(CheckableTreeNode node) {
List<File> filesList = new ArrayList<>();
Enumeration<CheckableTreeNode> children = node.depthFirstEnumeration();
List<CheckableTreeNode> nodesToRemove = new ArrayList<>();
for (CheckableTreeNode child : Collections.list(children)) {
if (child.isLeaf() && child.isSelected()) {
File nodeFile = ((FileNodeWrapper) child.getUserObject()).file;
if ((nodeFile != null) && nodeFile.isFile()) {
filesList.add(nodeFile);
nodesToRemove.add(child);
}
}
}
// remove imported files from tree
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
for (CheckableTreeNode nodeToRemove : nodesToRemove) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) nodeToRemove.getParent();
model.removeNodeFromParent(nodeToRemove);
// remove empty parent node
while ((parent != null) && parent.isLeaf()) {
DefaultMutableTreeNode pp = (DefaultMutableTreeNode) parent.getParent();
if (pp != null) {
model.removeNodeFromParent(parent);
}
parent = pp;
}
// TODO: update counter / see: getTreeCellRendererComponent for label generation
}
tree.invalidate();
tree.repaint();
return filesList;
}
/**
* Initializes the visible components in this dialog.
*/
private void initComponents() {
this.addComponentListener(dialogPositionListener);
/* Interrupts the searchThread by setting the State-Array to 0 */
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
threadState.set(false);
}
});
panelDirectory = new JPanel();
panelSearchArea = new JPanel();
panelFiles = new JPanel();
panelOptions = new JPanel();
panelEntryTypesSelection = new JPanel();
panelButtons = new JPanel();
panelImportArea = new JPanel();
buttonBrowse = new JButton(Localization.lang("Browse"));
buttonBrowse.setMnemonic('B');
buttonBrowse.setToolTipText(Localization.lang("Opens the file browser."));
buttonScan = new JButton(Localization.lang("Scan directory"));
buttonScan.setMnemonic('S');
buttonScan.setToolTipText(Localization.lang("Searches the selected directory for unlinked files."));
buttonApply = new JButton(Localization.lang("Apply"));
buttonApply.setMnemonic('I');
buttonApply.setToolTipText(Localization.lang("Starts the import of BibTeX entries."));
buttonClose = new JButton(Localization.lang("Close"));
buttonClose.setToolTipText(Localization.lang("Leave this dialog."));
buttonClose.setMnemonic('C');
/* Options for the TreeView */
buttonOptionSelectAll = new JButton();
buttonOptionSelectAll.setMnemonic('A');
buttonOptionSelectAll.setAction(actionSelectAll);
buttonOptionUnselectAll = new JButton();
buttonOptionUnselectAll.setMnemonic('U');
buttonOptionUnselectAll.setAction(actionUnselectAll);
buttonOptionExpandAll = new JButton();
buttonOptionExpandAll.setMnemonic('E');
buttonOptionExpandAll.setAction(actionExpandTree);
buttonOptionCollapseAll = new JButton();
buttonOptionCollapseAll.setMnemonic('L');
buttonOptionCollapseAll.setAction(actionCollapseTree);
checkboxCreateKeywords = new JCheckBox(Localization.lang("Create directory based keywords"));
checkboxCreateKeywords
.setToolTipText(Localization.lang("Creates keywords in created entrys with directory pathnames"));
checkboxCreateKeywords.setSelected(checkBoxWhyIsThereNoGetSelectedStupidSwing);
checkboxCreateKeywords.addItemListener(
e -> checkBoxWhyIsThereNoGetSelectedStupidSwing = !checkBoxWhyIsThereNoGetSelectedStupidSwing);
textfieldDirectoryPath = new JTextField();
textfieldDirectoryPath
.setText(lastSelectedDirectory == null ? "" : lastSelectedDirectory.toAbsolutePath().toString());
labelDirectoryDescription = new JLabel(Localization.lang("Select a directory where the search shall start."));
labelFileTypesDescription = new JLabel(Localization.lang("Select file type:"));
labelFilesDescription = new JLabel(Localization.lang("These files are not linked in the active database."));
labelEntryTypeDescription = new JLabel(Localization.lang("Entry type to be created:"));
labelSearchingDirectoryInfo = new JLabel(Localization.lang("Searching file system..."));
labelSearchingDirectoryInfo.setHorizontalAlignment(SwingConstants.CENTER);
labelSearchingDirectoryInfo.setVisible(false);
labelImportingInfo = new JLabel(Localization.lang("Importing into Database..."));
labelImportingInfo.setHorizontalAlignment(SwingConstants.CENTER);
labelImportingInfo.setVisible(false);
tree = new JTree();
scrollpaneTree = new JScrollPane(tree);
scrollpaneTree.setWheelScrollingEnabled(true);
progressBarSearching = new JProgressBar();
progressBarSearching.setIndeterminate(true);
progressBarSearching.setVisible(false);
progressBarSearching.setStringPainted(true);
progressBarImporting = new JProgressBar();
progressBarImporting.setIndeterminate(false);
progressBarImporting.setVisible(false);
progressBarImporting.setStringPainted(true);
}
/**
* Initializes the layout for the visible components in this menu. A
* {@link GridBagLayout} is used.
*/
private void initLayout() {
GridBagLayout gbl = new GridBagLayout();
panelDirectory.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
Localization.lang("Select directory")));
panelFiles.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
Localization.lang("Select files")));
panelEntryTypesSelection.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
Localization.lang("BibTeX entry creation")));
Insets basicInsets = new Insets(6, 6, 6, 6);
Insets smallInsets = new Insets(3, 2, 3, 1);
Insets noInsets = new Insets(0, 0, 0, 0);
// x, y, w, h, wx,wy,ix,iy
FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, buttonScan, GridBagConstraints.HORIZONTAL,
GridBagConstraints.EAST, noInsets, 0, 1, 1, 1, 1, 1, 40, 10);
FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, labelSearchingDirectoryInfo,
GridBagConstraints.HORIZONTAL, GridBagConstraints.EAST, noInsets, 0, 2, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, progressBarSearching, GridBagConstraints.HORIZONTAL,
GridBagConstraints.EAST, noInsets, 0, 3, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, labelDirectoryDescription, null,
GridBagConstraints.WEST, new Insets(6, 6, 0, 6), 0, 0, 3, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, textfieldDirectoryPath, GridBagConstraints.HORIZONTAL,
null, basicInsets, 0, 1, 2, 1, 1, 1, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, buttonBrowse, GridBagConstraints.HORIZONTAL,
GridBagConstraints.EAST, basicInsets, 2, 1, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, labelFileTypesDescription, GridBagConstraints.NONE,
GridBagConstraints.WEST, new Insets(18, 6, 18, 3), 0, 3, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, comboBoxFileTypeSelection,
GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, new Insets(18, 3, 18, 6), 1, 3, 1, 1, 1, 0, 0,
0);
FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, panelSearchArea, GridBagConstraints.HORIZONTAL,
GridBagConstraints.EAST, new Insets(18, 6, 18, 6), 2, 3, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, labelFilesDescription, GridBagConstraints.HORIZONTAL,
GridBagConstraints.WEST, new Insets(6, 6, 0, 6), 0, 0, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, scrollpaneTree, GridBagConstraints.BOTH,
GridBagConstraints.CENTER, basicInsets, 0, 1, 1, 1, 1, 1, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, panelOptions, GridBagConstraints.NONE,
GridBagConstraints.NORTHEAST, basicInsets, 1, 1, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionSelectAll, GridBagConstraints.HORIZONTAL,
GridBagConstraints.NORTH, noInsets, 0, 0, 1, 1, 1, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionUnselectAll, GridBagConstraints.HORIZONTAL,
GridBagConstraints.NORTH, noInsets, 0, 1, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionExpandAll, GridBagConstraints.HORIZONTAL,
GridBagConstraints.NORTH, new Insets(6, 0, 0, 0), 0, 2, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionCollapseAll, GridBagConstraints.HORIZONTAL,
GridBagConstraints.NORTH, noInsets, 0, 3, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, labelEntryTypeDescription,
GridBagConstraints.NONE, GridBagConstraints.WEST, basicInsets, 0, 0, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, comboBoxEntryTypeSelection,
GridBagConstraints.NONE, GridBagConstraints.WEST, basicInsets, 1, 0, 1, 1, 1, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, checkboxCreateKeywords,
GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, basicInsets, 0, 1, 2, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelImportArea, labelImportingInfo, GridBagConstraints.HORIZONTAL,
GridBagConstraints.CENTER, new Insets(6, 6, 0, 6), 0, 1, 1, 1, 1, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelImportArea, progressBarImporting, GridBagConstraints.HORIZONTAL,
GridBagConstraints.CENTER, new Insets(0, 6, 6, 6), 0, 2, 1, 1, 1, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, panelButtons, panelImportArea, GridBagConstraints.NONE,
GridBagConstraints.EAST, smallInsets, 1, 0, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelDirectory, GridBagConstraints.HORIZONTAL,
GridBagConstraints.CENTER, basicInsets, 0, 0, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelFiles, GridBagConstraints.BOTH,
GridBagConstraints.NORTHWEST, new Insets(12, 6, 2, 2), 0, 1, 1, 1, 1, 1, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelEntryTypesSelection,
GridBagConstraints.HORIZONTAL, GridBagConstraints.SOUTHWEST, new Insets(12, 6, 2, 2), 0, 2, 1, 1, 0, 0,
0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelButtons, GridBagConstraints.HORIZONTAL,
GridBagConstraints.CENTER, new Insets(10, 6, 10, 6), 0, 3, 1, 1, 0, 0, 0, 0);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
bb.addButton(buttonApply);
bb.addButton(buttonClose);
bb.addGlue();
bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelImportArea.add(bb.getPanel(), GridBagConstraints.NONE);
pack();
}
/**
* Adds a component to a container, using the specified gridbag-layout and
* the supplied parameters. <br>
* <br>
* This method is simply used to ged rid of thousands of lines of code,
* which inevitably rise when layouts such as the gridbag-layout is being
* used.
*
* @param layout
* The layout to be used.
* @param container
* The {@link Container}, to which the component will be added.
* @param component
* An AWT {@link Component}, that will be added to the container.
* @param fill
* A constant describing the fill behaviour (see
* {@link GridBagConstraints}). Can be <code>null</code>, if no
* filling wants to be specified.
* @param anchor
* A constant describing the anchor of the element in its parent
* container (see {@link GridBagConstraints}). Can be
* <code>null</code>, if no specification is needed.
* @param gridX
* The relative grid-X coordinate.
* @param gridY
* The relative grid-Y coordinate.
* @param width
* The relative width of the component.
* @param height
* The relative height of the component.
* @param weightX
* A value for the horizontal weight.
* @param weightY
* A value for the vertical weight.
* @param insets
* Insets of the component. Can be <code>null</code>.
*/
private static void addComponent(GridBagLayout layout, Container container, Component component, Integer fill,
Integer anchor, Insets insets, int gridX, int gridY, int width, int height, double weightX, double weightY,
int ipadX, int ipadY) {
container.setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = gridX;
constraints.gridy = gridY;
constraints.gridwidth = width;
constraints.gridheight = height;
constraints.weightx = weightX;
constraints.weighty = weightY;
constraints.ipadx = ipadX;
constraints.ipady = ipadY;
if (fill != null) {
constraints.fill = fill;
}
if (insets != null) {
constraints.insets = insets;
}
if (anchor != null) {
constraints.anchor = anchor;
}
layout.setConstraints(component, constraints);
container.add(component);
}
/**
* Creates the tree view, that holds the data structure. <br>
* <br>
* Initially, the root node is <b>not</b> visible, so that the tree appears empty at the beginning.
*/
private void createTree() {
/**
* Mouse listener to listen for mouse events on the tree. <br>
* This will mark the selected tree entry as "selected" or "unselected",
* which will cause this nodes checkbox to appear as either "checked" or
* "unchecked".
*/
treeMouseListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int row = tree.getRowForLocation(x, y);
TreePath path = tree.getPathForRow(row);
if (path != null) {
CheckableTreeNode node = (CheckableTreeNode) path.getLastPathComponent();
if (e.getClickCount() == 2) {
Object userObject = node.getUserObject();
if ((userObject instanceof FileNodeWrapper) && node.isLeaf()) {
FileNodeWrapper fnw = (FileNodeWrapper) userObject;
try {
JabRefDesktop.openExternalViewer(
JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext(),
fnw.file.getAbsolutePath(), FieldName.PDF);
} catch (IOException e1) {
LOGGER.info("Error opening file", e1);
}
}
} else {
node.check();
tree.invalidate();
tree.repaint();
}
}
}
};
CheckableTreeNode startNode = new CheckableTreeNode("ROOT");
DefaultTreeModel model = new DefaultTreeModel(startNode);
tree.setModel(model);
tree.setRootVisible(false);
DefaultTreeCellRenderer renderer = new CheckboxTreeCellRenderer();
tree.setCellRenderer(renderer);
tree.addMouseListener(treeMouseListener);
}
/**
* Initialises the combobox that contains the available file types which
* bibtex entries can be created of.
*/
private void createFileTypesCombobox() {
List<FileFilter> fileFilterList = creatorManager.getFileFilterList();
Vector<FileFilter> vector = new Vector<>();
for (FileFilter fileFilter : fileFilterList) {
vector.add(fileFilter);
}
comboBoxFileTypeSelection = new JComboBox<>(vector);
comboBoxFileTypeSelection.setRenderer(new DefaultListCellRenderer() {
/* (non-Javadoc)
* @see javax.swing.DefaultListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
*/
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (value instanceof EntryFromFileCreator) {
EntryFromFileCreator creator = (EntryFromFileCreator) value;
if (creator.getExternalFileType() != null) {
label.setIcon(creator.getExternalFileType().getIcon());
}
}
return label;
}
});
}
/**
* Creates the ComboBox-View for the Listbox that holds the Bibtex entry
* types.
*/
private void createEntryTypesCombobox() {
Iterator<EntryType> iterator = EntryTypes
.getAllValues(frame.getCurrentBasePanel().getBibDatabaseContext().getMode()).iterator();
Vector<BibtexEntryTypeWrapper> list = new Vector<>();
list.add(
new BibtexEntryTypeWrapper(null));
while (iterator.hasNext()) {
list.add(new BibtexEntryTypeWrapper(iterator.next()));
}
comboBoxEntryTypeSelection = new JComboBox<>(list);
}
/**
* Wrapper for displaying the Type {@link BibtexEntryType} in a Combobox.
*
* @author Nosh&Dan
* @version 12.11.2008 | 01:02:30
*
*/
private static class BibtexEntryTypeWrapper {
private final EntryType entryType;
BibtexEntryTypeWrapper(EntryType bibtexType) {
this.entryType = bibtexType;
}
@Override
public String toString() {
if (entryType == null) {
return Localization.lang("<No selection>");
}
return entryType.getName();
}
public EntryType getEntryType() {
return entryType;
}
}
public static class CheckableTreeNode extends DefaultMutableTreeNode {
private boolean isSelected;
private final JCheckBox checkbox;
public CheckableTreeNode(Object userObject) {
super(userObject);
checkbox = new JCheckBox();
}
/**
* @return the checkbox
*/
public JCheckBox getCheckbox() {
return checkbox;
}
public void check() {
setSelected(!isSelected);
}
public void setSelected(boolean bSelected) {
isSelected = bSelected;
Enumeration<CheckableTreeNode> tmpChildren = this.children();
for (CheckableTreeNode child : Collections.list(tmpChildren)) {
child.setSelected(bSelected);
}
}
public boolean isSelected() {
return isSelected;
}
}
private static class CheckboxTreeCellRenderer extends DefaultTreeCellRenderer {
private final FileSystemView fsv = FileSystemView.getFileSystemView();
@Override
public Component getTreeCellRendererComponent(final JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
Component nodeComponent = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,
hasFocus);
CheckableTreeNode node = (CheckableTreeNode) value;
FileNodeWrapper userObject = (FileNodeWrapper) node.getUserObject();
JPanel newPanel = new JPanel();
JCheckBox checkbox = node.getCheckbox();
checkbox.setSelected(node.isSelected());
try {
setIcon(fsv.getSystemIcon(userObject.file));
} catch (Exception ignored) {
// Ignored
}
newPanel.setBackground(nodeComponent.getBackground());
checkbox.setBackground(nodeComponent.getBackground());
GridBagLayout gbl = new GridBagLayout();
FindUnlinkedFilesDialog.addComponent(gbl, newPanel, checkbox, null, null, null, 0, 0, 1, 1, 0, 0, 0, 0);
FindUnlinkedFilesDialog.addComponent(gbl, newPanel, nodeComponent, GridBagConstraints.HORIZONTAL, null,
new Insets(1, 2, 0, 0), 1, 0, 1, 1, 1, 0, 0, 0);
if (userObject.fileCount > 0) {
JLabel label = new JLabel(
"(" + userObject.fileCount + " file" + (userObject.fileCount > 1 ? "s" : "") + ")");
FindUnlinkedFilesDialog.addComponent(gbl, newPanel, label, null, null, new Insets(1, 2, 0, 0), 2, 0, 1,
1, 0, 0, 0, 0);
}
return newPanel;
}
}
public static class FileNodeWrapper {
public final File file;
public final int fileCount;
public FileNodeWrapper(File aFile) {
this(aFile, 0);
}
/**
* @param aDirectory
* @param fileCount
*/
public FileNodeWrapper(File aDirectory, int fileCount) {
this.file = aDirectory;
this.fileCount = fileCount;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return file.getName();
}
}
}
|
package com.mingzuozhibi.commons.utils;
import com.mingzuozhibi.commons.gson.GsonFactory;
import com.mingzuozhibi.commons.result.BaseResult;
import org.apache.commons.lang3.StringUtils;
import java.util.Objects;
import java.util.Optional;
public abstract class ChecksUtils {
@SafeVarargs
public static Optional<String> runChecks(Optional<String>... checks) {
for (Optional<String> check : checks) {
if (check.isPresent()) return check;
}
return Optional.empty();
}
public static Optional<String> checkNotEmpty(String value, String paramName) {
if (StringUtils.isNotEmpty(value)) {
return Optional.empty();
}
return Optional.of(paramName + "");
}
public static Optional<String> checkSelected(Object value, String paramName) {
if (!Objects.isNull(value)) {
return Optional.empty();
}
return Optional.of(paramName + "");
}
public static Optional<String> checkIdentifier(String value, String paramName, int min, int max) {
return checkMatches(value, "[A-Za-z0-9_]{" + min + "," + max + "}",
paramName + "" + min + "-" + max);
}
public static Optional<String> checkMd5Encode(String encode, String paramName, int length) {
return checkMatches(encode, "[0-9a-f]{" + length + "}",
paramName + "" + length + "Md5");
}
public static Optional<String> checkMatches(String text, String regex, String error) {
if (text.matches(regex)) {
return Optional.empty();
}
return Optional.of(error);
}
public static String paramExists(String paramName) {
return errorResult("" + paramName + "");
}
public static String paramNotExists(String paramName) {
return errorResult("" + paramName + "");
}
public static String itemsExists(String itemName) {
return errorResult("" + itemName + "");
}
public static String itemsNotExists(String itemName) {
return errorResult("" + itemName + "");
}
private static String errorResult(String message) {
return GsonFactory.GSON.toJson(new BaseResult(message));
}
}
|
package net.snowflake.client.jdbc;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.List;
import java.util.Properties;
import net.snowflake.common.core.ResourceBundleManager;
import net.snowflake.common.core.SqlState;
/**
* JDBC Driver implementation of Snowflake for production. To use this driver, specify the following
* URL: jdbc:snowflake://host:port
*
* <p>Note: don't add logger to this class since logger init will potentially break driver class
* loading
*/
public class SnowflakeDriver implements Driver {
static SnowflakeDriver INSTANCE;
public static final Properties EMPTY_PROPERTIES = new Properties();
public static String implementVersion = "3.13.14";
static int majorVersion = 0;
static int minorVersion = 0;
static long patchVersion = 0;
protected static boolean disableIncidents = false;
private static boolean disableArrowResultFormat = false;
private static String disableArrowResultFormatMessage;
private static final ResourceBundleManager versionResourceBundleManager =
ResourceBundleManager.getSingleton("net.snowflake.client.jdbc.version");
static {
try {
DriverManager.registerDriver(INSTANCE = new SnowflakeDriver());
} catch (SQLException ex) {
throw new IllegalStateException("Unable to register " + SnowflakeDriver.class.getName(), ex);
}
initializeArrowSupport();
/*
* Get the manifest properties here.
*/
initializeClientVersionFromManifest();
}
/** try to initialize Arrow support if fails, JDBC is going to use the legacy format */
private static void initializeArrowSupport() {
try {
// this is required to enable direct memory usage for Arrow buffers in Java
System.setProperty("io.netty.tryReflectionSetAccessible", "true");
} catch (Throwable t) {
// fail to enable required feature for Arrow
disableArrowResultFormat = true;
disableArrowResultFormatMessage = t.getLocalizedMessage();
}
disableIllegalReflectiveAccessWarning();
}
static void disableIllegalReflectiveAccessWarning() {
// This function try to eliminate the warning by setting
// Disable this function and manually run arrow tests, e.g. testResultSetMetadata., then
// the warning can be found in output.
try {
Class unsafeClass = Class.forName("sun.misc.Unsafe");
Field field = unsafeClass.getDeclaredField("theUnsafe");
field.setAccessible(true);
Object unsafe = field.get(null);
Method putObjectVolatile =
unsafeClass.getDeclaredMethod(
"putObjectVolatile", Object.class, long.class, Object.class);
Method staticFieldOffset = unsafeClass.getDeclaredMethod("staticFieldOffset", Field.class);
Method staticFieldBase = unsafeClass.getDeclaredMethod("staticFieldBase", Field.class);
Class loggerClass = Class.forName("jdk.internal.module.IllegalAccessLogger");
Field loggerField = loggerClass.getDeclaredField("logger");
Long loggerOffset = (Long) staticFieldOffset.invoke(unsafe, loggerField);
Object loggerBase = staticFieldBase.invoke(unsafe, loggerField);
putObjectVolatile.invoke(unsafe, loggerBase, loggerOffset, null);
} catch (Throwable ex) {
// If failed to eliminate warnings, do nothing
}
}
private static void initializeClientVersionFromManifest() {
/*
* Get JDBC version numbers from static string in snowflake-jdbc
*/
try {
// parse implementation version major.minor.change
if (implementVersion != null) {
String[] versionBreakdown = implementVersion.split("\\.");
if (versionBreakdown.length == 3) {
majorVersion = Integer.parseInt(versionBreakdown[0]);
minorVersion = Integer.parseInt(versionBreakdown[1]);
patchVersion = Long.parseLong(versionBreakdown[2]);
} else {
throw new SnowflakeSQLLoggedException(
null,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
SqlState.INTERNAL_ERROR,
/*session = */ "Invalid Snowflake JDBC Version: " + implementVersion);
}
} else {
throw new SnowflakeSQLException(
SqlState.INTERNAL_ERROR,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
/*session = */ null,
"Snowflake JDBC Version is not set. "
+ "Ensure static version string was initialized.");
}
} catch (Throwable ex) {
}
}
/**
* For testing purposes only- used to compare that JDBC version in pom.xml matches static string
*
* @return String with version from pom.xml file
*/
static String getClientVersionStringFromManifest() {
return versionResourceBundleManager.getLocalizedMessage("version");
}
public static boolean isDisableArrowResultFormat() {
return disableArrowResultFormat;
}
public static String getDisableArrowResultFormatMessage() {
return disableArrowResultFormatMessage;
}
/**
* Checks whether a given url is in a valid format.
*
* <p>The current uri format is: jdbc:snowflake://[host[:port]]
*
* <p>jdbc:snowflake:// - run in embedded mode jdbc:snowflake://localhost - connect to localhost
* default port (8080)
*
* <p>jdbc:snowflake://localhost:8080- connect to localhost port 8080
*
* @param url url of the database including host and port
* @return true if the url is valid
*/
@Override
public boolean acceptsURL(String url) {
return SnowflakeConnectString.parse(url, EMPTY_PROPERTIES).isValid();
}
/**
* Connect method
*
* @param url jdbc url
* @param info addition info for passing database/schema names
* @return connection
* @throws SQLException if failed to create a snowflake connection
*/
@Override
public Connection connect(String url, Properties info) throws SQLException {
SnowflakeConnectString conStr = SnowflakeConnectString.parse(url, info);
if (!conStr.isValid()) {
return null;
}
return new SnowflakeConnectionV1(url, info);
}
@Override
public int getMajorVersion() {
return majorVersion;
}
@Override
public int getMinorVersion() {
return minorVersion;
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
DriverPropertyInfo[] retVal;
if (url == null || url.isEmpty()) {
retVal = new DriverPropertyInfo[1];
retVal[0] = new DriverPropertyInfo("serverURL", null);
retVal[0].description =
"server URL in form of <protocol>://<host or domain>:<port number>/<path of resource>";
return retVal;
}
Connection con = new SnowflakeConnectionV1(url, info, true);
List<DriverPropertyInfo> missingProperties =
((SnowflakeConnectionV1) con).returnMissingProperties();
con.close();
retVal = new DriverPropertyInfo[missingProperties.size()];
retVal = missingProperties.toArray(retVal);
return retVal;
}
@Override
public boolean jdbcCompliant() {
return false;
}
@Override
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
public static boolean isDisableIncidents() {
return disableIncidents;
}
public static void setDisableIncidents(boolean throttleIncidents) {
SnowflakeDriver.disableIncidents = throttleIncidents;
}
public static final void main(String[] args) {
if (args.length > 0 && "--version".equals(args[0])) {
Package pkg = Package.getPackage("net.snowflake.client.jdbc");
if (pkg != null) {
System.out.println(pkg.getImplementationVersion());
}
}
}
}
|
package com.mixpanel.android.viewcrawler;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewTreeObserver;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/* package */ class EditState {
public EditState() {
mUiThreadHandler = new Handler(Looper.getMainLooper());
mIntendedEdits = new HashMap<String, List<ViewVisitor>>();
mCurrentEdits = new HashSet<EditBinding>();
}
// Must be thread-safe
public void applyAllChangesOnUiThread(final Set<Activity> liveActivities) {
if (Thread.currentThread() == mUiThreadHandler.getLooper().getThread()) {
applyIntendedEdits(liveActivities);
} else {
mUiThreadHandler.post(new Runnable() {
@Override
public void run() {
applyIntendedEdits(liveActivities);
}
});
}
}
// Must be thread-safe
public void setEdits(Map<String, List<ViewVisitor>> newEdits) {
synchronized (mCurrentEdits) {
for (EditBinding stale:mCurrentEdits) {
stale.kill();
}
mCurrentEdits.clear();
}
synchronized(mIntendedEdits) {
mIntendedEdits.clear();
mIntendedEdits.putAll(newEdits);
}
}
// Must be called on UI Thread
private void applyIntendedEdits(final Set<Activity> liveActivities) {
synchronized (liveActivities) {
for (Activity activity:liveActivities) {
final String activityName = activity.getClass().getCanonicalName();
final View rootView = activity.getWindow().getDecorView().getRootView();
final List<ViewVisitor> specificChanges;
final List<ViewVisitor> wildcardChanges;
synchronized (mIntendedEdits) {
specificChanges = mIntendedEdits.get(activityName);
wildcardChanges = mIntendedEdits.get(null);
}
if (null != specificChanges) {
applyChangesFromList(rootView, specificChanges);
}
if (null != wildcardChanges) {
applyChangesFromList(rootView, wildcardChanges);
}
}
}
}
// Must be called on UI Thread
private void applyChangesFromList(View rootView, List<ViewVisitor> changes) {
synchronized (mCurrentEdits) {
int size = changes.size();
for (int i = 0; i < size; i++) {
final ViewVisitor visitor = changes.get(i);
final EditBinding binding = new EditBinding(rootView, visitor, mUiThreadHandler);
mCurrentEdits.add(binding);
}
}
}
/* The binding between a bunch of edits and a view. Should be instantiated and live on the UI thread */
private static class EditBinding implements ViewTreeObserver.OnGlobalLayoutListener, Runnable {
public EditBinding(View viewRoot, ViewVisitor edit, Handler uiThreadHandler) {
mEdit = edit;
mViewRoot = new WeakReference<View>(viewRoot);
mHandler = uiThreadHandler;
mAlive = true;
final ViewTreeObserver observer = viewRoot.getViewTreeObserver();
if (observer.isAlive()) {
observer.addOnGlobalLayoutListener(this);
}
run();
}
@Override
public void onGlobalLayout() {
run();
}
@Override
public void run() {
if (!mAlive) {
return;
}
final View viewRoot = mViewRoot.get();
if (null == viewRoot) {
kill();
return;
}
// ELSE View is alive and we are alive
mEdit.visit(viewRoot);
mHandler.removeCallbacks(this);
mHandler.postDelayed(this, 1000);
}
public void kill() {
mAlive = false;
final View viewRoot = mViewRoot.get();
if (null != viewRoot) {
final ViewTreeObserver observer = viewRoot.getViewTreeObserver();
if (observer.isAlive()) {
observer.removeGlobalOnLayoutListener(this);
}
}
}
private volatile boolean mAlive;
private final WeakReference<View> mViewRoot;
private final ViewVisitor mEdit;
private final Handler mHandler;
}
private final Handler mUiThreadHandler;
private final Map<String, List<ViewVisitor>> mIntendedEdits;
private final Set<EditBinding> mCurrentEdits;
@SuppressWarnings("unused")
private static final String LOGTAG = "MixpanelAPI.EditState";
}
|
package nl.hsac.fitnesse.fixture.slim;
import nl.hsac.fitnesse.fixture.util.XMLFormatter;
import nl.hsac.fitnesse.fixture.util.XmlHttpResponse;
/**
* Fixture to make HTTP requests returning XNL using Slim scripts and/or scenarios.
* Example use: make SOAP calls using #postTo().
*/
public class XmlHttpTest extends HttpTest {
private final XMLFormatter xmlFormatter = new XMLFormatter();
/**
* Register a prefix to use in XPath expressions.
* @param prefix prefix to be used in xPath expressions.
* @param namespace XML namespace the prefix should point to.
*/
public void registerPrefixForNamespace(String prefix, String namespace) {
getEnvironment().registerNamespace(prefix, getUrl(namespace));
}
/**
* @return request sent last time postTo() was called.
*/
@Override
public String request() {
return getEnvironment().getHtmlForXml(super.request());
}
/**
* @return response received last time postTo() was called.
*/
@Override
public String response() {
String response = super.response();
String result;
try {
result = getEnvironment().getHtmlForXml(response);
} catch (Exception e) {
result = response;
}
return result;
}
/**
* Gets XPath value, without ensuring response was valid.
* @param xPathExpr expression to evaluate.
* @return result of expression evaluation against last response received.
*/
public String rawXPath(String xPathExpr) {
return getResponse().getRawXPath(xPathExpr);
}
/**
* @param xPathExpr expression to evaluate.
* @return result of expression evaluation against last response received.
* @throws RuntimeException if no valid response was available or XPath could not be evaluated.
*/
public String xPath(String xPathExpr) {
return getResponse().getXPath(xPathExpr);
}
/**
* @param xPathExpr expression to evaluate.
* @return result of expression evaluation against last response received.
* @throws RuntimeException if no valid response was available or XPath could not be evaluated.
*/
public Double xPathDouble(String xPathExpr) {
return getResponse().getXPathDouble(xPathExpr);
}
/**
* @param xPathExpr expression to evaluate.
* @return result of expression evaluation against last response received.
* @throws RuntimeException if no valid response was available or XPath could not be evaluated.
*/
public Double xPathInt(String xPathExpr) {
return getResponse().getXPathDouble(xPathExpr);
}
@Override
protected boolean postProcessResponse() {
// always called after post or get, so easy place to ensure namespaces are registered
getResponse().setNamespaceContext(getEnvironment().getNamespaceContext());
boolean result = super.postProcessResponse();
return result;
}
@Override
public XmlHttpResponse getResponse() {
return (XmlHttpResponse) super.getResponse();
}
@Override
protected XmlHttpResponse createResponse() {
return new XmlHttpResponse();
}
}
|
package com.oreilly.rdf.tenuki.jaxrs;
import java.util.Iterator;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.hp.hpl.jena.rdf.model.Model;
import com.oreilly.rdf.tenuki.Changeset;
import com.oreilly.rdf.tenuki.ChangesetHandler;
@Path("/graphs/")
public class GraphResource extends DatasetAccessResource {
@Produces("text/uri-list")
@GET
public String getGraphsAsURIList() {
StringBuilder urilist = new StringBuilder();
for (Iterator<String> iterator = getDataset().listNames(); iterator
.hasNext();) {
String name = iterator.next();
urilist.append(name);
urilist.append("\r\n");
}
return urilist.toString();
}
@Produces({"application/rdf+xml", "text/turtle", "text/rdf+n3", "text/plain"})
@GET
public Model getGraphByQueryParam(@QueryParam("graph") String graphUri) {
return getDataset().getNamedModel(graphUri);
}
@Path("{graphUri}")
@Produces({"application/rdf+xml", "text/turtle", "text/rdf+n3", "text/plain"})
@GET
public Model getGraph(@PathParam("graphUri") String graphUri) {
return getDataset().getNamedModel(graphUri);
}
@Path("{graphUri}")
@Consumes({"application/rdf+xml", "text/turtle", "text/rdf+n3", "text/plain"})
@POST
public Response updateGraph(@PathParam("graphUri") String graphUri, Model model) {
Model dsModel = getDataset().getNamedModel(graphUri);
try {
if (dsModel.supportsTransactions()) {
dsModel.begin();
}
dsModel.add(model);
dsModel.close();
if (dsModel.supportsTransactions()) {
dsModel.commit();
}
} catch (RuntimeException e) {
if (dsModel.supportsTransactions()) {
dsModel.abort();
}
}
return Response.noContent().build();
}
@Path("{graphUri}")
@Consumes({"application/rdf+xml", "text/turtle", "text/rdf+n3", "text/plain"})
@PUT
public Response setGraph(@PathParam("graphUri") String graphUri, Model model) {
Model dsModel = getDataset().getNamedModel(graphUri);
try {
if (dsModel.supportsTransactions()) {
dsModel.begin();
}
dsModel.removeAll();
dsModel.add(model);
dsModel.close();
if (dsModel.supportsTransactions()) {
dsModel.commit();
}
} catch (RuntimeException e) {
if (dsModel.supportsTransactions()) {
dsModel.abort();
}
}
return Response.noContent().build();
}
@Path("{graphUri}")
@DELETE
public Response deleteGraph(@PathParam("graphUri") String graphUri) {
Model dsModel = getDataset().getNamedModel(graphUri);
try {
if (dsModel.supportsTransactions()) {
dsModel.begin();
}
dsModel.removeAll();
dsModel.close();
if (dsModel.supportsTransactions()) {
dsModel.commit();
}
} catch (RuntimeException e) {
if (dsModel.supportsTransactions()) {
dsModel.abort();
}
}
return Response.noContent().build();
}
@Path("{graphUri}")
@Consumes("application/vnd.talis.changeset+xml")
@PATCH
public Response applyChangesetToGraph(
@PathParam("graphUri") String graphUri, Changeset changeset) {
return applyChangeset(graphUri, changeset);
}
@Path("{graphUri}/patch")
@Consumes("application/vnd.talis.changeset+xml")
@POST
public Response applyChangesetToGraphPost(
@PathParam("graphUri") String graphUri, Changeset changeset) {
return applyChangeset(graphUri, changeset);
}
private Response applyChangeset(String graphUri, Changeset changeset) {
String subject = changeset.getSubjectOfChange().toString();
if ("changes".equals(graphUri) || subject.equals(graphUri)) {
Model dsModel = getDataset().getNamedModel(graphUri);
ChangesetHandler handler = new ChangesetHandler(dsModel);
handler.applyChangeset(changeset);
return Response.ok(dsModel,
MediaType.valueOf("application/rdf+xml")).build();
} else {
return Response.serverError().build();
}
}
}
|
package nl.pvanassen.ns.model.reisadvies;
import java.util.Date;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class ReisStop {
private final String naam;
private final Date tijd;
private final String spoor;
private final boolean gewijzigdVertrekspoor;
ReisStop(String naam, Date tijd, String spoor, boolean gewijzigdVertrekspoor) {
super();
this.naam = naam;
this.tijd = tijd;
this.spoor = spoor;
this.gewijzigdVertrekspoor = gewijzigdVertrekspoor;
}
/**
* @return Station name
*/
public String getNaam() {
return naam;
}
/**
* @return Date and time of arrival
*/
public Date getTijd() {
return tijd;
}
/**
* @return Track if the train stops at the station
*/
public String getSpoor() {
return spoor;
}
/**
* @return True if the departure track has changed for this ride, compared to a normal ride
*/
public boolean isGewijzigdVertrekspoor() {
return gewijzigdVertrekspoor;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package com.siemens.ct.exi.types;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import com.siemens.ct.exi.Constants;
import com.siemens.ct.exi.context.QNameContext;
import com.siemens.ct.exi.datatype.BinaryBase64Datatype;
import com.siemens.ct.exi.datatype.BinaryHexDatatype;
import com.siemens.ct.exi.datatype.BooleanDatatype;
import com.siemens.ct.exi.datatype.Datatype;
import com.siemens.ct.exi.datatype.DatetimeDatatype;
import com.siemens.ct.exi.datatype.DecimalDatatype;
import com.siemens.ct.exi.datatype.FloatDatatype;
import com.siemens.ct.exi.datatype.IntegerDatatype;
import com.siemens.ct.exi.datatype.ListDatatype;
import com.siemens.ct.exi.datatype.StringDatatype;
import com.siemens.ct.exi.exceptions.EXIException;
import com.siemens.ct.exi.util.xml.QNameUtilities;
/**
*
* @author Daniel.Peintner.EXT@siemens.com
* @author Joerg.Heuer@siemens.com
*
* @version 0.9.7-SNAPSHOT
*/
public abstract class AbstractTypeCoder implements TypeCoder {
// DTR maps
protected final QName[] dtrMapTypes;
protected final QName[] dtrMapRepresentations;
protected final Map<QName, Datatype> dtrMapRepresentationsDatatype;
protected Map<QName, Datatype> dtrMap;
protected final boolean dtrMapInUse;
public AbstractTypeCoder() throws EXIException {
this(null, null, null);
}
public AbstractTypeCoder(QName[] dtrMapTypes, QName[] dtrMapRepresentations, Map<QName, Datatype> dtrMapRepresentationsDatatype)
throws EXIException {
this.dtrMapTypes = dtrMapTypes;
this.dtrMapRepresentations = dtrMapRepresentations;
this.dtrMapRepresentationsDatatype = dtrMapRepresentationsDatatype;
if (dtrMapTypes == null) {
dtrMapInUse = false;
} else {
dtrMapInUse = true;
dtrMap = new HashMap<QName, Datatype>();
assert (dtrMapTypes.length == dtrMapRepresentations.length);
this.initDtrMaps();
}
}
private void initDtrMaps() throws EXIException {
assert (dtrMapInUse);
// binary
dtrMap.put(
BuiltIn.XSD_BASE64BINARY,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_BASE64BINARY));
dtrMap.put(
BuiltIn.XSD_HEXBINARY,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_HEXBINARY));
// boolean
dtrMap.put(
BuiltIn.XSD_BOOLEAN,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_BOOLEAN));
// date-times
dtrMap.put(
BuiltIn.XSD_DATETIME,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_DATETIME));
dtrMap.put(
BuiltIn.XSD_TIME,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_TIME));
dtrMap.put(
BuiltIn.XSD_DATE,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_DATE));
dtrMap.put(
BuiltIn.XSD_GYEARMONTH,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_GYEARMONTH));
dtrMap.put(
BuiltIn.XSD_GYEAR,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_GYEAR));
dtrMap.put(
BuiltIn.XSD_GMONTHDAY,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_GMONTHDAY));
dtrMap.put(
BuiltIn.XSD_GDAY,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_GDAY));
dtrMap.put(
BuiltIn.XSD_GMONTH,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_GMONTH));
// decimal
dtrMap.put(
BuiltIn.XSD_DECIMAL,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_DECIMAL));
// float
dtrMap.put(
BuiltIn.XSD_FLOAT,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_DOUBLE));
dtrMap.put(
BuiltIn.XSD_DOUBLE,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_DOUBLE));
// integer
dtrMap.put(
BuiltIn.XSD_INTEGER,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_INTEGER));
// string
dtrMap.put(
BuiltIn.XSD_STRING,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_STRING));
dtrMap.put(
BuiltIn.XSD_ANY_SIMPLE_TYPE,
getDatatypeRepresentation(Constants.W3C_EXI_NS_URI,
Constants.W3C_EXI_LN_STRING));
// all types derived by union are done differently
for (int i = 0; i < dtrMapTypes.length; i++) {
QName dtrMapRepr = dtrMapRepresentations[i];
Datatype representation = getDatatypeRepresentation(
dtrMapRepr.getNamespaceURI(), dtrMapRepr.getLocalPart());
QName type = dtrMapTypes[i];
dtrMap.put(type, representation);
}
}
protected Datatype getDtrDatatype(final Datatype datatype) {
assert (dtrMapInUse);
Datatype dtrDatatype;
if (datatype == BuiltIn.DEFAULT_DATATYPE) {
// e.g., untyped values are encoded always as String
dtrDatatype = datatype;
} else {
// check mappings
QNameContext qncSchemaType = datatype.getSchemaType();
QName schemaType = qncSchemaType.getQName();
dtrDatatype = dtrMap.get(schemaType);
// unions
if (dtrDatatype == null
&& datatype.getBuiltInType() == BuiltInType.STRING
&& ((StringDatatype) datatype).isDerivedByUnion()) {
dtrDatatype = datatype;
// union ancestors of interest
// Datatype dtBase = qncSchemaType.getSimpleBaseDatatype();
Datatype dtBase = datatype.getBaseDatatype();
if (dtBase != null
&& dtBase.getBuiltInType() == BuiltInType.STRING
&& ((StringDatatype) dtBase).isDerivedByUnion()) {
// check again
dtrDatatype = null;
}
}
// lists
if (dtrDatatype == null
&& datatype.getBuiltInType() == BuiltInType.LIST) {
dtrDatatype = datatype;
// list ancestors of interest
// Datatype dtBase = qncSchemaType.getSimpleBaseDatatype();
Datatype dtBase = datatype.getBaseDatatype();
if (dtBase != null
&& dtBase.getBuiltInType() == BuiltInType.LIST) {
// check again
dtrDatatype = null;
}
}
// enums
if (dtrDatatype == null
&& datatype.getBuiltInType() == BuiltInType.ENUMERATION) {
dtrDatatype = datatype;
// only ancestor types that have enums are of interest
// Datatype dtBase = qncSchemaType.getSimpleBaseDatatype();
Datatype dtBase = datatype.getBaseDatatype();
if (dtBase != null
&& dtBase.getBuiltInType() == BuiltInType.ENUMERATION) {
// check again
dtrDatatype = null;
}
}
if (dtrDatatype == null) {
// no mapping yet
// dtrDatatype = updateDtrDatatype(qncSchemaType);
dtrDatatype = updateDtrDatatype(datatype);
// // special integer handling
// if (dtrDatatype.getBuiltInType() == BuiltInType.INTEGER
// && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype
// .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) {
// dtrDatatype = datatype;
// dtrMap.put(qncSchemaType.getQName(), dtrDatatype);
}
}
// list item types
assert (dtrDatatype != null);
if (dtrDatatype.getBuiltInType() == BuiltInType.LIST) {
Datatype prev = dtrDatatype;
ListDatatype ldt = (ListDatatype) dtrDatatype;
Datatype dtList = ldt.getListDatatype();
dtrDatatype = this.getDtrDatatype(dtList);
if (dtrDatatype != dtList) {
// update item codec
dtrDatatype = new ListDatatype(dtrDatatype, ldt.getSchemaType());
} else {
dtrDatatype = prev;
}
}
return dtrDatatype;
}
// protected Datatype updateDtrDatatype(QNameContext qncSchemaType) {
protected Datatype updateDtrDatatype(Datatype datatype) {
// protected Datatype updateDtrDatatype(QNameContext qncSchemaType) {
assert (dtrMapInUse);
// // QNameContext qncSchemaType = datatype.getSchemaType();
// QNameContext qncBase = qncSchemaType.getSimpleBaseType();
// assert(qncSchemaType != null);
//// // special integer handling
//// if (dtrDatatype.getBuiltInType() == BuiltInType.INTEGER
//// && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype
//// .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) {
//// dtrDatatype = datatype;
// Datatype dt = dtrMap.get(qncBase.getQName());
// if (dt == null) {
// // dt = updateDtrDatatype(simpleBaseType);
// // dt = updateDtrDatatype(qncSchemaType.getSimpleBaseDatatype());
// dt = updateDtrDatatype(qncBase); //baseDatatype);
//// dtrMap.put(qncBase.getQName(), dt);
// } else {
// // save new mapping in map
//// dtrMap.put(qncSchemaType.getQName(), dt);
// return dt;
Datatype baseDatatype = datatype.getBaseDatatype();
// QNameContext qncSchemaType = datatype.getSchemaType();
// QNameContext simpleBaseType = qncSchemaType.getSimpleBaseDatatype().getSchemaType();
QNameContext simpleBaseType = baseDatatype.getSchemaType();
Datatype dtrDatatype = dtrMap.get(simpleBaseType.getQName());
if (dtrDatatype == null) {
// dt = updateDtrDatatype(simpleBaseType);
// dt = updateDtrDatatype(qncSchemaType.getSimpleBaseDatatype());
dtrDatatype = updateDtrDatatype(baseDatatype);
}
// special integer handling
if (dtrDatatype.getBuiltInType() == BuiltInType.INTEGER
&& (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype
.getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) {
dtrDatatype = datatype;
}
// save new mapping in map
dtrMap.put(datatype.getSchemaType().getQName(), dtrDatatype);
return dtrDatatype;
}
protected Datatype getDatatypeRepresentation(String reprUri,
String reprLocalPart) throws EXIException {
assert (dtrMapInUse);
try {
// find datatype for given representation
Datatype datatype = null;
if (Constants.W3C_EXI_NS_URI.equals(reprUri)) {
// EXI built-in datatypes
// see http://www.w3.org/TR/exi/#builtInEXITypes
if ("base64Binary".equals(reprLocalPart)) {
datatype = new BinaryBase64Datatype(null);
} else if ("hexBinary".equals(reprLocalPart)) {
datatype = new BinaryHexDatatype(null);
} else if ("boolean".equals(reprLocalPart)) {
datatype = new BooleanDatatype(null);
} else if ("dateTime".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.dateTime, null);
} else if ("time".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.time, null);
} else if ("date".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.date, null);
} else if ("gYearMonth".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.gYearMonth,
null);
} else if ("gYear".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.gYear, null);
} else if ("gMonthDay".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.gMonthDay,
null);
} else if ("gDay".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.gDay, null);
} else if ("gMonth".equals(reprLocalPart)) {
datatype = new DatetimeDatatype(DateTimeType.gMonth, null);
} else if ("decimal".equals(reprLocalPart)) {
datatype = new DecimalDatatype(null);
} else if ("double".equals(reprLocalPart)) {
datatype = new FloatDatatype(null);
} else if ("integer".equals(reprLocalPart)) {
datatype = new IntegerDatatype(null);
} else if ("string".equals(reprLocalPart)) {
datatype = new StringDatatype(null);
} else {
throw new EXIException(
"[EXI] Unsupported datatype representation: {"
+ reprUri + "}" + reprLocalPart);
}
} else {
// try to load datatype
QName qn = new QName(reprUri, reprLocalPart);
if(this.dtrMapRepresentationsDatatype != null) {
datatype = this.dtrMapRepresentationsDatatype.get(qn);
}
if(datatype == null) {
// final try: load class with this qname
String className = QNameUtilities.getClassName(qn);
@SuppressWarnings("rawtypes")
Class c = Class.forName(className);
Object o = c.newInstance();
if (o instanceof Datatype) {
datatype = (Datatype) o;
} else {
throw new Exception("[EXI] no Datatype instance");
}
}
}
return datatype;
} catch (Exception e) {
throw new EXIException(e);
}
}
}
|
package com.stratio.cucumber.testng;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.reflections.Reflections;
import cucumber.api.CucumberOptions;
import cucumber.runtime.ClassFinder;
import cucumber.runtime.RuntimeOptions;
import cucumber.runtime.RuntimeOptionsFactory;
import cucumber.runtime.io.MultiLoader;
import cucumber.runtime.io.ResourceLoader;
import cucumber.runtime.io.ResourceLoaderClassFinder;
public class CucumberRunner {
private final cucumber.runtime.Runtime runtime;
@SuppressWarnings("unused")
public CucumberRunner(Class<?> clazz, String... feature) throws IOException, ClassNotFoundException,
InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ClassLoader classLoader = clazz.getClassLoader();
ResourceLoader resourceLoader = new MultiLoader(classLoader);
RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz,
new Class[] { CucumberOptions.class });
RuntimeOptions runtimeOptions = runtimeOptionsFactory.create();
boolean aux = new File("target/executions/").mkdirs();
CucumberReporter reporterTestNG;
if ((feature.length == 0)) {
reporterTestNG = new CucumberReporter("target/executions/", clazz.getCanonicalName(), "");
} else {
List<String> features = new ArrayList<String>();
String fPath = "src/test/resources/features/" + feature[0] + ".feature";
features.add(fPath);
runtimeOptions.getFeaturePaths().addAll(features);
reporterTestNG = new CucumberReporter("target/executions/", clazz.getCanonicalName(), feature[0]);
}
List<String> uniqueGlue = new ArrayList<String>();
uniqueGlue.add("classpath:com/stratio/specs");
uniqueGlue.add("classpath:com/stratio/sparta/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/gosecsso/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/crossdata/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/streaming/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/ingestion/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/datavis/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/connectors/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/admin/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/explorer/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/manager/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/viewer/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/decision/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/cassandra/lucene/testsAT/specs");
runtimeOptions.getGlue().clear();
runtimeOptions.getGlue().addAll(uniqueGlue);
runtimeOptions.addFormatter(reporterTestNG);
Set<Class<? extends ICucumberFormatter>> implementers = new Reflections("com.stratio.tests.utils")
.getSubTypesOf(ICucumberFormatter.class);
for (Class<? extends ICucumberFormatter> implementerClazz : implementers) {
Constructor<?> ctor = implementerClazz.getConstructor();
ctor.setAccessible(true);
runtimeOptions.addFormatter((ICucumberFormatter) ctor.newInstance());
}
ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
runtime = new cucumber.runtime.Runtime(resourceLoader, classFinder, classLoader, runtimeOptions);
}
/**
* Run the testclases(Features).
*
* @throws IOException
*/
public void runCukes() throws IOException {
runtime.run();
}
}
|
package org.asciidoc.maven;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.asciidoctor.Asciidoctor;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@Mojo(name = "auto-refresh")
public class AsciidoctorRefreshMojo extends AsciidoctorMojo {
@Parameter(property = "port", required = false)
protected int port = 2000;
@Parameter(property = "interval", required = false)
protected int interval = 2000;
private Future<Asciidoctor> asciidoctor = null;
private Collection<FileAlterationMonitor> monitors = null;
private final AtomicBoolean needsUpdate = new AtomicBoolean(false);
private ScheduledExecutorService updaterScheduler = null;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
// this is long because of JRuby startup
createAsciidoctor();
startPolling();
startUpdater();
doWork();
stopUpdater();
stopMonitor();
}
private void stopUpdater() {
if (updaterScheduler != null) {
updaterScheduler.shutdown();
}
}
private void startUpdater() {
updaterScheduler = Executors.newScheduledThreadPool(1);
updaterScheduler.scheduleAtFixedRate(new Updater(needsUpdate, this), interval, interval, TimeUnit.MILLISECONDS);
}
protected void doWork() throws MojoFailureException, MojoExecutionException {
getLog().info("Rendered doc in " + executeAndReturnDuration() + "ms");
doWait();
}
protected void doWait() {
getLog().info("Type [exit|quit] to exit and [refresh] to force a manual re-rendering.");
String line;
final Scanner scanner = new Scanner(System.in);
while ((line = scanner.nextLine()) != null) {
line = line.trim();
if ("exit".equalsIgnoreCase(line) || "quit".equalsIgnoreCase(line)) {
break;
}
if ("refresh".equalsIgnoreCase(line)) {
doExecute();
} else {
getLog().warn("'" + line + "' not understood, available commands are [quit, exit, refresh].");
}
}
}
private void stopMonitor() throws MojoExecutionException {
if (monitors != null) {
for (final FileAlterationMonitor monitor : monitors) {
try {
monitor.stop();
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
}
protected synchronized void doExecute() {
ensureOutputExists();
// delete only content files, resources are synchronized so normally up to date
for (final File f : FileUtils.listFiles(outputDirectory, new RegexFileFilter(ASCIIDOC_REG_EXP_EXTENSION), TrueFileFilter.INSTANCE)) {
FileUtils.deleteQuietly(f);
}
try {
getLog().info("Re-rendered doc in " + executeAndReturnDuration() + "ms");
} catch (final MojoExecutionException e) {
getLog().error(e);
} catch (final MojoFailureException e) {
getLog().error(e);
}
}
protected long executeAndReturnDuration() throws MojoExecutionException, MojoFailureException {
final long start = System.nanoTime();
super.execute();
final long end = System.nanoTime();
return TimeUnit.NANOSECONDS.toMillis(end - start);
}
private void startPolling() throws MojoExecutionException {
monitors = new ArrayList<FileAlterationMonitor>();
{ // content monitor
final FileAlterationObserver observer;
if (sourceDirectory != null) {
observer = new FileAlterationObserver(sourceDirectory, new RegexFileFilter(ASCIIDOC_REG_EXP_EXTENSION));
} else if (sourceDocumentName != null) {
observer = new FileAlterationObserver(sourceDocumentName.getParentFile(), new NameFileFilter(sourceDocumentName.getName()));
} else {
monitors = null; // no need to start anything because there is no content
return;
}
final FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
final FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(final File file) {
getLog().info("File " + file.getAbsolutePath() + " created.");
needsUpdate.set(true);
}
@Override
public void onFileChange(final File file) {
getLog().info("File " + file.getAbsolutePath() + " updated.");
needsUpdate.set(true);
}
@Override
public void onFileDelete(final File file) {
getLog().info("File " + file.getAbsolutePath() + " deleted.");
needsUpdate.set(true);
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitors.add(monitor);
}
{ // resources monitors
if (synchronizations != null) {
for (final Synchronization s : synchronizations) {
final FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
final FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(final File file) {
getLog().info("File " + file.getAbsolutePath() + " created.");
synchronize(s);
needsUpdate.set(true);
}
@Override
public void onFileChange(final File file) {
getLog().info("File " + file.getAbsolutePath() + " updated.");
synchronize(s);
needsUpdate.set(true);
}
@Override
public void onFileDelete(final File file) {
getLog().info("File " + file.getAbsolutePath() + " deleted.");
FileUtils.deleteQuietly(file);
needsUpdate.set(true);
}
};
final File source = s.getSource();
final FileAlterationObserver observer;
if (source.isDirectory()) {
observer = new FileAlterationObserver(source);
} else {
observer = new FileAlterationObserver(source.getParentFile(), new NameFileFilter(source.getName()));
}
observer.addListener(listener);
monitor.addObserver(observer);
monitors.add(monitor);
}
}
}
for (final FileAlterationMonitor monitor : monitors) {
try {
monitor.start();
} catch (final Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
private void createAsciidoctor() {
final ExecutorService es = Executors.newSingleThreadExecutor();
asciidoctor = es.submit(new Callable<Asciidoctor>() {
@Override
public Asciidoctor call() throws Exception {
return Asciidoctor.Factory.create();
}
});
es.shutdown();
}
@Override
protected Asciidoctor getAsciidoctorInstance() throws MojoExecutionException {
try {
return asciidoctor.get();
} catch (final Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private static class Updater implements Runnable {
private final AtomicBoolean run;
private final AsciidoctorRefreshMojo mojo;
private Updater(final AtomicBoolean run, final AsciidoctorRefreshMojo mojo) {
this.run = run;
this.mojo = mojo;
}
@Override
public void run() {
if (run.get()) {
run.set(false);
mojo.doExecute();
}
}
}
}
|
package org.aslak.github.merge.service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import javax.inject.Inject;
import org.aslak.github.merge.Config;
import org.aslak.github.merge.model.Commit;
import org.aslak.github.merge.model.CurrentUser;
import org.aslak.github.merge.model.LocalStorage;
import org.aslak.github.merge.model.PullRequest;
import org.aslak.github.merge.service.NotificationService.Notifier;
import org.aslak.github.merge.service.NotificationService.NotifierProgress;
import org.aslak.github.merge.service.model.Result;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.MergeCommand.FastForwardMode;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.MergeResult;
import org.eclipse.jgit.api.RebaseCommand;
import org.eclipse.jgit.api.RebaseCommand.Operation;
import org.eclipse.jgit.api.RebaseResult;
import org.eclipse.jgit.api.ResetCommand.ResetType;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
public class GitService {
private static final String WORK_FOLDER = Config.tempStorage();
private NotificationService notificationService;
@Inject
public GitService(NotificationService notificationService) {
this.notificationService = notificationService;
}
public OfflineOperations perform(PullRequest request) {
return new Operations(null, request, notificationService);
}
public OnlineOperations perform(LocalStorage storage, PullRequest request) {
return new Operations(storage, request, notificationService);
}
public interface OnlineOperations {
Result<Boolean> doRebase(List<Commit> commits);
Result<List<Commit>> doStatus();
Result<List<Commit>> doPush(CurrentUser user);
}
public interface OfflineOperations {
Result<LocalStorage> doClone();
}
public static class Operations implements OnlineOperations, OfflineOperations {
private LocalStorage storage;
private PullRequest request;
private Notifier notifier;
private NotifierProgress progress;
private NotificationService notification;
public Operations(LocalStorage storage, PullRequest request, NotificationService notification) {
this.storage = storage;
this.request = request;
this.notification = notification;
this.notifier = notification.getNotifier(request.getKey());
this.progress = notification.getNotifierProgress(request.getKey());
}
@Override
public Result<LocalStorage> doClone() {
LocalStorage storage = null;
Git git = null;
try {
storage = repositoryExists();
if(storage == null) {
progress.start("Clone", 3);
git = cloneTargetRepository();
progress.major();
fetchPullRequestBranch(git);
progress.major();
createPullRequestbranch(git);
progress.major();
storage = new LocalStorage(git.getRepository().getWorkTree());
progress.end(true);
}
} catch(Exception e) {
progress.end(false);
notifier.message("Failed to clone due to exception: " + e.getMessage());
return new Result<>(e);
} finally {
close(git);
}
return new Result<>(storage);
}
@Override
public Result<List<Commit>> doStatus() {
Git git = null;
try {
git = open();
return new Result<>(status(git));
} catch(Exception e) {
notifier.message("Failed to get status due to exception: " + e.getMessage());
return new Result<>(new RuntimeException("Could not get status for " + request, e));
} finally {
close(git);
}
}
@Override
public Result<Boolean> doRebase(List<Commit> commits) {
Git git = null;
progress.start("Rebase", 3);
try {
git = open();
progress.major();
checkoutPullRequestBranch(git);
progress.major();
rebaseOnTargetBranch(git, commits);
progress.major();
progress.end(true);
return new Result<>(true);
}
catch(Exception e) {
progress.end(false);
notifier.message("Failed to rebase due to exception: " + e.getMessage());
try {
abortRebase(git);
notifier.message("Rebase aborted");
} catch (Exception e1) {
e1.printStackTrace();
}
return new Result<>(new RuntimeException("Failed to rebase " + request, e));
}
finally {
close(git);
}
}
@Override
public Result<List<Commit>> doPush(CurrentUser user) {
Git git = null;
progress.start("Push", 4);
try {
git = open();
progress.major();
checkoutTargetBranch(git);
progress.major();
List<Commit> commits = mergePullRequestBranchWithTarget(git);
progress.major();
pushTargetBranch(git, user);
progress.major();
progress.end(true);
return new Result<>(commits);
}
catch(Exception e) {
progress.end(false);
notifier.message("Failed to push due to exception: " + e.getMessage());
try {
resetTargetHard(git);
} catch (Exception e1) {
e1.printStackTrace();
}
return new Result<>(new RuntimeException("Failed to merge " + request, e));
}
finally {
close(git);
}
}
private void createPullRequestbranch(Git git) throws Exception {
git.branchCreate()
.setName(String.valueOf(request.getNumber()))
.setStartPoint("origin/pr/" + request.getNumber())
.call();
}
private void fetchPullRequestBranch(Git git) throws Exception {
notification.sendMessage(request.getKey(), "Fetching pull request branch from GitHub");
Repository repository = git.getRepository();
repository.getConfig().setString("remote", "origin", "fetch", "+refs/pull/" + request.getNumber() + "/head:refs/remotes/origin/pr/" + request.getNumber());
repository.getConfig().save();
git.fetch()
.setRemote("origin")
.setProgressMonitor(new NotificationProgressMonitor(request, notification, progress))
.call();
}
private Git cloneTargetRepository() {
File path = calculateRepositoryStoragePath(request);
if(!path.mkdirs()) {
throw new RuntimeException("Could not create path " + path);
}
notifier.message("Cloning repository from GitHub " + request.getTarget().toHttpsURL());
CloneCommand command = Git.cloneRepository()
.setBranch(request.getTarget().getBranch())
.setDirectory(path)
.setURI(request.getTarget().toHttpsURL())
.setProgressMonitor(new NotificationProgressMonitor(request, notification, progress));
try {
return command.call();
} catch(Exception e) {
notifier.message("Failed to clone repository " + e.getMessage());
throw new RuntimeException("Could not clone source repository " + request.getTarget().toHttpsURL(), e);
}
}
private LocalStorage repositoryExists() {
File path = calculateRepositoryStoragePath(request);
if(path.exists() && new File(path, ".git").exists()) {
return new LocalStorage(path);
}
return null;
}
private File calculateRepositoryStoragePath(PullRequest request) {
return Paths.get(WORK_FOLDER, request.getTarget().getUser(), request.getTarget().getRepository(), String.valueOf(request.getNumber())).toFile();
}
private Git open() throws IOException {
return Git.open(storage.getLocation());
}
private void close(Git git) {
if(git != null) {
git.close();
}
}
private void checkoutTargetBranch(Git git) throws Exception {
notifier.message("Checking out pull request branch: " + request.getTarget().getBranch());
git.checkout().setName(String.valueOf(request.getTarget().getBranch())).call();
}
private void checkoutPullRequestBranch(Git git) throws Exception {
notifier.message("Checking out pull request branch: " + request.getTarget().getBranch());
git.checkout().setName(String.valueOf(request.getNumber())).call();
}
private void abortRebase(Git git) throws Exception {
git.rebase().setOperation(Operation.ABORT)
.setProgressMonitor(new NotificationProgressMonitor(request, notification))
.call();
}
private void rebaseOnTargetBranch(Git git, final List<Commit> commits) throws Exception {
RebaseCommand rebase = git.rebase();
rebase.setUpstream(request.getTarget().getBranch());
rebase.setProgressMonitor(new NotificationProgressMonitor(request, notification, progress));
rebase.runInteractively(new GitUtil.InteractiveRebase(notification, request.getKey(), commits));
RebaseResult result = rebase.call();
if(!result.getStatus().isSuccessful()) {
throw new RuntimeException("Rebase not successful, status " + result.getStatus());
}
}
private List<Commit> status(Git git) throws Exception {
ObjectId target = git.getRepository().resolve(request.getTarget().getBranch());
ObjectId source = git.getRepository().resolve(String.valueOf(request.getNumber()));
return GitUtil.toCommitList(git.log().addRange(target, source).call());
}
private List<Commit> mergePullRequestBranchWithTarget(Git git) throws Exception {
notifier.message("Merging source " + request.getNumber() + " into target " + request.getTarget().getBranch());
MergeResult result = git.merge()
.setFastForward(FastForwardMode.FF_ONLY)
.include(git.getRepository().getRef(String.valueOf(request.getNumber())))
.call();
if(!result.getMergeStatus().isSuccessful()) {
throw new RuntimeException("Merge not successfull, status " + result.getMergeStatus());
} else {
notifier.message("Merged " + request + " : " + result.getMergeStatus());
}
return GitUtil.toCommitList(result.getMergedCommits());
}
private void pushTargetBranch(Git git, CurrentUser user) throws Exception {
notifier.message("Pushing to " + request.getTarget().toHttpsURL());
Iterable<PushResult> pushResults = git.push()
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(user.getAccessToken(), new char[0]))
.setRemote("origin")
.setRefSpecs(new RefSpec(request.getTarget().getBranch() + ":" + request.getTarget().getBranch()))
.setProgressMonitor(new NotificationProgressMonitor(request, notification))
.call();
for(PushResult pushResult : pushResults) {
if(pushResult.getMessages() != null && !pushResult.getMessages().isEmpty()) {
notifier.message(pushResult.getMessages());
}
}
notifier.message("Push success");
}
private void resetTargetHard(Git git) throws Exception {
git.reset().setMode(ResetType.HARD)
.setRef("origin/" + request.getTarget().getBranch()).call();
notifier.message("Reset origin/" + request.getTarget().getBranch());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.